getPattern example


class TimestampDatetimeWidget extends WidgetBase {

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    $date_format = DateFormat::load('html_date')->getPattern();
    $time_format = DateFormat::load('html_time')->getPattern();
    $default_value = isset($items[$delta]->value) ? DrupalDateTime::createFromTimestamp($items[$delta]->value) : '';
    $element['value'] = $element + [
      '#type' => 'datetime',
      '#default_value' => $default_value,
      '#date_year_range' => '1902:2037',
    ];

    $element['value']['#description'] = $element['#description'] !== ''
    ? $element['#description']
    : $this->t('Format: %format. Leave blank to use the time of form submission.',
    [

  protected function setUp(): void {
    parent::setUp();
    $this->executeMigration('d6_date_formats');
  }

  /** * Tests the Drupal 6 date formats to Drupal 8 migration. */
  public function testDateFormats() {
    $short_date_format = DateFormat::load('short');
    $this->assertSame('\S\H\O\R\T m/d/Y - H:i', $short_date_format->getPattern());

    $medium_date_format = DateFormat::load('medium');
    $this->assertSame('\M\E\D\I\U\M D, m/d/Y - H:i', $medium_date_format->getPattern());

    $long_date_format = DateFormat::load('long');
    $this->assertSame('\L\O\N\G l, F j, Y - H:i', $long_date_format->getPattern());

    // Test that we can re-import using the EntityDateFormat destination.     Database::getConnection('default', 'migrate')
      ->update('variable')
      ->fields(['value' => serialize('\S\H\O\R\T d/m/Y - H:i')])
      
$element['value']['#description'] = $this->fieldDefinition->getDescription();
    }
    else {
      $element['#theme_wrappers'][] = 'fieldset';
    }

    // Identify the type of date and time elements to use.     switch ($this->getFieldSetting('datetime_type')) {
      case DateTimeItem::DATETIME_TYPE_DATE:
        $date_type = 'date';
        $time_type = 'none';
        $date_format = $this->dateStorage->load('html_date')->getPattern();
        $time_format = '';
        break;

      default:
        $date_type = 'date';
        $time_type = 'time';
        $date_format = $this->dateStorage->load('html_date')->getPattern();
        $time_format = $this->dateStorage->load('html_time')->getPattern();
        break;
    }

    
/** * {@inheritdoc} */
  public function getInfo() {
    $date_format = '';
    $time_format = '';
    // Date formats cannot be loaded during install or update.     if (!defined('MAINTENANCE_MODE')) {
      if ($date_format_entity = DateFormat::load('html_date')) {
        /** @var \Drupal\Core\Datetime\DateFormatInterface $date_format_entity */
        $date_format = $date_format_entity->getPattern();
      }
      if ($time_format_entity = DateFormat::load('html_time')) {
        /** @var \Drupal\Core\Datetime\DateFormatInterface $time_format_entity */
        $time_format = $time_format_entity->getPattern();
      }
    }

    $class = static::class;

    // Note that since this information is cached, the #date_timezone property     // is not set here, as this needs to vary potentially by-user.

  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    $element = parent::formElement($items$delta$element$form$form_state);

    // Identify the type of date and time elements to use.     switch ($this->getFieldSetting('datetime_type')) {
      case DateRangeItem::DATETIME_TYPE_DATE:
      case DateRangeItem::DATETIME_TYPE_ALLDAY:
        $date_type = 'date';
        $time_type = 'none';
        $date_format = $this->dateStorage->load('html_date')->getPattern();
        $time_format = '';
        break;

      default:
        $date_type = 'date';
        $time_type = 'time';
        $date_format = $this->dateStorage->load('html_date')->getPattern();
        $time_format = $this->dateStorage->load('html_time')->getPattern();
        break;
    }

    

class IntlCaster
{
    /** * @return array */
    public static function castMessageFormatter(\MessageFormatter $c, array $a, Stub $stub, bool $isNested)
    {
        $a += [
            Caster::PREFIX_VIRTUAL.'locale' => $c->getLocale(),
            Caster::PREFIX_VIRTUAL.'pattern' => $c->getPattern(),
        ];

        return self::castError($c$a);
    }

