/**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $default_role_choices = user_role_names(TRUE);
     unset($default_role_choices[DRUPAL_AUTHENTICATED_RID]);
     $roles_config = $this->config('uc_role.settings');
     if (!count($default_role_choices)) {
         $form['no_roles'] = array('#markup' => $this->t('You need to <a href=":url">create new roles</a> before any can be added as product features.', [':url' => Url::fromRoute('user.role_add', [], ['query' => ['destination' => 'admin/store/config/products']])->toString()]), '#prefix' => '<p>', '#suffix' => '</p>');
         return $form;
     }
     $form['default_role'] = array('#type' => 'select', '#title' => $this->t('Default role'), '#default_value' => $roles_config->get('default_role'), '#description' => $this->t('The default role Ubercart grants on specified products.'), '#options' => _uc_role_get_choices());
     $form['default_role_choices'] = array('#type' => 'checkboxes', '#title' => $this->t('Product roles'), '#default_value' => $roles_config->get('default_role_choices'), '#multiple' => TRUE, '#description' => $this->t('These are roles that Ubercart can grant to customers who purchase specified products. If you leave all roles unchecked, they will all be eligible for adding to a product.'), '#options' => $default_role_choices);
     $form['role_lifetime'] = array('#type' => 'fieldset', '#title' => $this->t('Default role expiration'));
     $form['role_lifetime']['default_end_expiration'] = array('#type' => 'select', '#title' => $this->t('Expiration type'), '#options' => array('rel' => $this->t('Relative to purchase date'), 'abs' => $this->t('Fixed date')), '#default_value' => $roles_config->get('default_end_expiration'));
     $form['role_lifetime']['default_length'] = array('#type' => 'textfield', '#default_value' => $roles_config->get('default_granularity') == 'never' ? NULL : $roles_config->get('default_length'), '#size' => 4, '#maxlength' => 4, '#prefix' => '<div class="expiration">', '#suffix' => '</div>', '#states' => array('visible' => array('select[name="default_end_expiration"]' => array('value' => 'rel')), 'invisible' => array('select[name="default_granularity"]' => array('value' => 'never'))));
     $form['role_lifetime']['default_granularity'] = array('#type' => 'select', '#default_value' => $roles_config->get('default_granularity'), '#options' => array('never' => $this->t('never'), 'day' => $this->t('day(s)'), 'week' => $this->t('week(s)'), 'month' => $this->t('month(s)'), 'year' => $this->t('year(s)')), '#description' => $this->t('From the time the role was purchased.'), '#prefix' => '<div class="expiration">', '#suffix' => '</div>', '#states' => array('visible' => array('select[name="default_end_expiration"]' => array('value' => 'rel'))));
     $form['role_lifetime']['absolute'] = array('#type' => 'container', '#states' => array('visible' => array('select[name="default_end_expiration"]' => array('value' => 'abs'))));
     $date = (int) $roles_config->get('default_end_time');
     $date = !empty($date) ? DrupalDateTime::createFromTimestamp($date) : DrupalDateTime::createFromTimestamp(REQUEST_TIME);
     $form['role_lifetime']['absolute']['default_end_time'] = array('#type' => 'datetime', '#description' => $this->t('Expire the role at the beginning of this day.'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => $date);
     $form['role_lifetime']['default_by_quantity'] = array('#type' => 'checkbox', '#title' => $this->t('Multiply by quantity'), '#description' => $this->t('Check if the role duration should be multiplied by the quantity purchased.'), '#default_value' => $roles_config->get('default_by_quantity'));
     $form['reminder']['reminder_length'] = array('#type' => 'textfield', '#title' => $this->t('Time before reminder'), '#default_value' => $roles_config->get('reminder_granularity') == 'never' ? NULL : $roles_config->get('reminder_length'), '#size' => 4, '#maxlength' => 4, '#prefix' => '<div class="expiration">', '#suffix' => '</div>', '#states' => array('disabled' => array('select[name="reminder_granularity"]' => array('value' => 'never'))));
     $form['reminder']['reminder_granularity'] = array('#type' => 'select', '#default_value' => $roles_config->get('reminder_granularity'), '#options' => array('never' => $this->t('never'), 'day' => $this->t('day(s)'), 'week' => $this->t('week(s)'), 'month' => $this->t('month(s)'), 'year' => $this->t('year(s)')), '#description' => $this->t('The amount of time before a role expiration takes place that a customer is notified of its expiration.'), '#prefix' => '<div class="expiration">', '#suffix' => '</div>');
     $form['default_show_expiration'] = array('#type' => 'checkbox', '#title' => $this->t('Show expirations on user page'), '#default_value' => $roles_config->get('default_show_expiration'), '#description' => $this->t('If users have any role expirations they will be displayed on their account page.'));
     return parent::buildForm($form, $form_state);
 }
 /**
  * {@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 + array('#type' => 'datetime', '#default_value' => $default_value, '#date_year_range' => '1902:2037');
     $element['value']['#description'] = $this->t('Format: %format. Leave blank to use the time of form submission.', array('%format' => Datetime::formatExample($date_format . ' ' . $time_format)));
     return $element;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, OrderInterface $uc_order = NULL)
 {
     $balance = uc_payment_balance($uc_order);
     $form['balance'] = array('#prefix' => '<strong>' . $this->t('Order balance:') . '</strong> ', '#markup' => uc_currency_format($balance));
     $form['order_id'] = array('#type' => 'hidden', '#value' => $uc_order->id());
     $form['amount'] = array('#type' => 'uc_price', '#title' => $this->t('Check amount'), '#default_value' => $balance);
     $form['comment'] = array('#type' => 'textfield', '#title' => $this->t('Comment'), '#description' => $this->t('Any notes about the check, like type or check number.'), '#size' => 64, '#maxlength' => 256);
     $form['clear_date'] = array('#type' => 'datetime', '#title' => $this->t('Expected clear date'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => DrupalDateTime::createFromTimestamp(REQUEST_TIME));
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Receive check'));
     return $form;
 }
Exemple #4
0
 /**
  * {@inheritdoc}
  */
 protected function prepareValue($delta, array &$values)
 {
     $date = FALSE;
     $value = trim($values['value']);
     if (is_numeric($value) || is_string($value) && ($value = strtotime($value))) {
         $date = DrupalDateTime::createFromTimestamp($value, DATETIME_STORAGE_TIMEZONE);
     } elseif ($value instanceof \DateTime) {
         $date = DrupalDateTime::createFromDateTime($value);
     }
     if ($date && !$date->hasErrors()) {
         $values['value'] = $date->format($this->storageFormat);
     } else {
         $values['value'] = '';
     }
 }
