getCurrentTime example

/** * {@inheritdoc} */
  public function getRequestTime() {
    $request = $this->requestStack->getCurrentRequest();
    if ($request) {
      return $request->server->get('REQUEST_TIME');
    }
    // If this is called prior to the request being pushed to the stack fallback     // to built-in globals (if available) or the system time.     return $_SERVER['REQUEST_TIME'] ?? $this->getCurrentTime();
  }

  /** * {@inheritdoc} */
  public function getRequestMicroTime() {
    $request = $this->requestStack->getCurrentRequest();
    if ($request) {
      return $request->server->get('REQUEST_TIME_FLOAT');
    }
    // If this is called prior to the request being pushed to the stack fallback

    protected string $operator = Rule::OPERATOR_EQ;

    protected ?float $daysPassed = null;

    public function match(RuleScope $scope): bool
    {
        if (!$this->supportsScope($scope)) {
            return false;
        }

        $currentDate = $scope->getCurrentTime()->setTime(0, 0, 0, 0);

        if ($this->daysPassed === null && $this->operator !== self::OPERATOR_EMPTY) {
            throw new UnsupportedValueException(\gettype($this->daysPassed), self::class);
        }

        if (!$date = $this->getDate($scope)) {
            return RuleComparison::isNegativeOperator($this->operator);
        }

        if ($this->daysPassed === null) {
            return false;
        }
$this->providersUrl = $config_factory->get('media.settings')->get('oembed_providers_url');
    $this->time = $time;
    $this->maxAge = $max_age;
    $this->keyValue = $key_value_factory->get('media');
    $this->logger = $logger_factory->get('media');
  }

  /** * {@inheritdoc} */
  public function getAll() {
    $current_time = $this->time->getCurrentTime();
    $stored = $this->keyValue->get('oembed_providers');
    // If we have stored data that hasn't yet expired, return that. We need to     // store the data in a key-value store because, if the remote provider     // database is unavailable, we'd rather return stale data than throw an     // exception. This means we cannot use a normal cache backend or expirable     // key-value store, since those could delete the stale data at any time.     if ($stored && $stored['expires'] > $current_time) {
      return $stored['data'];
    }

    try {
      
protected bool $debug = true;

    /** * @var array<string> */
    protected array $customerGroupIds = [];

    public function match(RuleScope $scope): bool
    {
        $context = [...['scope' => $scope], ...$this->values];
        $lastModified = $this->lastModified ?? $scope->getCurrentTime();
        $name = $this->identifier ?? $this->getName();

        $options = ['auto_reload' => true];
        if (!$this->debug) {
            $options['cache'] = new FilesystemCache($this->cacheDir . '/' . $name);
        } else {
            $options['debug'] = true;
        }

        $script = new Script(
            $name,
            
$this->queue = [];
    $this->idSequence = 0;
  }

  /** * {@inheritdoc} */
  public function createItem($data) {
    $item = new \stdClass();
    $item->item_id = $this->idSequence++;
    $item->data = $data;
    $item->created = \Drupal::time()->getCurrentTime();
    $item->expire = 0;
    $this->queue[$item->item_id] = $item;
    return $item->item_id;
  }

  /** * {@inheritdoc} */
  public function numberOfItems() {
    return count($this->queue);
  }

  
$this->toDate = new \DateTime($this->toDate);
        }
    }

    public function match(RuleScope $scope): bool
    {
        if (\is_string($this->toDate) || \is_string($this->fromDate)) {
            throw new \LogicException('fromDate or toDate cannot be a string at this point.');
        }
        $toDate = $this->toDate;
        $fromDate = $this->fromDate;
        $now = $scope->getCurrentTime();

        if (!$this->useTime && $fromDate) {
            $fromDate = (new \DateTime())
                ->setTimestamp($fromDate->getTimestamp())
                ->setTime(0, 0);
        }

        if (!$this->useTime && $toDate) {
            $toDate = (new \DateTime())
                ->setTimestamp($toDate->getTimestamp())
                ->add(new \DateInterval('P1D'))
                
protected string $toTime;

    private bool $validationTurnover = false;

    private \DateTimeInterface $to;

    private \DateTimeInterface $from;

    public function match(RuleScope $scope): bool
    {
        $now = $scope->getCurrentTime();
        $this->from = $this->extractTime($this->fromTime, $now);
        $this->to = $this->extractTime($this->toTime, $now);

        $this->switchValidationIfToIsSmallerThanFrom();

        return $this->returnResultWithSightOnValidationTurnover($now);
    }

    public function getConstraints(): array
    {
        return [
            

  protected function doCreateItem($data) {
    $query = $this->connection->insert(static::TABLE_NAME)
      ->fields([
        'name' => $this->name,
        'data' => serialize($data),
        // We cannot rely on REQUEST_TIME because many items might be created         // by a single request which takes longer than 1 second.         'created' => \Drupal::time()->getCurrentTime(),
      ]);
    // Return the new serial ID, or FALSE on failure.     return $query->execute();
  }

  /** * {@inheritdoc} */
  public function numberOfItems() {
    try {
      return (int) $this->connection->query('SELECT COUNT([item_id]) FROM {' . static::TABLE_NAME . '} WHERE [name] = :name', [':name' => $this->name])
        
$this->assertTrue($option_field->hasAttribute('selected'));
    $this->assertSession()->fieldValueEquals('default_value_input[default_date]', '');

    // Loop through defined timezones to test that date-only defaults work at     // the extremes.     foreach (static::$timezones as $timezone) {
      $this->setSiteTimezone($timezone);
      $this->assertEquals($timezone$this->config('system.date')->get('timezone.default'), 'Time zone set to ' . $timezone);

      // The time of the request is determined very early on in the request so       // use the current time prior to making a request.       $request_time = $this->container->get('datetime.time')->getCurrentTime();
      $this->drupalGet('node/add/dateonly_content');

      $today = $this->dateFormatter->format($request_time, 'html_date', NULL, $timezone);
      $this->assertSession()->fieldValueEquals('field_dateonly[0][value][date]', $today);

      $edit = [
        'title[0][value]' => $timezone,
      ];
      $this->submitForm($edit, 'Save');
      $this->assertSession()->pageTextContains('dateonly_content ' . $timezone . ' has been created');

      
// Add a translation to the views configuration for the past and future     // formats.     $this->drupalGet('admin/structure/views/view/content/translate/de/edit');
    $edit = [
      'translation[config_names][views.view.content][display][default][display_options][fields][changed][settings][future_format]' => '@interval später',
      'translation[config_names][views.view.content][display][default][display_options][fields][changed][settings][past_format]' => 'vor @interval',
    ];
    $this->submitForm($edit, 'Save translation');

    // Create a timestamp just over an hour in the past and set the nodes update     // time to this.     $past_timestamp = \Drupal::time()->getCurrentTime() - 3700;
    $node->setChangedTime($past_timestamp);
    $node->save();

    $this->drupalGet('/de/admin/content');
    // Not all normal string translations are available, so 'hour' is still in     // English.     $this->assertSession()->pageTextContains('vor 1 hour');

    // Create a timestamp just over an hour in the future and set the nodes     // update time to this.     $past_timestamp = \Drupal::time()->getCurrentTime() + 3700;
    

    public function __construct(
        protected string $operator = self::OPERATOR_EQ,
        protected ?int $dayOfWeek = null
    ) {
        parent::__construct();
    }

    public function match(RuleScope $scope): bool
    {
        $todaysDayOfWeek = (int) $scope->getCurrentTime()->format('N');

        return RuleComparison::numeric($todaysDayOfWeek$this->dayOfWeek, $this->operator);
    }

    public function getConstraints(): array
    {
        return [
            'operator' => RuleConstraints::stringOperators(false),
            'dayOfWeek' => [new NotBlank()new Range(['min' => 1, 'max' => 7])],
        ];
    }

    

  protected function setUp(): void {
    // Setup logger before register() is called.     $this->logger = $this->createMock(LoggerInterface::class);
    parent::setUp();

    $this->connection = Database::getConnection();
    $this->cron = \Drupal::service('cron');

    $time = $this->prophesize('Drupal\Component\Datetime\TimeInterface');
    $time->getCurrentTime()->willReturn($this->currentTime);
    $time->getCurrentMicroTime()->willReturn(100.0);
    $time->getRequestTime()->willReturn($this->currentTime);
    \Drupal::getContainer()->set('datetime.time', $time->reveal());
    $this->assertEquals($this->currentTime, \Drupal::time()->getCurrentTime());
    $this->assertEquals($this->currentTime, \Drupal::time()->getRequestTime());

    $realQueueFactory = $this->container->get('queue');
    $queue_factory = $this->prophesize(get_class($realQueueFactory));
    $database = new DatabaseQueue('cron_queue_test_database_delay_exception', $this->connection);
    $memory = new Memory('cron_queue_test_memory_delay_exception');
    $queue_factory->get('cron_queue_test_database_delay_exception', Argument::cetera())->willReturn($database);
    
$config_factory = $this->getConfigFactoryStub([
      'media.settings' => [
        'oembed_providers_url' => 'https://oembed.com/providers.json',
      ],
    ]);

    $key_value_factory = new KeyValueMemoryFactory();
    $this->keyValue = $key_value_factory->get('media');

    $this->currentTime = time();
    $time = $this->prophesize('\Drupal\Component\Datetime\TimeInterface');
    $time->getCurrentTime()->willReturn($this->currentTime);

    $this->logger = $this->prophesize('\Psr\Log\LoggerInterface');
    $logger_factory = new LoggerChannelFactory();
    $logger_factory->addLogger($this->logger->reveal());

    $this->responses = new MockHandler();
    $client = new Client([
      'handler' => HandlerStack::create($this->responses),
    ]);
    $this->repository = new ProviderRepository(
      $client,
      

  protected function processQueue(QueueInterface $queue, QueueWorkerInterface $worker) {
    $lease_time = $worker->getPluginDefinition()['cron']['time'];
    $end = $this->time->getCurrentTime() + $lease_time;
    while ($this->time->getCurrentTime() < $end && ($item = $queue->claimItem($lease_time))) {
      try {
        $worker->processItem($item->data);
        $queue->deleteItem($item);
      }
      catch (DelayedRequeueException $e) {
        // The worker requested the task not be immediately re-queued.         // - If the queue doesn't support ::delayItem(), we should leave the         // item's current expiry time alone.         // - If the queue does support ::delayItem(), we should allow the         // queue to update the item's expiry using the requested delay.
$_SERVER['REQUEST_TIME_FLOAT'] = 2345678.90;
    $this->assertEquals(2345678.90, $this->time->getRequestMicroTime());
  }

  /** * Tests the getCurrentTime method. * * @covers ::getCurrentTime */
  public function testGetCurrentTime() {
    $expected = 12345678;
    $this->assertEquals($expected$this->time->getCurrentTime());
  }

  /** * Tests the getCurrentMicroTime method. * * @covers ::getCurrentMicroTime */
  public function testGetCurrentMicroTime() {
    $expected = 1234567.89;
    $this->assertEquals($expected$this->time->getCurrentMicroTime());
  }

}
Home | Imprint | This part of the site doesn't use cookies.