    /** * @return array */
    public static function castNumberFormatter(\NumberFormatter $c, array $a, Stub $stub, bool $isNested, int $filter = 0)
    {
        $a += [
            
// ARIA described-by.       $this->assertSession()->elementExists('xpath', '//input[@aria-describedby="edit-' . $field_name . '-0-value--description"]');
      $this->assertSession()->elementExists('xpath', '//div[@id="edit-' . $field_name . '-0-value--description"]');

      // Build up a date in the UTC timezone. Note that using this will also       // mimic the user in a different timezone simply entering '2012-12-31' via       // the UI.       $value = '2012-12-31 00:00:00';
      $date = new DrupalDateTime($value, DateTimeItemInterface::STORAGE_TIMEZONE);

      // Submit a valid date and ensure it is accepted.       $date_format = DateFormat::load('html_date')->getPattern();
      $time_format = DateFormat::load('html_time')->getPattern();

      $edit = [
        "{$field_name}[0][value][date]" => $date->format($date_format),
      ];
      $this->submitForm($edit, 'Save');
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl()$match);
      $id = $match[1];
      $this->assertSession()->pageTextContains('entity_test ' . $id . ' has been created.');
      $this->assertSession()->responseContains($date->format($date_format));
      $this->assertSession()->responseNotContains($date->format($time_format));

      
/** * {@inheritdoc} */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form$form_state);

    // The machine name field should already check to see if the requested     // machine name is available.     $pattern = trim($form_state->getValue('date_format_pattern'));
    foreach ($this->dateFormatStorage->loadMultiple() as $format) {
      if ($format->getPattern() == $pattern && ($format->id() == $this->entity->id())) {
        $this->messenger()->addStatus($this->t('The existing format/name combination has not been altered.'));
        continue;
      }
    }
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setValue('pattern', trim($form_state->getValue('date_format_pattern')));
    


    public function testGetResource()
    {
        $resource = new DirectoryResource($this->directory);
        $this->assertSame(realpath($this->directory)$resource->getResource(), '->getResource() returns the path to the resource');
    }

    public function testGetPattern()
    {
        $resource = new DirectoryResource($this->directory, 'bar');
        $this->assertEquals('bar', $resource->getPattern());
    }

    public function testResourceDoesNotExist()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/The directory ".*" does not exist./');
        new DirectoryResource('/____foo/foobar'.mt_rand(1, 999999));
    }

    public function testIsFresh()
    {
        
$this->flags = $flags;
        return $this;
    }
    
    /** * Returns node's raw value * * @return string */
    public function getRaw()
    {
        return "/" . $this->getPattern() . "/" . $this->getFlags();
    }
    
    /** * Sets node's raw value that must include delimiters * * @param string $raw Raw value * * @return $this */
    public function setRaw($raw)
    {
        
        
// Make sure the "datetime_timestamp" widget is on the page.     $this->assertSession()->elementsCount('xpath', '//div[contains(@class, "field--widget-datetime-timestamp") and @id="edit-field-timestamp-wrapper"]', 1);

    // Look for the widget elements and make sure they are empty.     $this->assertSession()->fieldExists('field_timestamp[0][value][date]');
    $this->assertSession()->fieldValueEquals('field_timestamp[0][value][date]', '');
    $this->assertSession()->fieldExists('field_timestamp[0][value][time]');
    $this->assertSession()->fieldValueEquals('field_timestamp[0][value][time]', '');

    // Submit the date.     $date_format = DateFormat::load('html_date')->getPattern();
    $time_format = DateFormat::load('html_time')->getPattern();

    $edit = [
      'field_timestamp[0][value][date]' => $date->format($date_format),
      'field_timestamp[0][value][time]' => $date->format($time_format),
    ];
    $this->submitForm($edit, 'Save');

    // Make sure the submitted date is set as the default in the widget.     $this->assertSession()->fieldExists('field_timestamp[0][value][date]');
    $this->assertSession()->fieldValueEquals('field_timestamp[0][value][date]', $date->format($date_format));
    
$view->vars['widget'] = $options['widget'];

        // Change the input to an HTML5 date input if         // * the widget is set to "single_text"         // * the format matches the one expected by HTML5         // * the html5 is set to true         if ($options['html5'] && 'single_text' === $options['widget'] && self::HTML5_FORMAT === $options['format']) {
            $view->vars['type'] = 'date';
        }

