getRequestTime example


  public function testStatisticsTokenReplacement() {
    $language_interface = \Drupal::languageManager()->getCurrentLanguage();

    // Create user and node.     $user = $this->drupalCreateUser(['create page content']);
    $this->drupalLogin($user);
    $node = $this->drupalCreateNode(['type' => 'page', 'uid' => $user->id()]);

    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
    $date_formatter = $this->container->get('date.formatter');
    $request_time = \Drupal::time()->getRequestTime();

    // Generate and test tokens.     $tests = [];
    $tests['[node:total-count]'] = 0;
    $tests['[node:day-count]'] = 0;
    $tests['[node:last-view]'] = 'never';
    $tests['[node:last-view:short]'] = $date_formatter->format($request_time, 'short');

    foreach ($tests as $input => $expected) {
      $output = \Drupal::token()->replace($input['node' => $node]['langcode' => $language_interface->getId()]);
      $this->assertEquals($expected$outputnew FormattableMarkup('Statistics token %token replaced.', ['%token' => $input]));
    }
// Set revision data details for revisionable entities.     if ($entity->getEntityType()->isRevisionable()) {
      if ($bundle_entity_type = $entity->getEntityType()->getBundleEntityType()) {
        $bundle_entity = $this->entityTypeManager->getStorage($bundle_entity_type)->load($entity->bundle());
        if ($bundle_entity instanceof RevisionableEntityBundleInterface) {
          $entity->setNewRevision($bundle_entity->shouldCreateNewRevision());
        }
      }
      if ($entity instanceof RevisionLogInterface && $entity->isNewRevision()) {
        $entity->setRevisionUserId($this->user->id());
        $entity->setRevisionCreationTime($this->time->getRequestTime());
      }
    }

    $entity->save();
    $primary_data = new ResourceObjectData([ResourceObject::createFromEntity($resource_type$entity)], 1);
    return $this->buildWrappedResponse($primary_data$request$this->getIncludes($request$primary_data));
  }

  /** * Deletes an individual entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The loaded entity. * * @return \Drupal\jsonapi\ResourceResponse * The response. */
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_state->get('entity');
    /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
    $storage = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId());
    $entity = $storage->createRevision($entity$entity->isDefaultRevision());

    $new_state = $form_state->getValue('new_state');

    $entity->set('moderation_state', $new_state);

    if ($entity instanceof RevisionLogInterface) {
      $entity->setRevisionCreationTime($this->time->getRequestTime());
      $entity->setRevisionLogMessage($form_state->getValue('revision_log'));
      $entity->setRevisionUserId($this->currentUser()->id());
    }
    $entity->save();

    $this->messenger()->addStatus($this->t('The moderation state has been updated.'));

    $new_state = $this->moderationInfo->getWorkflowForEntity($entity)->getTypePlugin()->getState($new_state);
    // The page we're on likely won't be visible if we just set the entity to     // the default state, as we hide that latest-revision tab if there is no     // pending revision. Redirect to the canonical URL instead, since that will

class TestTime extends Time {

  /** * {@inheritdoc} */
  public function getRequestTime() {
    if ($mock_date = \Drupal::state()->get('update_test.mock_date', NULL)) {
      return \DateTime::createFromFormat('Y-m-d', $mock_date)->getTimestamp();
    }
    return parent::getRequestTime();
  }

}

  protected function preUpdateEntityTypeSchema(EntityTypeInterface $entity_type, EntityTypeInterface $original, array $field_storage_definitions, array $original_field_storage_definitions, array &$sandbox = NULL) {
    $temporary_prefix = static::getTemporaryTableMappingPrefix($entity_type$field_storage_definitions);
    $sandbox['temporary_table_mapping'] = $this->storage->getCustomTableMapping($entity_type$field_storage_definitions$temporary_prefix);
    $sandbox['new_table_mapping'] = $this->storage->getCustomTableMapping($entity_type$field_storage_definitions);
    $sandbox['original_table_mapping'] = $this->storage->getCustomTableMapping($original$original_field_storage_definitions);

    $backup_prefix = static::getTemporaryTableMappingPrefix($original$original_field_storage_definitions, 'old_');
    $sandbox['backup_table_mapping'] = $this->storage->getCustomTableMapping($original$original_field_storage_definitions$backup_prefix);
    $sandbox['backup_prefix_key'] = substr($backup_prefix, 4);
    $sandbox['backup_request_time'] = \Drupal::time()->getRequestTime();

    // Create temporary tables based on the new entity type and field storage     // definitions.     $temporary_table_names = array_combine(
      $this->getTableNames($entity_type$field_storage_definitions$sandbox['new_table_mapping']),
      $this->getTableNames($entity_type$field_storage_definitions$sandbox['temporary_table_mapping'])
    );
    $this->entityType = $entity_type;
    $this->fieldStorageDefinitions = $field_storage_definitions;

    // Update the storage's entity type and field storage definitions because