Exemple #5
0
 /**
  * {@inheritdoc}
  */
 protected function prepareValue($delta, array &$values)
 {
     $value = trim($values['value']);
     // This is a year value.
     if (ctype_digit($value) && strlen($value) === 4) {
         $value = 'January ' . $value;
     }
     if (is_numeric($value) || ($value = strtotime($value))) {
         $date = DrupalDateTime::createFromTimestamp($value, DATETIME_STORAGE_TIMEZONE);
     }
     if (isset($date) && !$date->hasErrors()) {
         $values['value'] = $date->format($this->storageFormat);
     } else {
         $values['value'] = '';
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $args = NULL)
 {
     if (!isset($args['start_date'])) {
         $args['start_date'] = REQUEST_TIME;
     }
     if (!isset($args['end_date'])) {
         $args['end_date'] = REQUEST_TIME;
     }
     if (!isset($args['statuses'])) {
         $args['statuses'] = uc_report_order_statuses();
     }
     $form['params'] = array('#type' => 'fieldset', '#title' => $this->t('Customize tax report parameters'), '#description' => $this->t('Adjust these values and update the report to build your sales tax report. Once submitted, the report may be bookmarked for easy reference in the future.'));
     $form['params']['start_date'] = array('#type' => 'datetime', '#title' => $this->t('Start date'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => DrupalDateTime::createFromTimestamp($args['start_date']));
     $form['params']['end_date'] = array('#type' => 'datetime', '#title' => $this->t('End date'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => DrupalDateTime::createFromTimestamp($args['end_date']));
     $form['params']['statuses'] = array('#type' => 'select', '#title' => $this->t('Order statuses'), '#description' => $this->t('Only orders with selected statuses will be included in the report.') . '<br />' . $this->t('Hold Ctrl + click to select multiple statuses.'), '#options' => OrderStatus::getOptionsList(), '#default_value' => $args['statuses'], '#multiple' => TRUE, '#size' => 5);
     $form['params']['actions'] = array('#type' => 'actions');
     $form['params']['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Update report'));
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /** @var \Drupal\comment\CommentInterface $comment */
     $comment = $this->entity;
     $entity = $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
     $field_name = $comment->getFieldName();
     $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
     $config = $this->config('user.settings');
     // In several places within this function, we vary $form on:
     // - The current user's permissions.
     // - Whether the current user is authenticated or anonymous.
     // - The 'user.settings' configuration.
     // - The comment field's definition.
     $form['#cache']['contexts'][] = 'user.permissions';
     $form['#cache']['contexts'][] = 'user.roles:authenticated';
     $this->renderer->addCacheableDependency($form, $config);
     $this->renderer->addCacheableDependency($form, $field_definition->getConfig($entity->bundle()));
     // Use #comment-form as unique jump target, regardless of entity type.
     $form['#id'] = Html::getUniqueId('comment_form');
     $form['#theme'] = array('comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form');
     $anonymous_contact = $field_definition->getSetting('anonymous');
     $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
     if (!$this->currentUser->isAuthenticated() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
         $form['#attached']['library'][] = 'core/drupal.form';
         $form['#attributes']['data-user-info-from-browser'] = TRUE;
     }
     // If not replying to a comment, use our dedicated page callback for new
     // Comments on entities.
     if (!$comment->id() && !$comment->hasParentComment()) {
         $form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));
     }
     $comment_preview = $form_state->get('comment_preview');
     if (isset($comment_preview)) {
         $form += $comment_preview;
     }
     $form['author'] = array();
     // Display author information in a details element for comment moderators.
     if ($is_admin) {
         $form['author'] += array('#type' => 'details', '#title' => $this->t('Administration'));
     }
     // Prepare default values for form elements.
     $author = '';
     if ($is_admin) {
         if (!$comment->getOwnerId()) {
             $author = $comment->getAuthorName();
         }
         $status = $comment->getStatus();
         if (empty($comment_preview)) {
             $form['#title'] = $this->t('Edit comment %title', array('%title' => $comment->getSubject()));
         }
     } else {
         $status = $this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
     }
     $date = '';
     if ($comment->id()) {
         $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
     }
     // The uid field is only displayed when a user with the permission
     // 'administer comments' is editing an existing comment from an
     // authenticated user.
     $owner = $comment->getOwner();
     $form['author']['uid'] = ['#type' => 'entity_autocomplete', '#target_type' => 'user', '#default_value' => $owner->isAnonymous() ? NULL : $owner, '#selection_settings' => ['include_anonymous' => FALSE], '#title' => $this->t('Authored by'), '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]), '#access' => $is_admin];
     // The name field is displayed when an anonymous user is adding a comment or
     // when a user with the permission 'administer comments' is editing an
     // existing comment from an anonymous user.
     $form['author']['name'] = array('#type' => 'textfield', '#title' => $is_admin ? $this->t('Name for @anonymous', ['@anonymous' => $config->get('anonymous')]) : $this->t('Your name'), '#default_value' => $author, '#required' => $this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT, '#maxlength' => 60, '#access' => $this->currentUser->isAnonymous() || $is_admin, '#size' => 30, '#attributes' => ['data-drupal-default-value' => $config->get('anonymous')]);
     if ($is_admin) {
         // When editing a comment only display the name textfield if the uid field
         // is empty.
         $form['author']['name']['#states'] = ['visible' => [':input[name="uid"]' => array('empty' => TRUE)]];
     }
     // Add author email and homepage fields depending on the current user.
     $form['author']['mail'] = array('#type' => 'email', '#title' => $this->t('Email'), '#default_value' => $comment->getAuthorEmail(), '#required' => $this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT, '#maxlength' => 64, '#size' => 30, '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'), '#access' => $comment->getOwner()->isAnonymous() && $is_admin || $this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT);
     $form['author']['homepage'] = array('#type' => 'url', '#title' => $this->t('Homepage'), '#default_value' => $comment->getHomepage(), '#maxlength' => 255, '#size' => 30, '#access' => $is_admin || $this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT);
     // Add administrative comment publishing options.
     $form['author']['date'] = array('#type' => 'datetime', '#title' => $this->t('Authored on'), '#default_value' => $date, '#size' => 20, '#access' => $is_admin);
     $form['author']['status'] = array('#type' => 'radios', '#title' => $this->t('Status'), '#default_value' => $status, '#options' => array(CommentInterface::PUBLISHED => $this->t('Published'), CommentInterface::NOT_PUBLISHED => $this->t('Not published')), '#access' => $is_admin);
     return parent::form($form, $form_state, $comment);
 }
 /**
  * Tests date and time field.
  */
 function testDatetimeField()
 {
     $field_name = $this->fieldStorage->getName();
     // Change the field to a datetime field.
     $this->fieldStorage->setSetting('datetime_type', 'datetime');
     $this->fieldStorage->save();
     // Display creation form.
     $this->drupalGet('entity_test/add');
     $this->assertFieldByName("{$field_name}[0][value][date]", '', 'Date element found.');
     $this->assertFieldByName("{$field_name}[0][value][time]", '', 'Time element found.');
     // Build up a date in the UTC timezone.
     $value = '2012-12-31 00:00:00';
     $date = new DrupalDateTime($value, 'UTC');
     // Update the timezone to the system default.
     $date->setTimezone(timezone_open(drupal_get_user_timezone()));
     // Submit a valid date and ensure it is accepted.
     $date_format = entity_load('date_format', 'html_date')->getPattern();
     $time_format = entity_load('date_format', 'html_time')->getPattern();
     $edit = array("{$field_name}[0][value][date]" => $date->format($date_format), "{$field_name}[0][value][time]" => $date->format($time_format));
     $this->drupalPostForm(NULL, $edit, t('Save'));
     preg_match('|entity_test/manage/(\\d+)|', $this->url, $match);
     $id = $match[1];
     $this->assertText(t('entity_test @id has been created.', array('@id' => $id)));
     $this->assertRaw($date->format($date_format));
     $this->assertRaw($date->format($time_format));
     // Verify that the date is output according to the formatter settings.
     $options = array('format_type' => array('short', 'medium', 'long'));
     foreach ($options as $setting => $values) {
         foreach ($values as $new_value) {
             // Update the entity display settings.
             $this->displayOptions['settings'] = array($setting => $new_value) + $this->defaultSettings;
             entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save();
             $this->renderTestEntity($id);
             switch ($setting) {
                 case 'format_type':
                     // Verify that a date is displayed.
                     $expected = format_date($date->getTimestamp(), $new_value);
                     $this->renderTestEntity($id);
                     $this->assertText($expected, SafeMarkup::format('Formatted date field using %value format displayed as %expected.', array('%value' => $new_value, '%expected' => $expected)));
                     break;
             }
         }
     }
     // Verify that the plain formatter works.
     $this->displayOptions['type'] = 'datetime_plain';
     $this->displayOptions['settings'] = $this->defaultSettings;
     entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save();
     $expected = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);
     $this->renderTestEntity($id);
     $this->assertText($expected, SafeMarkup::format('Formatted date field using plain format displayed as %expected.', array('%expected' => $expected)));
     // Verify that the 'datetime_custom' formatter works.
     $this->displayOptions['type'] = 'datetime_custom';
     $this->displayOptions['settings'] = array('date_format' => 'm/d/Y g:i:s A') + $this->defaultSettings;
     entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save();
     $expected = $date->format($this->displayOptions['settings']['date_format']);
     $this->renderTestEntity($id);
     $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', array('%expected' => $expected)));
     // Verify that the 'timezone_override' setting works.
     $this->displayOptions['type'] = 'datetime_custom';
     $this->displayOptions['settings'] = array('date_format' => 'm/d/Y g:i:s A', 'timezone_override' => 'America/New_York') + $this->defaultSettings;
     entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save();
     $expected = $date->format($this->displayOptions['settings']['date_format'], array('timezone' => 'America/New_York'));
     $this->renderTestEntity($id);
     $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_custom format displayed as %expected.', array('%expected' => $expected)));
     // Verify that the 'datetime_time_ago' formatter works for intervals in the
     // past.  First update the test entity so that the date difference always
     // has the same interval.  Since the database always stores UTC, and the
     // interval will use this, force the test date to use UTC and not the local
     // or user timezome.
     $timestamp = REQUEST_TIME - 87654321;
     $entity = entity_load('entity_test', $id);
     $field_name = $this->fieldStorage->getName();
     $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
     $entity->{$field_name}->value = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);
     $entity->save();
     $this->displayOptions['type'] = 'datetime_time_ago';
     $this->displayOptions['settings'] = array('future_format' => '@interval from now', 'past_format' => '@interval earlier', 'granularity' => 3);
     entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save();
     $expected = SafeMarkup::format($this->displayOptions['settings']['past_format'], ['@interval' => \Drupal::service('date.formatter')->formatTimeDiffSince($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])]);
     $this->renderTestEntity($id);
     $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected)));
     // Verify that the 'datetime_time_ago' formatter works for intervals in the
     // future.  First update the test entity so that the date difference always
     // has the same interval.  Since the database always stores UTC, and the
     // interval will use this, force the test date to use UTC and not the local
     // or user timezome.
     $timestamp = REQUEST_TIME + 87654321;
     $entity = entity_load('entity_test', $id);
     $field_name = $this->fieldStorage->getName();
     $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
     $entity->{$field_name}->value = $date->format(DATETIME_DATETIME_STORAGE_FORMAT);
     $entity->save();
     entity_get_display($this->field->getTargetEntityTypeId(), $this->field->getTargetBundle(), 'full')->setComponent($field_name, $this->displayOptions)->save();
     $expected = SafeMarkup::format($this->displayOptions['settings']['future_format'], ['@interval' => \Drupal::service('date.formatter')->formatTimeDiffUntil($timestamp, ['granularity' => $this->displayOptions['settings']['granularity']])]);
     $this->renderTestEntity($id);
     $this->assertText($expected, SafeMarkup::format('Formatted date field using datetime_time_ago format displayed as %expected.', array('%expected' => $expected)));
 }
 /**
  * {@inheritdoc}
  */
 public function getCreatedTime()
 {
     return DrupalDateTime::createFromTimestamp($this->get('created')->value);
 }
 /**
  * Overrides Drupal\Core\Entity\EntityForm::form().
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     /** @var \Drupal\comment\CommentInterface $comment */
     $comment = $this->entity;
     $entity = $this->entityManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
     $field_name = $comment->getFieldName();
     $field_definition = $this->entityManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle())[$comment->getFieldName()];
     // Use #comment-form as unique jump target, regardless of entity type.
     $form['#id'] = drupal_html_id('comment_form');
     $form['#theme'] = array('comment_form__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name, 'comment_form');
     $anonymous_contact = $field_definition->getSetting('anonymous');
     $is_admin = $comment->id() && $this->currentUser->hasPermission('administer comments');
     if (!$this->currentUser->isAuthenticated() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
         $form['#attached']['library'][] = 'core/drupal.form';
         $form['#attributes']['data-user-info-from-browser'] = TRUE;
     }
     // If not replying to a comment, use our dedicated page callback for new
     // Comments on entities.
     if (!$comment->id() && !$comment->hasParentComment()) {
         $form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));
     }
     $comment_preview = $form_state->get('comment_preview');
     if (isset($comment_preview)) {
         $form += $comment_preview;
     }
     $form['author'] = array();
     // Display author information in a details element for comment moderators.
     if ($is_admin) {
         $form['author'] += array('#type' => 'details', '#title' => $this->t('Administration'));
     }
     // Prepare default values for form elements.
     if ($is_admin) {
         $author = $comment->getAuthorName();
         $status = $comment->getStatus();
         if (empty($comment_preview)) {
             $form['#title'] = $this->t('Edit comment %title', array('%title' => $comment->getSubject()));
         }
     } else {
         if ($this->currentUser->isAuthenticated()) {
             $author = $this->currentUser->getUsername();
         } else {
             $author = $comment->getAuthorName() ? $comment->getAuthorName() : '';
         }
         $status = $this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED;
     }
     $date = '';
     if ($comment->id()) {
         $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
     }
     // Add the author name field depending on the current user.
     $form['author']['name'] = array('#type' => 'textfield', '#title' => $this->t('Your name'), '#default_value' => $author, '#required' => $this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT, '#maxlength' => 60, '#size' => 30);
     if ($is_admin) {
         $form['author']['name']['#title'] = $this->t('Authored by');
         $form['author']['name']['#description'] = $this->t('Leave blank for %anonymous.', array('%anonymous' => $this->config('user.settings')->get('anonymous')));
         $form['author']['name']['#autocomplete_route_name'] = 'user.autocomplete';
     } elseif ($this->currentUser->isAuthenticated()) {
         $form['author']['name']['#type'] = 'item';
         $form['author']['name']['#value'] = $form['author']['name']['#default_value'];
         $form['author']['name']['#theme'] = 'username';
         $form['author']['name']['#account'] = $this->currentUser;
     } elseif ($this->currentUser->isAnonymous()) {
         $form['author']['name']['#attributes']['data-drupal-default-value'] = $this->config('user.settings')->get('anonymous');
     }
     $language_configuration = \Drupal::moduleHandler()->invoke('language', 'get_default_configuration', array('comment', $comment->getTypeId()));
     $form['langcode'] = array('#title' => t('Language'), '#type' => 'language_select', '#default_value' => $comment->getUntranslated()->language()->getId(), '#languages' => Language::STATE_ALL, '#access' => isset($language_configuration['language_show']) && $language_configuration['language_show']);
     // Add author email and homepage fields depending on the current user.
     $form['author']['mail'] = array('#type' => 'email', '#title' => $this->t('Email'), '#default_value' => $comment->getAuthorEmail(), '#required' => $this->currentUser->isAnonymous() && $anonymous_contact == COMMENT_ANONYMOUS_MUST_CONTACT, '#maxlength' => 64, '#size' => 30, '#description' => $this->t('The content of this field is kept private and will not be shown publicly.'), '#access' => $is_admin || $this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT);
     $form['author']['homepage'] = array('#type' => 'url', '#title' => $this->t('Homepage'), '#default_value' => $comment->getHomepage(), '#maxlength' => 255, '#size' => 30, '#access' => $is_admin || $this->currentUser->isAnonymous() && $anonymous_contact != COMMENT_ANONYMOUS_MAYNOT_CONTACT);
     // Add administrative comment publishing options.
     $form['author']['date'] = array('#type' => 'datetime', '#title' => $this->t('Authored on'), '#default_value' => $date, '#size' => 20, '#access' => $is_admin);
     $form['author']['status'] = array('#type' => 'radios', '#title' => $this->t('Status'), '#default_value' => $status, '#options' => array(CommentInterface::PUBLISHED => $this->t('Published'), CommentInterface::NOT_PUBLISHED => $this->t('Not published')), '#access' => $is_admin);
     // Used for conditional validation of author fields.
     $form['is_anonymous'] = array('#type' => 'value', '#value' => $comment->id() ? !$comment->getOwnerId() : $this->currentUser->isAnonymous());
     return parent::form($form, $form_state, $comment);
 }
