You are here

public function TestTime::getRequestTime in Automatic Updates 8.2

Returns the timestamp for the current request.

This method should be used to obtain the current system time at the start of the request. It will be the same value for the life of the request (even for long execution times).

If the request is not available it will fallback to the current system time.

This method can replace instances of

$request_time = $_SERVER['REQUEST_TIME'];
$request_time = REQUEST_TIME;
$request_time = $requestStack
  ->getCurrentRequest()->server
  ->get('REQUEST_TIME');
$request_time = $request->server
  ->get('REQUEST_TIME');

and most instances of

$time = time();

with

$request_time = \Drupal::time()
  ->getRequestTime();

or the equivalent using the injected service.

Using the time service, rather than other methods, is especially important when creating tests, which require predictable timestamps.

Return value

int A Unix timestamp.

Overrides Time::getRequestTime

See also

\Drupal\Component\Datetime\TimeInterface::getRequestMicroTime()

\Drupal\Component\Datetime\TimeInterface::getCurrentTime()

\Drupal\Component\Datetime\TimeInterface::getCurrentMicroTime()

File

tests/modules/automatic_updates_test/src/Datetime/TestTime.php, line 36

Class

TestTime
Test service for altering the request time.

Namespace

Drupal\automatic_updates_test\Datetime

Code

public function getRequestTime() : int {
  if ($faked_date = \Drupal::state()
    ->get('automatic_updates_test.fake_date_time')) {
    return \DateTime::createFromFormat('U', $faked_date)
      ->getTimestamp();
  }
  return $this->decoratorTime
    ->getRequestTime();
}