$this->setCommentSubject(TRUE);
    $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');

    $edit = [];
    $date = new DrupalDateTime('2008-03-02 17:23');
    $edit['subject[0][value]'] = $this->randomMachineName(8);
    $edit['comment_body[0][value]'] = $this->randomMachineName(16);
    $edit['uid'] = $web_user->getAccountName() . ' (' . $web_user->id() . ')';
    $edit['date[date]'] = $date->format('Y-m-d');
    $edit['date[time]'] = $date->format('H:i:s');
    $raw_date = $date->getTimestamp();
    $expected_text_date = $this->container->get('date.formatter')->formatInterval(\Drupal::time()->getRequestTime() - $raw_date);
    $expected_form_date = $date->format('Y-m-d');
    $expected_form_time = $date->format('H:i:s');
    $comment = $this->postComment($this->node, $edit['subject[0][value]']$edit['comment_body[0][value]'], TRUE);
    $this->drupalGet('comment/' . $comment->id() . '/edit');
    $this->submitForm($edit, 'Preview');

    // Check that the preview is displaying the subject, comment, author and date correctly.     $this->assertSession()->titleEquals('Preview comment | Drupal');
    $this->assertSession()->pageTextContains($edit['subject[0][value]']);
    $this->assertSession()->pageTextContains($edit['comment_body[0][value]']);
    $this->assertSession()->pageTextContains($web_user->getAccountName());
    
'type' => 'int',
        ],
      ],
    ];
  }

  /** * {@inheritdoc} */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    // Pick a random timestamp in the past year.     $timestamp = \Drupal::time()->getRequestTime() - mt_rand(0, 86400 * 365);
    $values['value'] = $timestamp;
    return $values;
  }

}
$language = ConfigurableLanguage::createFromLangcode('de');
    $language->save();

    $this->createContentType(['type' => 'page']);

    $this->setCurrentUser($this->createUser(['administer nodes']));

    $this->container->get('content_translation.manager')->setEnabled('node', 'page', TRUE);

    // Create two nodes, a published and an unpublished one, so we can test the     // behavior of the module with default/existing content.     $this->createdTimestamp = \Drupal::time()->getRequestTime();
    $this->nodes[] = $this->createNode(['title' => 'live - 1 - r1 - published', 'body' => 'node 1', 'created' => $this->createdTimestamp++, 'status' => TRUE]);
    $this->nodes[] = $this->createNode(['title' => 'live - 2 - r2 - unpublished', 'body' => 'node 2', 'created' => $this->createdTimestamp++, 'status' => FALSE]);

    $translation = $this->nodes[0]->addTranslation('de');
    $translation->setTitle('live - 1 - r1 - published - de');
    $translation->save();
  }

  /** * Tests various scenarios for creating and publishing content in workspaces. */
  
/** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // The revision timestamp will be updated when the revision is saved. Keep     // the original one for the confirmation message.     $original_revision_timestamp = $this->revision->getRevisionCreationTime();

    $this->revision = $this->prepareRevertedRevision($this->revision, $form_state);
    $this->revision->revision_log = $this->t('Copy of the revision from %date.', ['%date' => $this->dateFormatter->format($original_revision_timestamp)]);
    $this->revision->setRevisionUserId($this->currentUser()->id());
    $this->revision->setRevisionCreationTime($this->time->getRequestTime());
    $this->revision->setChangedTime($this->time->getRequestTime());
    $this->revision->save();

    $this->logger('content')->info('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
    $this->messenger()
      ->addStatus($this->t('@type %title has been reverted to the revision from %revision-date.', [
        '@type' => node_get_type_label($this->revision),
        '%title' => $this->revision->label(),
        '%revision-date' => $this->dateFormatter->format($original_revision_timestamp),
      ]));
    $form_state->setRedirect(
      
// Insert a row with a big value for wid.     $insert = $connection->insert('watchdog');
    $insert->fields([
      'wid'         => 2147483647000,
      'message'     => 'Dblog test log message with big WID',
      'type'        => 'test',
      'variables'   => '',
      'severity'    => RfcLogLevel::NOTICE,
      'uid'         => 1,
      'location'    => $base_root . \Drupal::request()->getRequestUri(),
      'hostname'    => $base_root,
      'timestamp'   => \Drupal::time()->getRequestTime(),
    ]);
    $insert->execute();

    // Insert another row without a value for wid, to test auto-increment.     $insert = $connection->insert('watchdog');
    $insert->fields([
      'message'     => 'Dblog test log message with big WID',
      'type'        => 'test',
      'variables'   => '',
      'severity'    => RfcLogLevel::NOTICE,
      'uid'         => 1,
      

  public function testModeratedContentPage() {
    $assert_session = $this->assertSession();
    $this->drupalLogin($this->adminUser);

    // Use an explicit changed time to ensure the expected order in the content     // admin listing. We want these to appear in the table in the same order as     // they appear in the following code, and the 'moderated_content' view has a     // table style configuration with a default sort on the 'changed' field     // descending.     $time = \Drupal::time()->getRequestTime();
    $excluded_nodes['published_page'] = $this->drupalCreateNode(['type' => 'page', 'changed' => $time--, 'moderation_state' => 'published']);
    $excluded_nodes['published_article'] = $this->drupalCreateNode(['type' => 'article', 'changed' => $time--, 'moderation_state' => 'published']);

    $excluded_nodes['unmoderated_type'] = $this->drupalCreateNode(['type' => 'unmoderated_type', 'changed' => $time--]);
    $excluded_nodes['unmoderated_type']->setNewRevision(TRUE);
    $excluded_nodes['unmoderated_type']->isDefaultRevision(FALSE);
    $excluded_nodes['unmoderated_type']->changed->value = $time--;
    $excluded_nodes['unmoderated_type']->save();

    $nodes['published_then_draft_article'] = $this->drupalCreateNode(['type' => 'article', 'changed' => $time--, 'moderation_state' => 'published', 'title' => 'first article - published']);
    $nodes['published_then_draft_article']->setNewRevision(TRUE);
    
$plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('datetime.time')
    );
  }

  /** * {@inheritdoc} */
  public function execute($entity = NULL) {
    $entity->setChangedTime($this->time->getRequestTime())->save();
  }

  /** * {@inheritdoc} */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    // It's not necessary to check the changed field access here, because     // Drupal\Core\Field\ChangedFieldItemList would anyway return 'not allowed'.     // Also changing the changed field value is only a workaround to trigger an     // entity resave. Without a field change, this would not be possible.     /** @var \Drupal\Core\Entity\EntityInterface $object */
    
// Mark the entity as requiring validation.     $entity->setValidationRequired(!$form_state->getTemporaryValue('entity_validated'));

    // Save as a new revision if requested to do so.     if ($this->showRevisionUi() && !$form_state->isValueEmpty('revision')) {
      $entity->setNewRevision();
      if ($entity instanceof RevisionLogInterface) {
        // If a new revision is created, save the current user as         // revision author.         $entity->setRevisionUserId($this->currentUser()->id());
        $entity->setRevisionCreationTime($this->time->getRequestTime());
      }
    }

    return $entity;
  }

  /** * {@inheritdoc} * * Button-level validation handlers are highly discouraged for entity forms, * as they will prevent entity validation from running. If the entity is going * to be saved during the form submission, this method should be manually * invoked from the button-level validation handler, otherwise an exception * will be thrown. */
// Confirm that the node was created.     $this->assertSession()->pageTextContains('Basic page ' . $edit['title[0][value]'] . ' has been created.');

    // Verify that the creation message contains a link to a node.     $this->assertSession()->elementExists('xpath', '//div[@data-drupal-messages]//a[contains(@href, "node/")]');
  }

  /** * Creates nodes with different authored dates. */
  public function testAuthoredDate() {
    $now = \Drupal::time()->getRequestTime();
    $admin = $this->drupalCreateUser([], NULL, TRUE);
    $this->drupalLogin($admin);

    // Create a node with the default creation date.     $edit = [
      'title[0][value]' => $this->randomMachineName(8),
      'body[0][value]' => $this->randomMachineName(16),
    ];
    $this->drupalGet('node/add/page');
    $this->submitForm($edit, 'Save');
    $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
    

  protected function prepareItem($cache$allow_invalid = FALSE) {
    if (!isset($cache->data)) {
      return FALSE;
    }
    // Check expire time.     $cache->valid = $cache->expire == static::CACHE_PERMANENT || $cache->expire >= $this->getRequestTime();

    if (!$allow_invalid && !$cache->valid) {
      return FALSE;
    }

    return $cache;
  }

  /** * {@inheritdoc} */
  
Home | Imprint | This part of the site doesn't use cookies.