        if ($form->getConfig()->hasAttribute('formatter')) {
            $pattern = $form->getConfig()->getAttribute('formatter')->getPattern();

            // remove special characters unless the format was explicitly specified             if (!\is_string($options['format'])) {
                // remove quoted strings first                 $pattern = preg_replace('/\'[^\']+\'/', '', $pattern);

                // remove remaining special chars                 $pattern = preg_replace('/[^yMd]+/', '', $pattern);
            }

            // set right order with respect to locale (e.g.: de_DE=dd.MM.yy; en_US=M/d/yy)
    $this->timezones['php initial'] = date_default_timezone_get();
    $user = $this->createUser();
    $user->set('timezone', $this->timezones['user'])->save();
    // This also sets PHP's assumed time.     \Drupal::currentUser()->setAccount($user);

    // Set a reference date to use in tests.     $this->date = new DrupalDatetime('2000-01-01 12:00', NULL);

    // Create arrays listing the dates and times of $this->date formatted     // according to the various timezones of $this->timezones.     $this->dateFormat = DateFormat::load('html_date')->getPattern();
    $this->timeFormat = DateFormat::load('html_time')->getPattern();
    $date = clone $this->date;
    foreach ($this->timezones as $label => $timezone) {
      $date->setTimezone(new \DateTimeZone($timezone));
      $this->formattedDates['date'][$label] = $date->format($this->dateFormat);
      $this->formattedDates['time'][$label] = $date->format($this->timeFormat);
      $this->formattedDates['day'][$label] = $date->format('j');
      $this->formattedDates['month'][$label] = $date->format('n');
      $this->formattedDates['year'][$label] = $date->format('Y');
      $this->formattedDates['hour'][$label] = $date->format('G');
      $this->formattedDates['minute'][$label] = $date->format('i');
      
EOTXT;
        $this->assertDumpEquals($expected$var);
    }

    public function testCastNumberFormatter()
    {
        $var = new \NumberFormatter('en', \NumberFormatter::DECIMAL);

        $expectedLocale = $var->getLocale();
        $expectedPattern = $var->getPattern();

        $expectedAttribute1 = $var->getAttribute(\NumberFormatter::PARSE_INT_ONLY);
        $expectedAttribute2 = $var->getAttribute(\NumberFormatter::GROUPING_USED);
        $expectedAttribute3 = $var->getAttribute(\NumberFormatter::DECIMAL_ALWAYS_SHOWN);
        $expectedAttribute4 = $var->getAttribute(\NumberFormatter::MAX_INTEGER_DIGITS);
        $expectedAttribute5 = $var->getAttribute(\NumberFormatter::MIN_INTEGER_DIGITS);
        $expectedAttribute6 = $var->getAttribute(\NumberFormatter::INTEGER_DIGITS);
        $expectedAttribute7 = $var->getAttribute(\NumberFormatter::MAX_FRACTION_DIGITS);
        $expectedAttribute8 = $var->getAttribute(\NumberFormatter::MIN_FRACTION_DIGITS);
        $expectedAttribute9 = $var->getAttribute(\NumberFormatter::FRACTION_DIGITS);
        $expectedAttribute10 = $var->getAttribute(\NumberFormatter::MULTIPLIER);
        
// Create a DrupalDateTime object from the timestamp and timezone.     $create_settings = [
      'langcode' => $langcode,
      'country' => $this->country(),
    ];
    $date = DrupalDateTime::createFromTimestamp($timestamp$this->timezones[$timezone]$create_settings);

    // If we have a non-custom date format use the provided date format pattern.     if ($type !== 'custom') {
      if ($date_format = $this->dateFormat($type$langcode)) {
        $format = $date_format->getPattern();
      }
    }

    // Fall back to the 'medium' date format type if the format string is     // empty, either from not finding a requested date format or being given an     // empty custom format string.     if (empty($format)) {
      $format = $this->dateFormat('fallback', $langcode)->getPattern();
    }

    // Call $date->format().
Home | Imprint | This part of the site doesn't use cookies.