Exemple #11
0
 /**
  * {@inheritdoc}
  */
 public function getDateTime()
 {
     if ($this->value) {
         return DrupalDateTime::createFromTimestamp($this->value);
     }
 }
 /**
  * Formats the date for display.
  */
 function getDateFormatted()
 {
     return is_numeric($this->getDate()) ? DrupalDateTime::createFromTimestamp($this->getDate()) : $this->t('Not configured');
 }
 /**
  * Tests the ability to override the time zone in the format method.
  */
 function testTimezoneFormat()
 {
     // Create a date in UTC
     $date = DrupalDateTime::createFromTimestamp(87654321, 'UTC');
     // Verify that the date format method displays the default time zone.
     $this->assertEqual($date->format('Y/m/d H:i:s e'), '1972/10/11 12:25:21 UTC', 'Date has default UTC time zone and correct date/time.');
     // Verify that the format method can override the time zone.
     $this->assertEqual($date->format('Y/m/d H:i:s e', array('timezone' => 'America/New_York')), '1972/10/11 08:25:21 America/New_York', 'Date displayed overidden time zone and correct date/time');
     // Verify that the date format method still displays the default time zone
     // for the date object.
     $this->assertEqual($date->format('Y/m/d H:i:s e'), '1972/10/11 12:25:21 UTC', 'Date still has default UTC time zone and correct date/time');
 }
 /**
  * Collect additional information for the "Cash on Delivery" payment method.
  */
 protected function deliveryDateForm($order)
 {
     $delivery_date = empty($order->payment_details['delivery_date']) ? DrupalDateTime::createFromTimestamp(REQUEST_TIME) : DrupalDateTime::createFromTimestamp($order->payment_details['delivery_date']);
     $form['delivery_date'] = array('#type' => 'datetime', '#title' => $this->t('Enter a desired delivery date:'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#prefix' => '<div>', '#suffix' => '</div>', '#default_value' => $delivery_date);
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, OrderInterface $uc_order = NULL, $shipment = NULL)
 {
     // Sometimes $shipment is an ID, sometimes it's an object. FIX THIS! @todo
     if (!is_object($shipment)) {
         // Then $shipment is an ID.
         $shipment = Shipment::load($shipment);
     } elseif (isset($shipment->sid)) {
         $form['sid'] = array('#type' => 'value', '#value' => $shipment->sid);
         $shipment = Shipment::load($shipment->sid);
         $methods = \Drupal::moduleHandler()->invokeAll('uc_fulfillment_method');
         if (isset($methods[$shipment->shipping_method])) {
             $method = $methods[$shipment->shipping_method];
         }
     }
     $form['order_id'] = array('#type' => 'value', '#value' => $uc_order->id());
     $addresses = array();
     $form['packages'] = array('#type' => 'fieldset', '#title' => $this->t('Packages'), '#tree' => TRUE);
     if (isset($shipment->o_street1)) {
         $o_address = new \stdClass();
         foreach ($shipment as $field => $value) {
             if (substr($field, 0, 2) == 'o_') {
                 $o_address->{substr($field, 2)} = $value;
             }
         }
         $addresses[] = (object) $o_address;
     }
     foreach ($shipment->packages as $id => $package) {
         foreach ($package->addresses as $address) {
             if (!in_array($address, $addresses)) {
                 $addresses[] = (object) $address;
             }
         }
         // Create list of products and get a representative product (last one in
         // the loop) to use for some default values
         $product_list = array();
         $declared_value = 0;
         foreach ($package->products as $product) {
             $product_list[] = $product->qty . ' x ' . $product->model;
             $declared_value += $product->qty * $product->price;
         }
         $pkg_form = array('#type' => 'fieldset', '#title' => $this->t('Package @id', ['@id' => $id]));
         $pkg_form['products'] = array('#theme' => 'item_list', '#items' => $product_list);
         $pkg_form['pkg_type'] = array('#type' => 'textfield', '#title' => $this->t('Package type'), '#default_value' => $package->pkg_type, '#description' => $this->t('For example: Box, pallet, tube, envelope, etc.'));
         if (isset($method) && is_array($method['ship']['pkg_types'])) {
             $pkg_form['pkg_type']['#type'] = 'select';
             $pkg_form['pkg_type']['#options'] = $method['ship']['pkg_types'];
             $pkg_form['pkg_type']['#description'] = '';
         }
         $pkg_form['declared_value'] = array('#type' => 'uc_price', '#title' => $this->t('Declared value'), '#default_value' => isset($package->value) ? $package->value : $declared_value);
         $pkg_form['weight'] = array('#type' => 'container', '#attributes' => array('class' => array('uc-inline-form', 'clearfix')), '#description' => $this->t('Weight of the package. Default value is sum of product weights in the package.'), '#weight' => 15);
         $pkg_form['weight']['weight'] = array('#type' => 'number', '#title' => $this->t('Weight'), '#min' => 0, '#step' => 'any', '#default_value' => isset($package->weight) ? $package->weight : 0, '#size' => 10);
         $pkg_form['weight']['units'] = array('#type' => 'select', '#title' => $this->t('Units'), '#options' => array('lb' => $this->t('Pounds'), 'kg' => $this->t('Kilograms'), 'oz' => $this->t('Ounces'), 'g' => $this->t('Grams')), '#default_value' => isset($package->weight_units) ? $package->weight_units : \Drupal::config('uc_store.settings')->get('weight.units'));
         $pkg_form['dimensions'] = array('#type' => 'container', '#attributes' => array('class' => array('uc-inline-form', 'clearfix')), '#title' => $this->t('Dimensions'), '#description' => $this->t('Physical dimensions of the packaged product.'), '#weight' => 20);
         $pkg_form['dimensions']['length'] = array('#type' => 'number', '#title' => $this->t('Length'), '#min' => 0, '#step' => 'any', '#default_value' => isset($package->length) ? $package->length : 1, '#size' => 8);
         $pkg_form['dimensions']['width'] = array('#type' => 'number', '#title' => $this->t('Width'), '#min' => 0, '#step' => 'any', '#default_value' => isset($package->width) ? $package->width : 1, '#size' => 8);
         $pkg_form['dimensions']['height'] = array('#type' => 'number', '#title' => $this->t('Height'), '#min' => 0, '#step' => 'any', '#default_value' => isset($package->height) ? $package->height : 1, '#size' => 8);
         $pkg_form['dimensions']['units'] = array('#type' => 'select', '#title' => $this->t('Units of measurement'), '#options' => array('in' => $this->t('Inches'), 'ft' => $this->t('Feet'), 'cm' => $this->t('Centimeters'), 'mm' => $this->t('Millimeters')), '#default_value' => isset($package->length_units) ? $package->length_units : \Drupal::config('uc_store.settings')->get('length.units'));
         $pkg_form['tracking_number'] = array('#type' => 'textfield', '#title' => $this->t('Tracking number'), '#default_value' => isset($package->tracking_number) ? $package->tracking_number : '');
         $form['packages'][$id] = $pkg_form;
     }
     if (!empty($shipment->d_street1)) {
         foreach ($shipment as $field => $value) {
             if (substr($field, 0, 2) == 'd_') {
                 $uc_order->{'delivery_' . substr($field, 2)} = $value;
             }
         }
     }
     $form += \Drupal::formBuilder()->getForm('\\Drupal\\uc_fulfillment\\Form\\AddressForm', $addresses, $uc_order);
     $form['shipment'] = array('#type' => 'fieldset', '#title' => $this->t('Shipment data'));
     // Determine shipping option chosen by the customer.
     $message = '';
     if (isset($uc_order->quote['method'])) {
         // Order has a quote attached.
         $method = $uc_order->quote['method'];
         $methods = \Drupal::moduleHandler()->invokeAll('uc_fulfillment_method');
         if (isset($methods[$method])) {
             // Quote is from a currently-active shipping method.
             $services = $methods[$method]['quote']['accessorials'];
             $method = $services[$uc_order->quote['accessorials']];
         }
         $message = $this->t('Customer selected "@method" as the shipping method and paid @rate', ['@method' => $method, '@rate' => uc_currency_format($uc_order->quote['rate'])]);
     } else {
         // No quotes for this order.
         $message = $this->t('There are no shipping quotes attached to this order. Customer was not charged for shipping.');
     }
     // Inform administrator of customer's shipping choice.
     $form['shipment']['shipping_choice'] = array('#type' => 'container', '#markup' => $message);
     $form['shipment']['shipping_method'] = array('#type' => 'hidden', '#value' => isset($shipment->shipping_method) ? $shipment->shipping_method : 'manual');
     $form['shipment']['carrier'] = array('#type' => 'textfield', '#title' => $this->t('Carrier'), '#default_value' => isset($shipment->carrier) ? $shipment->carrier : '');
     $form['shipment']['accessorials'] = array('#type' => 'textfield', '#title' => $this->t('Shipment options'), '#default_value' => isset($shipment->accessorials) ? $shipment->accessorials : '', '#description' => $this->t('Short notes about the shipment, e.g. residential, overnight, etc.'));
     $form['shipment']['transaction_id'] = array('#type' => 'textfield', '#title' => $this->t('Transaction ID'), '#default_value' => isset($shipment->transaction_id) ? $shipment->transaction_id : '');
     $form['shipment']['tracking_number'] = array('#type' => 'textfield', '#title' => $this->t('Tracking number'), '#default_value' => isset($shipment->tracking_number) ? $shipment->tracking_number : '');
     $ship_date = REQUEST_TIME;
     if (isset($shipment->ship_date)) {
         $ship_date = $shipment->ship_date;
     }
     $exp_delivery = REQUEST_TIME;
     if (isset($shipment->expected_delivery)) {
         $exp_delivery = $shipment->expected_delivery;
     }
     $form['shipment']['ship_date'] = array('#type' => 'datetime', '#title' => $this->t('Ship date'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => DrupalDateTime::createFromTimestamp($ship_date));
     $form['shipment']['expected_delivery'] = array('#type' => 'datetime', '#title' => $this->t('Expected delivery'), '#date_date_element' => 'date', '#date_time_element' => 'none', '#default_value' => DrupalDateTime::createFromTimestamp($exp_delivery));
     $form['shipment']['cost'] = array('#type' => 'uc_price', '#title' => $this->t('Shipping cost'), '#default_value' => isset($shipment->cost) ? $shipment->cost : 0);
     $form['actions'] = array('#type' => 'actions');
     $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save shipment'), '#weight' => 10);
     return $form;
 }
Exemple #16
0
 /**
  * Tests the basics around constructing and working with typed data objects.
  */
 public function testGetAndSet()
 {
     // Boolean type.
     $typed_data = $this->createTypedData(array('type' => 'boolean'), TRUE);
     $this->assertTrue($typed_data instanceof BooleanInterface, 'Typed data object is an instance of BooleanInterface.');
     $this->assertTrue($typed_data->getValue() === TRUE, 'Boolean value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(FALSE);
     $this->assertTrue($typed_data->getValue() === FALSE, 'Boolean value was changed.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $this->assertTrue(is_string($typed_data->getString()), 'Boolean value was converted to string');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Boolean wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // String type.
     $value = $this->randomString();
     $typed_data = $this->createTypedData(array('type' => 'string'), $value);
     $this->assertTrue($typed_data instanceof StringInterface, 'Typed data object is an instance of StringInterface.');
     $this->assertTrue($typed_data->getValue() === $value, 'String value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = $this->randomString();
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'String value was changed.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // Funky test.
     $this->assertTrue(is_string($typed_data->getString()), 'String value was converted to string');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'String wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(array('no string'));
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Integer type.
     $value = rand();
     $typed_data = $this->createTypedData(array('type' => 'integer'), $value);
     $this->assertTrue($typed_data instanceof IntegerInterface, 'Typed data object is an instance of IntegerInterface.');
     $this->assertTrue($typed_data->getValue() === $value, 'Integer value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = rand();
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'Integer value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Integer value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Integer wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Float type.
     $value = 123.45;
     $typed_data = $this->createTypedData(array('type' => 'float'), $value);
     $this->assertTrue($typed_data instanceof FloatInterface, 'Typed data object is an instance of FloatInterface.');
     $this->assertTrue($typed_data->getValue() === $value, 'Float value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = 678.9;
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'Float value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Float value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Float wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Date Time type.
     $value = '2014-01-01T20:00:00+00:00';
     $typed_data = $this->createTypedData(array('type' => 'datetime_iso8601'), $value);
     $this->assertTrue($typed_data instanceof DateTimeInterface, 'Typed data object is an instance of DateTimeInterface.');
     $this->assertTrue($typed_data->getValue() == $value, 'Date value was fetched.');
     $this->assertEqual($typed_data->getValue(), $typed_data->getDateTime()->format('c'), 'Value representation of a date is ISO 8601');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = '2014-01-02T20:00:00+00:00';
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getDateTime()->format('c') === $new_value, 'Date value was changed and set by an ISO8601 date.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $this->assertTrue($typed_data->getDateTime()->format('Y-m-d') == '2014-01-02', 'Date value was changed and set by date string.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime(), 'Date wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DateTimeInterface.
     $typed_data = $this->createTypedData(array('type' => 'datetime_iso8601'), '2014-01-01T20:00:00+00:00');
     $this->assertTrue($typed_data->getDateTime() instanceof DrupalDateTime);
     $typed_data->setDateTime(new DrupalDateTime('2014-01-02T20:00:00+00:00'));
     $this->assertEqual($typed_data->getValue(), '2014-01-02T20:00:00+00:00');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime());
     // Timestamp type.
     $value = REQUEST_TIME;
     $typed_data = $this->createTypedData(array('type' => 'timestamp'), $value);
     $this->assertTrue($typed_data instanceof DateTimeInterface, 'Typed data object is an instance of DateTimeInterface.');
     $this->assertTrue($typed_data->getValue() == $value, 'Timestamp value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = REQUEST_TIME + 1;
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'Timestamp value was changed and set.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime(), 'Timestamp wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DateTimeInterface.
     $typed_data = $this->createTypedData(array('type' => 'timestamp'), REQUEST_TIME);
     $this->assertTrue($typed_data->getDateTime() instanceof DrupalDateTime);
     $typed_data->setDateTime(DrupalDateTime::createFromTimestamp(REQUEST_TIME + 1));
     $this->assertEqual($typed_data->getValue(), REQUEST_TIME + 1);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime());
     // DurationIso8601 type.
     $value = 'PT20S';
     $typed_data = $this->createTypedData(array('type' => 'duration_iso8601'), $value);
     $this->assertTrue($typed_data instanceof DurationInterface, 'Typed data object is an instance of DurationInterface.');
     $this->assertIdentical($typed_data->getValue(), $value, 'DurationIso8601 value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('P40D');
     $this->assertEqual($typed_data->getDuration()->d, 40, 'DurationIso8601 value was changed and set by duration string.');
     $this->assertTrue(is_string($typed_data->getString()), 'DurationIso8601 value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'DurationIso8601 wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DurationInterface.
     $typed_data = $this->createTypedData(array('type' => 'duration_iso8601'), 'PT20S');
     $this->assertTrue($typed_data->getDuration() instanceof \DateInterval);
     $typed_data->setDuration(new \DateInterval('P40D'));
     // @todo: Should we make this "nicer"?
     $this->assertEqual($typed_data->getValue(), 'P0Y0M40DT0H0M0S');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDuration());
     // Time span type.
     $value = 20;
     $typed_data = $this->createTypedData(array('type' => 'timespan'), $value);
     $this->assertTrue($typed_data instanceof DurationInterface, 'Typed data object is an instance of DurationInterface.');
     $this->assertIdentical($typed_data->getValue(), $value, 'Time span value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(60 * 60 * 4);
     $this->assertEqual($typed_data->getDuration()->s, 14400, 'Time span was changed');
     $this->assertTrue(is_string($typed_data->getString()), 'Time span value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Time span wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DurationInterface.
     $typed_data = $this->createTypedData(array('type' => 'timespan'), 20);
     $this->assertTrue($typed_data->getDuration() instanceof \DateInterval);
     $typed_data->setDuration(new \DateInterval('PT4H'));
     $this->assertEqual($typed_data->getValue(), 60 * 60 * 4);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDuration());
     // URI type.
     $uri = 'http://example.com/foo/';
     $typed_data = $this->createTypedData(array('type' => 'uri'), $uri);
     $this->assertTrue($typed_data instanceof UriInterface, 'Typed data object is an instance of UriInterface.');
     $this->assertTrue($typed_data->getValue() === $uri, 'URI value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue($uri . 'bar.txt');
     $this->assertTrue($typed_data->getValue() === $uri . 'bar.txt', 'URI value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'URI value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'URI wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     $typed_data->setValue('public://field/image/Photo on 4-28-14 at 12.01 PM.jpg');
     $this->assertEqual($typed_data->validate()->count(), 0, 'Filename with spaces is valid.');
     // Generate some files that will be used to test the binary data type.
     $files = array();
     for ($i = 0; $i < 3; $i++) {
         $path = "public://example_{$i}.png";
         file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', $path);
         $image = File::create(['uri' => $path]);
         $image->save();
         $files[] = $image;
     }
     // Email type.
     $value = $this->randomString();
     $typed_data = $this->createTypedData(array('type' => 'email'), $value);
     $this->assertTrue($typed_data instanceof StringInterface, 'Typed data object is an instance of StringInterface.');
     $this->assertIdentical($typed_data->getValue(), $value, 'Email value was fetched.');
     $new_value = '*****@*****.**';
     $typed_data->setValue($new_value);
     $this->assertIdentical($typed_data->getValue(), $new_value, 'Email value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Email value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Email wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalidATexample.com');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Binary type.
     $typed_data = $this->createTypedData(array('type' => 'binary'), $files[0]->getFileUri());
     $this->assertTrue($typed_data instanceof BinaryInterface, 'Typed data object is an instance of BinaryInterface.');
     $this->assertTrue(is_resource($typed_data->getValue()), 'Binary value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // Try setting by URI.
     $typed_data->setValue($files[1]->getFileUri());
     $this->assertEqual(fgets($typed_data->getValue()), fgets(fopen($files[1]->getFileUri(), 'r')), 'Binary value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Binary value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // Try setting by resource.
     $typed_data->setValue(fopen($files[2]->getFileUri(), 'r'));
     $this->assertEqual(fgets($typed_data->getValue()), fgets(fopen($files[2]->getFileUri(), 'r')), 'Binary value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Binary value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Binary wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Any type.
     $value = array('foo');
     $typed_data = $this->createTypedData(array('type' => 'any'), $value);
     $this->assertIdentical($typed_data->getValue(), $value, 'Any value was fetched.');
     $new_value = '*****@*****.**';
     $typed_data->setValue($new_value);
     $this->assertIdentical($typed_data->getValue(), $new_value, 'Any value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Any value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Any wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // We cannot test invalid values as everything is valid for the any type,
     // but make sure an array or object value passes validation also.
     $typed_data->setValue(array('entry'));
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue((object) array('entry'));
     $this->assertEqual($typed_data->validate()->count(), 0);
 }
Exemple #17
0
 /**
  * Formats a date, using a date type or a custom date format string.
  *
  * @param int $timestamp
  *   A UNIX timestamp to format.
  * @param string $type
  *   (optional) The format to use, one of:
  *   - One of the built-in formats: 'short', 'medium',
  *     'long', 'html_datetime', 'html_date', 'html_time',
  *     'html_yearless_date', 'html_week', 'html_month', 'html_year'.
  *   - The name of a date type defined by a date format config entity.
  *   - The machine name of an administrator-defined date format.
  *   - 'custom', to use $format.
  *   Defaults to 'medium'.
  * @param string $format
  *   (optional) If $type is 'custom', a PHP date format string suitable for
  *   input to date(). Use a backslash to escape ordinary text, so it does not
  *   get interpreted as date format characters.
  * @param string|null $timezone
  *   (optional) Time zone identifier, as described at
  *   http://php.net/manual/timezones.php Defaults to the time zone used to
  *   display the page.
  * @param string|null $langcode
  *   (optional) Language code to translate to. NULL (default) means to use
  *   the user interface language for the page.
  *
  * @return string
  *   A translated date string in the requested format. Since the format may
  *   contain user input, this value should be escaped when output.
  */
 public function format($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL)
 {
     if (!isset($timezone)) {
         $timezone = date_default_timezone_get();
     }
     // Store DateTimeZone objects in an array rather than repeatedly
     // constructing identical objects over the life of a request.
     if (!isset($this->timezones[$timezone])) {
         $this->timezones[$timezone] = timezone_open($timezone);
     }
     if (empty($langcode)) {
         $langcode = $this->languageManager->getCurrentLanguage()->getId();
     }
     // Create a DrupalDateTime object from the timestamp and timezone.
     $create_settings = array('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 ($date_format = $this->dateFormat($type, $langcode)) {
         $format = $date_format->getPattern();
     }
     // Fall back to medium if a format was not found.
     if (empty($format)) {
         $format = $this->dateFormat('fallback', $langcode)->getPattern();
     }
     // Call $date->format().
     $settings = array('langcode' => $langcode);
     return $date->format($format, $settings);
 }
 /**
  * {@inheritdoc}
  */
 public function summary()
 {
     $rule_scheduler = $this->getRuleScheduler();
     if ($rule_scheduler) {
         return $this->t('Current date is after @date', ['@date' => DrupalDateTime::createFromTimestamp($rule_scheduler->getDate())]);
     } else {
         return $this->t('Current date is after a date');
     }
 }