diff --git a/core/core.api.php b/core/core.api.php index 66352cd8f3..9a577af48a 100644 --- a/core/core.api.php +++ b/core/core.api.php @@ -192,7 +192,7 @@ * // Find out when cron was last run; the key is 'system.cron_last'. * $time = $state->get('system.cron_last'); * // Set the cron run time to the current request time. - * $state->set('system.cron_last', REQUEST_TIME); + * $state->set('system.cron_last', \Drupal::time()->getRequestTime()); * @endcode * * For more on the State API, see https://www.drupal.org/developing/api/8/state @@ -1909,7 +1909,7 @@ function hook_cron() { \Drupal::database()->delete('mymodule_table') ->condition('expires', $expires, '>=') ->execute(); - \Drupal::state()->set('mymodule.last_check', REQUEST_TIME); + \Drupal::state()->set('mymodule.last_check', \Drupal::time()->getRequestTime()); // Long-running operation example, leveraging a queue: // Queue news feeds for updates once their refresh interval has elapsed. @@ -1918,12 +1918,12 @@ function hook_cron() { foreach (Feed::loadMultiple($ids) as $feed) { if ($queue->createItem($feed)) { // Add timestamp to avoid queueing item more than once. - $feed->setQueuedTime(REQUEST_TIME); + $feed->setQueuedTime(\Drupal::time()->getRequestTime()); $feed->save(); } } $ids = \Drupal::entityQuery('aggregator_feed') - ->condition('queued', REQUEST_TIME - (3600 * 6), '<') + ->condition('queued', \Drupal::time()->getRequestTime() - (3600 * 6), '<') ->execute(); if ($ids) { $feeds = Feed::loadMultiple($ids); diff --git a/core/includes/bootstrap.inc b/core/includes/bootstrap.inc index f35f104311..d8068ea61c 100644 --- a/core/includes/bootstrap.inc +++ b/core/includes/bootstrap.inc @@ -688,7 +688,7 @@ function drupal_valid_test_ua($new_prefix = NULL) { $private_key = file_get_contents($key_file); // The file properties add more entropy not easily accessible to others. $key = $private_key . filectime(__FILE__) . fileinode(__FILE__); - $time_diff = REQUEST_TIME - $time; + $time_diff = (int) $_SERVER['REQUEST_TIME'] - $time; $test_hmac = Crypt::hmacBase64($check_string, $key); // Since we are making a local request a 600 second time window is allowed, // and the HMAC must match. diff --git a/core/includes/common.inc b/core/includes/common.inc index 65dc02ee2c..a0defbf77c 100644 --- a/core/includes/common.inc +++ b/core/includes/common.inc @@ -1103,7 +1103,7 @@ function drupal_flush_all_caches() { */ function _drupal_flush_css_js() { // The timestamp is converted to base 36 in order to make it more compact. - Drupal::state()->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36)); + Drupal::state()->set('system.css_js_query_string', base_convert(\Drupal::time()->getRequestTime(), 10, 36)); } /** diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc index 566afddf67..7d8fb1caa0 100644 --- a/core/includes/install.core.inc +++ b/core/includes/install.core.inc @@ -1061,9 +1061,9 @@ function install_display_output($output, $install_state) { $response = $bare_html_page_renderer->renderBarePage($output, $output['#title'], 'install_page', $regions); $default_headers = [ 'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT', - 'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME), + 'Last-Modified' => gmdate(DATE_RFC1123, \Drupal::time()->getRequestTime()), 'Cache-Control' => 'no-cache, must-revalidate', - 'ETag' => '"' . REQUEST_TIME . '"', + 'ETag' => '"' . \Drupal::time()->getRequestTime() . '"', ]; $response->headers->add($default_headers); $response->send(); diff --git a/core/lib/Drupal/Component/Datetime/Time.php b/core/lib/Drupal/Component/Datetime/Time.php index 77da2e2c1f..37d3be42ce 100644 --- a/core/lib/Drupal/Component/Datetime/Time.php +++ b/core/lib/Drupal/Component/Datetime/Time.php @@ -30,7 +30,11 @@ public function __construct(RequestStack $request_stack) { * {@inheritdoc} */ public function getRequestTime() { - return $this->requestStack->getCurrentRequest()->server->get('REQUEST_TIME'); + $request = $this->requestStack->getCurrentRequest(); + if ($request) { + return $request->server->get('REQUEST_TIME'); + } + return (int) $_SERVER['REQUEST_TIME']; } /** diff --git a/core/lib/Drupal/Component/Datetime/TimeInterface.php b/core/lib/Drupal/Component/Datetime/TimeInterface.php index 0c81575c73..aab28e3820 100644 --- a/core/lib/Drupal/Component/Datetime/TimeInterface.php +++ b/core/lib/Drupal/Component/Datetime/TimeInterface.php @@ -17,7 +17,6 @@ interface TimeInterface { * This method can replace instances of * @code * $request_time = $_SERVER['REQUEST_TIME']; - * $request_time = REQUEST_TIME; * $request_time = $requestStack->getCurrentRequest()->server->get('REQUEST_TIME'); * $request_time = $request->server->get('REQUEST_TIME'); * @endcode diff --git a/core/lib/Drupal/Core/Asset/CssCollectionOptimizer.php b/core/lib/Drupal/Core/Asset/CssCollectionOptimizer.php index 26ed07f79e..f241a5f188 100644 --- a/core/lib/Drupal/Core/Asset/CssCollectionOptimizer.php +++ b/core/lib/Drupal/Core/Asset/CssCollectionOptimizer.php @@ -192,7 +192,7 @@ public function deleteAll() { $delete_stale = function ($uri) { // Default stale file threshold is 30 days. - if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) { + if (\Drupal::time()->getRequestTime() - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) { $this->fileSystem->delete($uri); } }; diff --git a/core/lib/Drupal/Core/Asset/JsCollectionOptimizer.php b/core/lib/Drupal/Core/Asset/JsCollectionOptimizer.php index dc66652b6c..d591a0e8a1 100644 --- a/core/lib/Drupal/Core/Asset/JsCollectionOptimizer.php +++ b/core/lib/Drupal/Core/Asset/JsCollectionOptimizer.php @@ -194,7 +194,7 @@ public function deleteAll() { $this->state->delete('system.js_cache_files'); $delete_stale = function ($uri) { // Default stale file threshold is 30 days. - if (REQUEST_TIME - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) { + if (\Drupal::time()->getRequestTime() - filemtime($uri) > \Drupal::config('system.performance')->get('stale_file_threshold')) { $this->fileSystem->delete($uri); } }; diff --git a/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php b/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php index 99d0e14f54..19314c3aa9 100644 --- a/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php +++ b/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php @@ -40,11 +40,12 @@ public function render(array $js_assets) { $elements = []; // A dummy query-string is added to filenames, to gain control over - // browser-caching. The string changes on every update or full cache - // flush, forcing browsers to load a new copy of the files, as the - // URL changed. Files that should not be cached get REQUEST_TIME as - // query-string instead, to enforce reload on every page request. - $default_query_string = $this->state->get('system.css_js_query_string', '0'); + // browser-caching. The string changes on every update or full cache flush, + // forcing browsers to load a new copy of the files, as the URL changed. + // Files that should not be cached get + // \Drupal::time()->getRequestTime() as query-string instead, + // to enforce reload on every page request. + $default_query_string = $this->state->get('system.css_js_query_string') ?: '0'; // Defaults for each SCRIPT element. $element_defaults = [ @@ -78,7 +79,7 @@ public function render(array $js_assets) { // Only add the cache-busting query string if this isn't an aggregate // file. if (!isset($js_asset['preprocessed'])) { - $element['#attributes']['src'] .= $query_string_separator . ($js_asset['cache'] ? $query_string : REQUEST_TIME); + $element['#attributes']['src'] .= $query_string_separator . ($js_asset['cache'] ? $query_string : \Drupal::time()->getRequestTime()); } break; diff --git a/core/lib/Drupal/Core/Batch/BatchStorage.php b/core/lib/Drupal/Core/Batch/BatchStorage.php index 69efc1b9bb..097d26c469 100644 --- a/core/lib/Drupal/Core/Batch/BatchStorage.php +++ b/core/lib/Drupal/Core/Batch/BatchStorage.php @@ -109,7 +109,7 @@ public function cleanup() { try { // Cleanup the batch table and the queue for failed batches. $this->connection->delete('batch') - ->condition('timestamp', REQUEST_TIME - 864000, '<') + ->condition('timestamp', \Drupal::time()->getRequestTime() - 864000, '<') ->execute(); } catch (\Exception $e) { @@ -152,7 +152,7 @@ protected function doCreate(array $batch) { $this->connection->insert('batch') ->fields([ 'bid' => $batch['id'], - 'timestamp' => REQUEST_TIME, + 'timestamp' => \Drupal::time()->getRequestTime(), 'token' => $this->csrfToken->get($batch['id']), 'batch' => serialize($batch), ]) diff --git a/core/lib/Drupal/Core/Cache/ApcuBackend.php b/core/lib/Drupal/Core/Cache/ApcuBackend.php index 6014fb8bff..ad04efce8b 100644 --- a/core/lib/Drupal/Core/Cache/ApcuBackend.php +++ b/core/lib/Drupal/Core/Cache/ApcuBackend.php @@ -145,7 +145,7 @@ protected function prepareItem($cache, $allow_invalid) { $cache->tags = $cache->tags ? explode(' ', $cache->tags) : []; // Check expire time. - $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME; + $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= \Drupal::time()->getRequestTime(); // Check if invalidateTags() has been called with any of the entry's tags. if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) { @@ -235,7 +235,7 @@ public function invalidate($cid) { */ public function invalidateMultiple(array $cids) { foreach ($this->getMultiple($cids) as $cache) { - $this->set($cache->cid, $cache, REQUEST_TIME - 1); + $this->set($cache->cid, $cache, \Drupal::time()->getRequestTime() - 1); } } @@ -245,7 +245,7 @@ public function invalidateMultiple(array $cids) { public function invalidateAll() { foreach ($this->getAll() as $data) { $cid = str_replace($this->binPrefix, '', $data['key']); - $this->set($cid, $data['value'], REQUEST_TIME - 1); + $this->set($cid, $data['value'], \Drupal::time()->getRequestTime() - 1); } } diff --git a/core/lib/Drupal/Core/Cache/DatabaseBackend.php b/core/lib/Drupal/Core/Cache/DatabaseBackend.php index cb8b099c18..16ec1297b5 100644 --- a/core/lib/Drupal/Core/Cache/DatabaseBackend.php +++ b/core/lib/Drupal/Core/Cache/DatabaseBackend.php @@ -151,7 +151,7 @@ protected function prepareItem($cache, $allow_invalid) { $cache->tags = $cache->tags ? explode(' ', $cache->tags) : []; // Check expire time. - $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME; + $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= \Drupal::time()->getRequestTime(); // Check if invalidateTags() has been called with any of the items's tags. if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) { @@ -336,7 +336,7 @@ public function invalidateMultiple(array $cids) { // Update in chunks when a large array is passed. foreach (array_chunk($cids, 1000) as $cids_chunk) { $this->connection->update($this->bin) - ->fields(['expire' => REQUEST_TIME - 1]) + ->fields(['expire' => \Drupal::time()->getRequestTime() - 1]) ->condition('cid', $cids_chunk, 'IN') ->execute(); } @@ -352,7 +352,7 @@ public function invalidateMultiple(array $cids) { public function invalidateAll() { try { $this->connection->update($this->bin) - ->fields(['expire' => REQUEST_TIME - 1]) + ->fields(['expire' => \Drupal::time()->getRequestTime() - 1]) ->execute(); } catch (\Exception $e) { @@ -383,7 +383,7 @@ public function garbageCollection() { $this->connection->delete($this->bin) ->condition('expire', Cache::PERMANENT, '<>') - ->condition('expire', REQUEST_TIME, '<') + ->condition('expire', \Drupal::time()->getRequestTime(), '<') ->execute(); } catch (\Exception $e) { diff --git a/core/lib/Drupal/Core/Cache/MemoryBackend.php b/core/lib/Drupal/Core/Cache/MemoryBackend.php index d402d70b54..e1899ddfb1 100644 --- a/core/lib/Drupal/Core/Cache/MemoryBackend.php +++ b/core/lib/Drupal/Core/Cache/MemoryBackend.php @@ -196,12 +196,12 @@ public function removeBin() { } /** - * Wrapper method for REQUEST_TIME constant. + * Wrapper method for $_SERVER['REQUEST_TIME']. * * @return int */ protected function getRequestTime() { - return defined('REQUEST_TIME') ? REQUEST_TIME : (int) $_SERVER['REQUEST_TIME']; + return \Drupal::hasContainer() ? \Drupal::time()->getRequestTime() : (int) $_SERVER['REQUEST_TIME']; } /** diff --git a/core/lib/Drupal/Core/Cache/PhpBackend.php b/core/lib/Drupal/Core/Cache/PhpBackend.php index e4628781b2..174360f45f 100644 --- a/core/lib/Drupal/Core/Cache/PhpBackend.php +++ b/core/lib/Drupal/Core/Cache/PhpBackend.php @@ -126,7 +126,7 @@ protected function prepareItem($cache, $allow_invalid) { } // Check expire time. - $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= REQUEST_TIME; + $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= \Drupal::time()->getRequestTime(); // Check if invalidateTags() has been called with any of the item's tags. if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) { @@ -195,7 +195,7 @@ public function invalidate($cid) { */ protected function invalidatebyHash($cidhash) { if ($item = $this->getByHash($cidhash)) { - $item->expire = REQUEST_TIME - 1; + $item->expire = \Drupal::time()->getRequestTime() - 1; $this->writeItem($cidhash, $item); } } diff --git a/core/lib/Drupal/Core/Cron.php b/core/lib/Drupal/Core/Cron.php index a18bf5b5a2..a3dbe2220b 100644 --- a/core/lib/Drupal/Core/Cron.php +++ b/core/lib/Drupal/Core/Cron.php @@ -172,10 +172,10 @@ protected function processQueues() { $this->queueFactory->get($queue_name)->createQueue(); $queue_worker = $this->queueManager->createInstance($queue_name); - $end = time() + (isset($info['cron']['time']) ? $info['cron']['time'] : 15); + $end = \Drupal::time()->getCurrentTime() + (isset($info['cron']['time']) ? $info['cron']['time'] : 15); $queue = $this->queueFactory->get($queue_name); $lease_time = isset($info['cron']['time']) ?: NULL; - while (time() < $end && ($item = $queue->claimItem($lease_time))) { + while (\Drupal::time()->getCurrentTime() < $end && ($item = $queue->claimItem($lease_time))) { try { $queue_worker->processItem($item->data); $queue->deleteItem($item); diff --git a/core/lib/Drupal/Core/Datetime/DateFormatter.php b/core/lib/Drupal/Core/Datetime/DateFormatter.php index d784743cd5..252eafe5e4 100644 --- a/core/lib/Drupal/Core/Datetime/DateFormatter.php +++ b/core/lib/Drupal/Core/Datetime/DateFormatter.php @@ -171,7 +171,7 @@ public function formatInterval($interval, $granularity = 2, $langcode = NULL) { * {@inheritdoc} */ public function getSampleDateFormats($langcode = NULL, $timestamp = NULL, $timezone = NULL) { - $timestamp = $timestamp ?: time(); + $timestamp = $timestamp ?: \Drupal::time()->getCurrentTime(); // All date format characters for the PHP date() function. $date_chars = str_split('dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU'); $date_elements = array_combine($date_chars, $date_chars); diff --git a/core/lib/Drupal/Core/Datetime/DateHelper.php b/core/lib/Drupal/Core/Datetime/DateHelper.php index 168ef62740..a5feebf1d2 100644 --- a/core/lib/Drupal/Core/Datetime/DateHelper.php +++ b/core/lib/Drupal/Core/Datetime/DateHelper.php @@ -291,10 +291,10 @@ public static function weekDaysOrdered($weekdays) { public static function years($min = 0, $max = 0, $required = FALSE) { // Ensure $min and $max are valid values. if (empty($min)) { - $min = intval(date('Y', REQUEST_TIME) - 3); + $min = intval(date('Y', \Drupal::time()->getRequestTime()) - 3); } if (empty($max)) { - $max = intval(date('Y', REQUEST_TIME) + 3); + $max = intval(date('Y', \Drupal::time()->getRequestTime()) + 3); } $none = ['' => '']; $range = range($min, $max); diff --git a/core/lib/Drupal/Core/Entity/entity.api.php b/core/lib/Drupal/Core/Entity/entity.api.php index d2ffcc4cae..7539b89b40 100644 --- a/core/lib/Drupal/Core/Entity/entity.api.php +++ b/core/lib/Drupal/Core/Entity/entity.api.php @@ -568,7 +568,7 @@ * @code * $fids = Drupal::entityQuery('file') * ->condition('status', FILE_STATUS_PERMANENT, '<>') - * ->condition('changed', REQUEST_TIME - $age, '<') + * ->condition('changed', \Drupal::time()->getRequestTime() - $age, '<') * ->range(0, 100) * ->execute(); * $files = $storage->loadMultiple($fids); @@ -1122,8 +1122,8 @@ function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity) { ->fields([ 'type' => $entity->getEntityTypeId(), 'id' => $entity->id(), - 'created' => REQUEST_TIME, - 'updated' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), + 'updated' => \Drupal::time()->getRequestTime(), ]) ->execute(); } @@ -1145,8 +1145,8 @@ function hook_ENTITY_TYPE_insert(Drupal\Core\Entity\EntityInterface $entity) { \Drupal::database()->insert('example_entity') ->fields([ 'id' => $entity->id(), - 'created' => REQUEST_TIME, - 'updated' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), + 'updated' => \Drupal::time()->getRequestTime(), ]) ->execute(); } @@ -1168,7 +1168,7 @@ function hook_entity_update(Drupal\Core\Entity\EntityInterface $entity) { // Update the entity's entry in a fictional table of all entities. \Drupal::database()->update('example_entity') ->fields([ - 'updated' => REQUEST_TIME, + 'updated' => \Drupal::time()->getRequestTime(), ]) ->condition('type', $entity->getEntityTypeId()) ->condition('id', $entity->id()) @@ -1192,7 +1192,7 @@ function hook_ENTITY_TYPE_update(Drupal\Core\Entity\EntityInterface $entity) { // Update the entity's entry in a fictional table of this type of entity. \Drupal::database()->update('example_entity') ->fields([ - 'updated' => REQUEST_TIME, + 'updated' => \Drupal::time()->getRequestTime(), ]) ->condition('id', $entity->id()) ->execute(); diff --git a/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php index 747262c849..9bcff72aaa 100644 --- a/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php +++ b/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php @@ -248,8 +248,8 @@ protected function setResponseCacheable(Response $response, Request $request) { // In order to support HTTP cache-revalidation, ensure that there is a // Last-Modified and an ETag header on the response. if (!$response->headers->has('Last-Modified')) { - $timestamp = REQUEST_TIME; - $response->setLastModified(new \DateTime(gmdate(DateTimePlus::RFC7231, REQUEST_TIME))); + $timestamp = \Drupal::time()->getRequestTime(); + $response->setLastModified(new \DateTime(gmdate(DateTimePlus::RFC7231, \Drupal::time()->getRequestTime()))); } else { $timestamp = $response->getLastModified()->getTimestamp(); diff --git a/core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/TimestampFormatter.php b/core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/TimestampFormatter.php index cbc6d7ddd5..55463da624 100644 --- a/core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/TimestampFormatter.php +++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/TimestampFormatter.php @@ -106,7 +106,7 @@ public function settingsForm(array $form, FormStateInterface $form_state) { $date_formats = []; foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) { - $date_formats[$machine_name] = $this->t('@name format: @date', ['@name' => $value->label(), '@date' => $this->dateFormatter->format(REQUEST_TIME, $machine_name)]); + $date_formats[$machine_name] = $this->t('@name format: @date', ['@name' => $value->label(), '@date' => $this->dateFormatter->format(\Drupal::time()->getRequestTime(), $machine_name)]); } $date_formats['custom'] = $this->t('Custom'); diff --git a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php index bd2e129f29..9e737758ab 100644 --- a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php +++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/ChangedItem.php @@ -30,7 +30,7 @@ public function preSave() { // Set the timestamp to request time if it is not set. if (!$this->value) { - $this->value = REQUEST_TIME; + $this->value = \Drupal::time()->getRequestTime(); } else { // On an existing entity translation, the changed timestamp will only be @@ -47,7 +47,7 @@ public function preSave() { if (!$entity->isNew() && $original && $original->hasTranslation($langcode)) { $original_value = $original->getTranslation($langcode)->get($this->getFieldDefinition()->getName())->value; if ($this->value == $original_value && $entity->hasTranslationChanges()) { - $this->value = REQUEST_TIME; + $this->value = \Drupal::time()->getRequestTime(); } } } diff --git a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/CreatedItem.php b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/CreatedItem.php index da2e2a7450..78a66a7f84 100644 --- a/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/CreatedItem.php +++ b/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/CreatedItem.php @@ -22,7 +22,7 @@ class CreatedItem extends TimestampItem { public function applyDefaultValue($notify = TRUE) { parent::applyDefaultValue($notify); // Created fields default to the current timestamp. - $this->setValue(['value' => REQUEST_TIME], $notify); + $this->setValue(['value' => \Drupal::time()->getRequestTime()], $notify); return $this; } diff --git a/core/lib/Drupal/Core/Flood/DatabaseBackend.php b/core/lib/Drupal/Core/Flood/DatabaseBackend.php index afb295546c..80fcdacf06 100644 --- a/core/lib/Drupal/Core/Flood/DatabaseBackend.php +++ b/core/lib/Drupal/Core/Flood/DatabaseBackend.php @@ -83,8 +83,8 @@ protected function doInsert($name, $window, $identifier) { ->fields([ 'event' => $name, 'identifier' => $identifier, - 'timestamp' => REQUEST_TIME, - 'expiration' => REQUEST_TIME + $window, + 'timestamp' => \Drupal::time()->getRequestTime(), + 'expiration' => \Drupal::time()->getRequestTime() + $window, ]) ->execute(); } @@ -118,7 +118,7 @@ public function isAllowed($name, $threshold, $window = 3600, $identifier = NULL) $number = $this->connection->select(static::TABLE_NAME, 'f') ->condition('event', $name) ->condition('identifier', $identifier) - ->condition('timestamp', REQUEST_TIME - $window, '>') + ->condition('timestamp', \Drupal::time()->getRequestTime() - $window, '>') ->countQuery() ->execute() ->fetchField(); @@ -136,7 +136,7 @@ public function isAllowed($name, $threshold, $window = 3600, $identifier = NULL) public function garbageCollection() { try { $return = $this->connection->delete(static::TABLE_NAME) - ->condition('expiration', REQUEST_TIME, '<') + ->condition('expiration', \Drupal::time()->getRequestTime(), '<') ->execute(); } catch (\Exception $e) { diff --git a/core/lib/Drupal/Core/Flood/MemoryBackend.php b/core/lib/Drupal/Core/Flood/MemoryBackend.php index 9899e35e7e..b60ec8494f 100644 --- a/core/lib/Drupal/Core/Flood/MemoryBackend.php +++ b/core/lib/Drupal/Core/Flood/MemoryBackend.php @@ -38,8 +38,8 @@ public function register($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = $this->requestStack->getCurrentRequest()->getClientIp(); } - // We can't use REQUEST_TIME here, because that would not guarantee - // uniqueness. + // We can't use \Drupal::time()->getRequestTime() here, because that would + // not guarantee uniqueness. $time = microtime(TRUE); $this->events[$name][$identifier][$time + $window] = $time; } diff --git a/core/lib/Drupal/Core/KeyValueStore/DatabaseStorageExpirable.php b/core/lib/Drupal/Core/KeyValueStore/DatabaseStorageExpirable.php index 86d3dabc53..8eba51ffea 100644 --- a/core/lib/Drupal/Core/KeyValueStore/DatabaseStorageExpirable.php +++ b/core/lib/Drupal/Core/KeyValueStore/DatabaseStorageExpirable.php @@ -36,7 +36,7 @@ public function has($key) { return (bool) $this->connection->query('SELECT 1 FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND name = :key AND expire > :now', [ ':collection' => $this->collection, ':key' => $key, - ':now' => REQUEST_TIME, + ':now' => \Drupal::time()->getRequestTime(), ])->fetchField(); } @@ -47,7 +47,7 @@ public function getMultiple(array $keys) { $values = $this->connection->query( 'SELECT name, value FROM {' . $this->connection->escapeTable($this->table) . '} WHERE expire > :now AND name IN ( :keys[] ) AND collection = :collection', [ - ':now' => REQUEST_TIME, + ':now' => \Drupal::time()->getRequestTime(), ':keys[]' => $keys, ':collection' => $this->collection, ])->fetchAllKeyed(); @@ -62,7 +62,7 @@ public function getAll() { 'SELECT name, value FROM {' . $this->connection->escapeTable($this->table) . '} WHERE collection = :collection AND expire > :now', [ ':collection' => $this->collection, - ':now' => REQUEST_TIME, + ':now' => \Drupal::time()->getRequestTime(), ])->fetchAllKeyed(); return array_map([$this->serializer, 'decode'], $values); } @@ -78,7 +78,7 @@ public function setWithExpire($key, $value, $expire) { ]) ->fields([ 'value' => $this->serializer->encode($value), - 'expire' => REQUEST_TIME + $expire, + 'expire' => \Drupal::time()->getRequestTime() + $expire, ]) ->execute(); } diff --git a/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php b/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php index f9c9b4c17a..abc213a1fa 100644 --- a/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php +++ b/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php @@ -59,7 +59,7 @@ public function get($collection) { */ public function garbageCollection() { $this->connection->delete('key_value_expire') - ->condition('expire', REQUEST_TIME, '<') + ->condition('expire', \Drupal::time()->getRequestTime(), '<') ->execute(); } diff --git a/core/lib/Drupal/Core/Path/AliasManager.php b/core/lib/Drupal/Core/Path/AliasManager.php index 5673f6627b..495ef82a20 100644 --- a/core/lib/Drupal/Core/Path/AliasManager.php +++ b/core/lib/Drupal/Core/Path/AliasManager.php @@ -332,12 +332,12 @@ protected function pathAliasWhitelistRebuild($path = NULL) { } /** - * Wrapper method for REQUEST_TIME constant. + * Wrapper method for \Drupal::time()->getRequestTime(). * * @return int */ protected function getRequestTime() { - return defined('REQUEST_TIME') ? REQUEST_TIME : (int) $_SERVER['REQUEST_TIME']; + return \Drupal::hasContainer() ? \Drupal::time()->getRequestTime() : (int) $_SERVER['REQUEST_TIME']; } } diff --git a/core/lib/Drupal/Core/Queue/DatabaseQueue.php b/core/lib/Drupal/Core/Queue/DatabaseQueue.php index 1d0621e0e5..fa043e4d3a 100644 --- a/core/lib/Drupal/Core/Queue/DatabaseQueue.php +++ b/core/lib/Drupal/Core/Queue/DatabaseQueue.php @@ -87,9 +87,10 @@ protected function doCreateItem($data) { ->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' => time(), + // We cannot rely on \Drupal::time()->getRequestTime() + // 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(); @@ -124,6 +125,30 @@ public function claimItem($lease_time = 30) { } catch (\Exception $e) { $this->catchException($e); + // If the table does not exist there are no items currently available to + // claim. + return FALSE; + } + if ($item) { + // Try to update the item. Only one thread can succeed in UPDATEing the + // same row. We cannot rely on \Drupal::time()->getRequestTime() + // because items might be claimed by a single consumer + // which runs longer than 1 second. If we continue to use + // \Drupal::time()->getRequestTime() instead of the current + // \Drupal::time()->getCurrentTime(), we steal time from the lease, + // and will tend to reset items + // before the lease should really expire. + $update = $this->connection->update(static::TABLE_NAME) + ->fields([ + 'expire' => \Drupal::time()->getCurrentTime() + $lease_time, + ]) + ->condition('item_id', $item->item_id) + ->condition('expire', 0); + // If there are affected rows, this update succeeded. + if ($update->execute()) { + $item->data = unserialize($item->data); + return $item; + } } // If the table does not exist there are no items currently available to @@ -214,7 +239,7 @@ public function garbageCollection() { try { // Clean up the queue for failed batches. $this->connection->delete(static::TABLE_NAME) - ->condition('created', REQUEST_TIME - 864000, '<') + ->condition('created', \Drupal::time()->getRequestTime() - 864000, '<') ->condition('name', 'drupal_batch:%', 'LIKE') ->execute(); @@ -225,7 +250,7 @@ public function garbageCollection() { 'expire' => 0, ]) ->condition('expire', 0, '<>') - ->condition('expire', REQUEST_TIME, '<') + ->condition('expire', \Drupal::time()->getRequestTime(), '<') ->execute(); } catch (\Exception $e) { diff --git a/core/lib/Drupal/Core/Queue/Memory.php b/core/lib/Drupal/Core/Queue/Memory.php index 2e4ac0f1c9..2bfab4e884 100644 --- a/core/lib/Drupal/Core/Queue/Memory.php +++ b/core/lib/Drupal/Core/Queue/Memory.php @@ -44,7 +44,7 @@ public function createItem($data) { $item = new \stdClass(); $item->item_id = $this->idSequence++; $item->data = $data; - $item->created = time(); + $item->created = \Drupal::time()->getCurrentTime(); $item->expire = 0; $this->queue[$item->item_id] = $item; return $item->item_id; @@ -63,7 +63,7 @@ public function numberOfItems() { public function claimItem($lease_time = 30) { foreach ($this->queue as $key => $item) { if ($item->expire == 0) { - $item->expire = time() + $lease_time; + $item->expire = \Drupal::time()->getCurrentTime() + $lease_time; $this->queue[$key] = $item; return $item; } diff --git a/core/lib/Drupal/Core/Session/SessionHandler.php b/core/lib/Drupal/Core/Session/SessionHandler.php index 784042aa68..0213060ac7 100644 --- a/core/lib/Drupal/Core/Session/SessionHandler.php +++ b/core/lib/Drupal/Core/Session/SessionHandler.php @@ -76,7 +76,7 @@ public function write($sid, $value) { 'uid' => $request->getSession()->get('uid', 0), 'hostname' => $request->getClientIP(), 'session' => $value, - 'timestamp' => REQUEST_TIME, + 'timestamp' => \Drupal::time()->getRequestTime(), ]; $this->connection->merge('sessions') ->keys(['sid' => Crypt::hashBase64($sid)]) @@ -125,7 +125,7 @@ public function gc($lifetime) { // to '1814400'. At that value, only after a user doesn't log in after // three weeks (1814400 seconds) will their session be removed. $this->connection->delete('sessions') - ->condition('timestamp', REQUEST_TIME - $lifetime, '<') + ->condition('timestamp', \Drupal::time()->getRequestTime() - $lifetime, '<') ->execute(); return TRUE; } diff --git a/core/lib/Drupal/Core/Session/SessionManager.php b/core/lib/Drupal/Core/Session/SessionManager.php index 27e05809ad..c63b59dc62 100644 --- a/core/lib/Drupal/Core/Session/SessionManager.php +++ b/core/lib/Drupal/Core/Session/SessionManager.php @@ -232,7 +232,7 @@ public function regenerate($destroy = FALSE, $lifetime = NULL) { if (isset($old_session_id)) { $params = session_get_cookie_params(); - $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0; + $expire = $params['lifetime'] ? \Drupal::time()->getRequestTime() + $params['lifetime'] : 0; setcookie($this->getName(), $this->getId(), $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']); $this->migrateStoredSession($old_session_id); } @@ -265,7 +265,7 @@ public function destroy() { // setcookie() can only be called when headers are not yet sent. if ($cookies->has($session_name) && !headers_sent()) { $params = session_get_cookie_params(); - setcookie($session_name, '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']); + setcookie($session_name, '', \Drupal::time()->getRequestTime() - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']); $cookies->remove($session_name); } } diff --git a/core/lib/Drupal/Core/Template/TwigPhpStorageCache.php b/core/lib/Drupal/Core/Template/TwigPhpStorageCache.php index 995ce97803..d50075e234 100644 --- a/core/lib/Drupal/Core/Template/TwigPhpStorageCache.php +++ b/core/lib/Drupal/Core/Template/TwigPhpStorageCache.php @@ -111,7 +111,7 @@ public function write($key, $content) { $this->storage()->save($key, $content); // Save the last mtime. $cid = 'twig:' . $key; - $this->cache->set($cid, REQUEST_TIME); + $this->cache->set($cid, \Drupal::time()->getRequestTime()); } /** diff --git a/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php b/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php index f3c5eab8ca..45c1ce4df0 100644 --- a/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php +++ b/core/lib/Drupal/Core/Test/FunctionalTestSetupTrait.php @@ -274,7 +274,7 @@ protected function prepareRequestForGenerator($clean_urls = TRUE, $override_serv $request = Request::create($request_path, 'GET', [], [], [], $server); // Ensure the request time is REQUEST_TIME to ensure that API calls // in the test use the right timestamp. - $request->server->set('REQUEST_TIME', REQUEST_TIME); + $request->server->set('REQUEST_TIME', \Drupal::time()->getRequestTime()); $this->container->get('request_stack')->push($request); // The request context is normally set by the router_listener from within diff --git a/core/modules/aggregator/aggregator.module b/core/modules/aggregator/aggregator.module index 336dbcef4e..3f74cfd1de 100644 --- a/core/modules/aggregator/aggregator.module +++ b/core/modules/aggregator/aggregator.module @@ -174,14 +174,14 @@ function aggregator_cron() { foreach (Feed::loadMultiple($ids) as $feed) { if ($queue->createItem($feed)) { // Add timestamp to avoid queueing item more than once. - $feed->setQueuedTime(REQUEST_TIME); + $feed->setQueuedTime(\Drupal::time()->getRequestTime()); $feed->save(); } } // Delete queued timestamp after 6 hours assuming the update has failed. $ids = \Drupal::entityQuery('aggregator_feed') - ->condition('queued', REQUEST_TIME - (3600 * 6), '<') + ->condition('queued', \Drupal::time()->getRequestTime() - (3600 * 6), '<') ->execute(); if ($ids) { diff --git a/core/modules/aggregator/src/Controller/AggregatorController.php b/core/modules/aggregator/src/Controller/AggregatorController.php index 5beb15441c..e85f19d65b 100644 --- a/core/modules/aggregator/src/Controller/AggregatorController.php +++ b/core/modules/aggregator/src/Controller/AggregatorController.php @@ -120,12 +120,12 @@ public function adminOverview() { $last_checked = $feed->getLastCheckedTime(); $refresh_rate = $feed->getRefreshRate(); - $row[] = ($last_checked ? $this->t('@time ago', ['@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $last_checked)]) : $this->t('never')); + $row[] = ($last_checked ? $this->t('@time ago', ['@time' => $this->dateFormatter->formatInterval(\Drupal::time()->getRequestTime() - $last_checked)]) : $this->t('never')); if (!$last_checked && $refresh_rate) { $next_update = $this->t('imminently'); } elseif ($last_checked && $refresh_rate) { - $next_update = $next = $this->t('%time left', ['%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - REQUEST_TIME)]); + $next_update = $next = $this->t('%time left', ['%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - \Drupal::time()->getRequestTime())]); } else { $next_update = $this->t('never'); diff --git a/core/modules/aggregator/src/Entity/Feed.php b/core/modules/aggregator/src/Entity/Feed.php index 4c3a5b856e..3e8dd3bea8 100644 --- a/core/modules/aggregator/src/Entity/Feed.php +++ b/core/modules/aggregator/src/Entity/Feed.php @@ -85,7 +85,7 @@ public function refreshItems() { $success = \Drupal::service('aggregator.items.importer')->refresh($this); // Regardless of successful or not, indicate that it has been checked. - $this->setLastCheckedTime(REQUEST_TIME); + $this->setLastCheckedTime(\Drupal::time()->getRequestTime()); $this->setQueuedTime(0); $this->save(); diff --git a/core/modules/aggregator/src/FeedStorage.php b/core/modules/aggregator/src/FeedStorage.php index fc5eddeae7..5dc7cbdcdf 100644 --- a/core/modules/aggregator/src/FeedStorage.php +++ b/core/modules/aggregator/src/FeedStorage.php @@ -17,7 +17,7 @@ class FeedStorage extends SqlContentEntityStorage implements FeedStorageInterfac */ public function getFeedIdsToRefresh() { return $this->database->query('SELECT fid FROM {' . $this->getBaseTable() . '} WHERE queued = 0 AND checked + refresh < :time AND refresh <> :never', [ - ':time' => REQUEST_TIME, + ':time' => \Drupal::time()->getRequestTime(), ':never' => static::CLEAR_NEVER, ])->fetchCol(); } diff --git a/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php b/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php index 5f0eade44e..caa360d2ac 100644 --- a/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php +++ b/core/modules/aggregator/src/Plugin/aggregator/processor/DefaultProcessor.php @@ -257,7 +257,7 @@ public function postProcess(FeedInterface $feed) { if ($aggregator_clear != FeedStorageInterface::CLEAR_NEVER) { // Delete all items that are older than flush item timer. - $age = REQUEST_TIME - $aggregator_clear; + $age = \Drupal::time()->getRequestTime() - $aggregator_clear; $result = $this->itemStorage->getQuery() ->condition('fid', $feed->id()) ->condition('timestamp', $age, '<') diff --git a/core/modules/aggregator/tests/src/Functional/AggregatorCronTest.php b/core/modules/aggregator/tests/src/Functional/AggregatorCronTest.php index acc6b61b5f..315a9a6849 100644 --- a/core/modules/aggregator/tests/src/Functional/AggregatorCronTest.php +++ b/core/modules/aggregator/tests/src/Functional/AggregatorCronTest.php @@ -36,7 +36,7 @@ public function testCron() { // Test feed locking when queued for update. $this->deleteFeedItems($feed); - $feed->setQueuedTime(REQUEST_TIME)->save(); + $feed->setQueuedTime(\Drupal::time()->getRequestTime())->save(); $this->cronRun(); $this->assertEqual(0, $count_query->execute()); $feed->setQueuedTime(0)->save(); diff --git a/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php b/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php index 7459cee66d..214bffb47c 100644 --- a/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php +++ b/core/modules/aggregator/tests/src/Kernel/Views/IntegrationTest.php @@ -81,7 +81,7 @@ public function testAggregatorItemView() { for ($i = 0; $i < 10; $i++) { $values = []; $values['fid'] = $feed->id(); - $values['timestamp'] = mt_rand(REQUEST_TIME - 10, REQUEST_TIME + 10); + $values['timestamp'] = mt_rand(\Drupal::time()->getRequestTime() - 10, \Drupal::time()->getRequestTime() + 10); $values['title'] = $this->randomMachineName(); $values['description'] = $this->randomMachineName(); // Add a image to ensure that the sanitizing can be tested below. diff --git a/core/modules/big_pipe/tests/modules/big_pipe_regression_test/src/BigPipeRegressionTestController.php b/core/modules/big_pipe/tests/modules/big_pipe_regression_test/src/BigPipeRegressionTestController.php index 6c1fde7331..f7cc704788 100644 --- a/core/modules/big_pipe/tests/modules/big_pipe_regression_test/src/BigPipeRegressionTestController.php +++ b/core/modules/big_pipe/tests/modules/big_pipe_regression_test/src/BigPipeRegressionTestController.php @@ -39,7 +39,7 @@ public function regression2802923() { */ public static function currentTime() { return [ - '#markup' => '', + '#markup' => '', '#cache' => ['max-age' => 0], ]; } diff --git a/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php b/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php index 743f85a381..c16e793f12 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentRevisionsTest.php @@ -56,7 +56,7 @@ protected function setUp() { $block->setNewRevision(TRUE); $block->setRevisionLogMessage($this->randomMachineName(32)); $block->setRevisionUser($this->adminUser); - $block->setRevisionCreationTime(REQUEST_TIME); + $block->setRevisionCreationTime(\Drupal::time()->getRequestTime()); $logs[] = $block->getRevisionLogMessage(); $block->save(); $blocks[] = $block->getRevisionId(); diff --git a/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php b/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php index b62ea413d8..6b8a3ded7e 100644 --- a/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php +++ b/core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php @@ -68,7 +68,7 @@ public function testImport() { public function testDeterminingChanges() { // Initial creation. $block = $this->createBlockContent('test_changes'); - $this->assertEqual($block->getChangedTime(), REQUEST_TIME, 'Creating a block sets default "changed" timestamp.'); + $this->assertEqual($block->getChangedTime(), \Drupal::time()->getRequestTime(), 'Creating a block sets default "changed" timestamp.'); // Update the block without applying changes. $block->save(); diff --git a/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateBlockContentTest.php b/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateBlockContentTest.php index 40c30a6715..f8b661deab 100644 --- a/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateBlockContentTest.php +++ b/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateBlockContentTest.php @@ -40,14 +40,14 @@ public function testBlockMigration() { /** @var \Drupal\block_content\Entity\BlockContent $block */ $block = BlockContent::load(1); $this->assertIdentical('My block 1', $block->label()); - $this->assertTrue(REQUEST_TIME <= $block->getChangedTime() && $block->getChangedTime() <= time()); + $this->assertTrue(\Drupal::time()->getRequestTime() <= $block->getChangedTime() && $block->getChangedTime() <= \Drupal::time()->getCurrentTime()); $this->assertIdentical('en', $block->language()->getId()); $this->assertIdentical('

My first custom block body

', $block->body->value); $this->assertIdentical('full_html', $block->body->format); $block = BlockContent::load(2); $this->assertIdentical('My block 2', $block->label()); - $this->assertTrue(REQUEST_TIME <= $block->getChangedTime() && $block->getChangedTime() <= time()); + $this->assertTrue(\Drupal::time()->getRequestTime() <= $block->getChangedTime() && $block->getChangedTime() <= \Drupal::time()->getCurrentTime()); $this->assertIdentical('en', $block->language()->getId()); $this->assertIdentical('

My second custom block body

', $block->body->value); $this->assertIdentical('full_html', $block->body->format); diff --git a/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateCustomBlockContentTranslationTest.php b/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateCustomBlockContentTranslationTest.php index 99bbc42855..1f75327f3a 100644 --- a/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateCustomBlockContentTranslationTest.php +++ b/core/modules/block_content/tests/src/Kernel/Migrate/d6/MigrateCustomBlockContentTranslationTest.php @@ -47,7 +47,7 @@ public function testCustomBlockContentTranslation() { /** @var \Drupal\block_content\Entity\BlockContent $block */ $block = BlockContent::load(1)->getTranslation('fr'); $this->assertSame('fr - Static Block', $block->label()); - $this->assertGreaterThanOrEqual(REQUEST_TIME, $block->getChangedTime()); + $this->assertGreaterThanOrEqual(\Drupal::time()->getRequestTime(), $block->getChangedTime()); $this->assertLessThanOrEqual(time(), $block->getChangedTime()); $this->assertSame('fr', $block->language()->getId()); $this->assertSame('

fr - My first custom block body

', $block->body->value); @@ -55,7 +55,7 @@ public function testCustomBlockContentTranslation() { $block = $block->getTranslation('zu'); $this->assertSame('My block 1', $block->label()); - $this->assertGreaterThanOrEqual(REQUEST_TIME, $block->getChangedTime()); + $this->assertGreaterThanOrEqual(\Drupal::time()->getRequestTime(), $block->getChangedTime()); $this->assertLessThanOrEqual(time(), $block->getChangedTime()); $this->assertSame('zu', $block->language()->getId()); $this->assertSame('

zu - My first custom block body

', $block->body->value); @@ -63,7 +63,7 @@ public function testCustomBlockContentTranslation() { $block = BlockContent::load(2)->getTranslation('fr'); $this->assertSame('Encore un bloc statique', $block->label()); - $this->assertGreaterThanOrEqual(REQUEST_TIME, $block->getChangedTime()); + $this->assertGreaterThanOrEqual(\Drupal::time()->getRequestTime(), $block->getChangedTime()); $this->assertLessThanOrEqual(time(), $block->getChangedTime()); $this->assertSame('fr', $block->language()->getId()); $this->assertSame('Nom de vocabulaire beaucoup plus long que trente-deux caractères', $block->body->value); diff --git a/core/modules/comment/src/CommentForm.php b/core/modules/comment/src/CommentForm.php index 48c72712df..b8197c8648 100644 --- a/core/modules/comment/src/CommentForm.php +++ b/core/modules/comment/src/CommentForm.php @@ -284,7 +284,7 @@ public function buildEntity(array $form, FormStateInterface $form_state) { $comment->setCreatedTime($form_state->getValue('date')->getTimestamp()); } else { - $comment->setCreatedTime(REQUEST_TIME); + $comment->setCreatedTime(\Drupal::time()->getRequestTime()); } // Empty author ID should revert to anonymous. $author_id = $form_state->getValue('uid'); diff --git a/core/modules/comment/src/CommentStatistics.php b/core/modules/comment/src/CommentStatistics.php index 1bcb22a38b..32867fe210 100644 --- a/core/modules/comment/src/CommentStatistics.php +++ b/core/modules/comment/src/CommentStatistics.php @@ -136,8 +136,9 @@ public function create(FieldableEntityInterface $entity, $fields) { // EntityOwnerInterface or author is not set. $last_comment_uid = $this->currentUser->id(); } - // Default to REQUEST_TIME when entity does not have a changed property. - $last_comment_timestamp = REQUEST_TIME; + // Default to \Drupal::time()->getRequestTime() when entity does not have + // a changed property. + $last_comment_timestamp = \Drupal::time()->getRequestTime(); // @todo Make comment statistics language aware and add some tests. See // https://www.drupal.org/node/2318875 if ($entity instanceof EntityChangedInterface) { @@ -258,8 +259,8 @@ public function update(CommentInterface $comment) { 'cid' => 0, 'comment_count' => 0, // Use the changed date of the entity if it's set, or default to - // REQUEST_TIME. - 'last_comment_timestamp' => ($entity instanceof EntityChangedInterface) ? $entity->getChangedTimeAcrossTranslations() : REQUEST_TIME, + // \Drupal::time()->getRequestTime(). + 'last_comment_timestamp' => ($entity instanceof EntityChangedInterface) ? $entity->getChangedTimeAcrossTranslations() : \Drupal::time()->getRequestTime(), 'last_comment_name' => '', 'last_comment_uid' => $last_comment_uid, ]) diff --git a/core/modules/comment/tests/src/Functional/CommentBlockTest.php b/core/modules/comment/tests/src/Functional/CommentBlockTest.php index 954728bf71..2c146e8f62 100644 --- a/core/modules/comment/tests/src/Functional/CommentBlockTest.php +++ b/core/modules/comment/tests/src/Functional/CommentBlockTest.php @@ -48,7 +48,7 @@ public function testRecentCommentBlock() { // Add some test comments, with and without subjects. Because the 10 newest // comments should be shown by the block, we create 11 to test that behavior // below. - $timestamp = REQUEST_TIME; + $timestamp = \Drupal::time()->getRequestTime(); for ($i = 0; $i < 11; ++$i) { $subject = ($i % 2) ? $this->randomMachineName() : ''; $comments[$i] = $this->postComment($this->node, $this->randomMachineName(), $subject); diff --git a/core/modules/comment/tests/src/Functional/CommentTranslationUITest.php b/core/modules/comment/tests/src/Functional/CommentTranslationUITest.php index 8f47909403..4f44357e2a 100644 --- a/core/modules/comment/tests/src/Functional/CommentTranslationUITest.php +++ b/core/modules/comment/tests/src/Functional/CommentTranslationUITest.php @@ -168,7 +168,7 @@ protected function doTestAuthoringInfo() { $user = $this->drupalCreateUser(); $values[$langcode] = [ 'uid' => $user->id(), - 'created' => REQUEST_TIME - mt_rand(0, 1000), + 'created' => \Drupal::time()->getRequestTime() - mt_rand(0, 1000), ]; /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */ $date_formatter = $this->container->get('date.formatter'); diff --git a/core/modules/comment/tests/src/Functional/Views/DefaultViewRecentCommentsTest.php b/core/modules/comment/tests/src/Functional/Views/DefaultViewRecentCommentsTest.php index b6f98a0dd2..d1de0b2a93 100644 --- a/core/modules/comment/tests/src/Functional/Views/DefaultViewRecentCommentsTest.php +++ b/core/modules/comment/tests/src/Functional/Views/DefaultViewRecentCommentsTest.php @@ -97,7 +97,7 @@ protected function setUp($import_test_views = TRUE) { $comment->comment_body->format = 'full_html'; // Ensure comments are sorted in ascending order. - $time = REQUEST_TIME + ($this->masterDisplayResults - $i); + $time = \Drupal::time()->getRequestTime() + ($this->masterDisplayResults - $i); $comment->setCreatedTime($time); $comment->changed->value = $time; diff --git a/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php b/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php index 7cef38b4d8..0d6a3a56ac 100644 --- a/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php +++ b/core/modules/comment/tests/src/Kernel/Views/CommentViewsFieldAccessTest.php @@ -78,7 +78,7 @@ public function testCommentFields() { $this->assertFieldAccess('comment', 'homepage', 'https://example.com'); $this->assertFieldAccess('comment', 'uid', $user->getAccountName()); // $this->assertFieldAccess('comment', 'created', \Drupal::service('date.formatter')->format(123456)); - // $this->assertFieldAccess('comment', 'changed', \Drupal::service('date.formatter')->format(REQUEST_TIME)); + // $this->assertFieldAccess('comment', 'changed', \Drupal::service('date.formatter')->format(\Drupal::time()->getRequestTime())); $this->assertFieldAccess('comment', 'status', 'On'); } diff --git a/core/modules/config_translation/src/FormElement/DateFormat.php b/core/modules/config_translation/src/FormElement/DateFormat.php index d0ae033a42..8cd218e0ec 100644 --- a/core/modules/config_translation/src/FormElement/DateFormat.php +++ b/core/modules/config_translation/src/FormElement/DateFormat.php @@ -16,7 +16,7 @@ public function getTranslationElement(LanguageInterface $translation_language, $ /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */ $date_formatter = \Drupal::service('date.formatter'); $description = $this->t('A user-defined date format. See the PHP manual for available options.'); - $format = $this->t('Displayed as %date_format', ['%date_format' => $date_formatter->format(REQUEST_TIME, 'custom', $translation_config)]); + $format = $this->t('Displayed as %date_format', ['%date_format' => $date_formatter->format(\Drupal::time()->getRequestTime(), 'custom', $translation_config)]); return [ '#type' => 'textfield', diff --git a/core/modules/content_translation/src/ContentTranslationHandler.php b/core/modules/content_translation/src/ContentTranslationHandler.php index 44dea176d5..8373515663 100644 --- a/core/modules/content_translation/src/ContentTranslationHandler.php +++ b/core/modules/content_translation/src/ContentTranslationHandler.php @@ -521,14 +521,14 @@ public function entityFormAlter(array &$form, FormStateInterface $form_state, En '#description' => t('Leave blank for %anonymous.', ['%anonymous' => \Drupal::config('user.settings')->get('anonymous')]), ]; - $date = $new_translation ? REQUEST_TIME : $metadata->getCreatedTime(); + $date = $new_translation ? \Drupal::time()->getRequestTime() : $metadata->getCreatedTime(); $form['content_translation']['created'] = [ '#type' => 'textfield', '#title' => t('Authored on'), '#maxlength' => 25, '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', [ - '%time' => $this->dateFormatter->format(REQUEST_TIME, 'custom', 'Y-m-d H:i:s O'), - '%timezone' => $this->dateFormatter->format(REQUEST_TIME, 'custom', 'O'), + '%time' => $this->dateFormatter->format(\Drupal::time()->getRequestTime(), 'custom', 'Y-m-d H:i:s O'), + '%timezone' => $this->dateFormatter->format(\Drupal::time()->getRequestTime(), 'custom', 'O'), ]), '#default_value' => $new_translation || !$date ? '' : $this->dateFormatter->format($date, 'custom', 'Y-m-d H:i:s O'), ]; @@ -678,7 +678,7 @@ public function entityFormEntityBuild($entity_type, EntityInterface $entity, arr $metadata = $this->manager->getTranslationMetadata($entity); $metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0)); $metadata->setPublished(!empty($values['status'])); - $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME); + $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : \Drupal::time()->getRequestTime()); $metadata->setOutdated(!empty($values['outdated'])); if (!empty($values['retranslate'])) { @@ -725,7 +725,7 @@ public function entityFormSubmit($form, FormStateInterface $form_state) { // handler as well and have the same logic like in the Form API. if ($entity->hasField('content_translation_changed')) { $metadata = $this->manager->getTranslationMetadata($entity); - $metadata->setChangedTime(REQUEST_TIME); + $metadata->setChangedTime(\Drupal::time()->getRequestTime()); } } diff --git a/core/modules/content_translation/src/Controller/ContentTranslationController.php b/core/modules/content_translation/src/Controller/ContentTranslationController.php index 5d48cc0533..c9eb61b4fa 100644 --- a/core/modules/content_translation/src/Controller/ContentTranslationController.php +++ b/core/modules/content_translation/src/Controller/ContentTranslationController.php @@ -88,7 +88,7 @@ public function prepareTranslation(ContentEntityInterface $entity, LanguageInter // Update the translation author to current user, as well the translation // creation time. $metadata->setAuthor($user); - $metadata->setCreatedTime(REQUEST_TIME); + $metadata->setCreatedTime(\Drupal::time()->getRequestTime()); $metadata->setSource($source_langcode); } diff --git a/core/modules/content_translation/src/Tests/ContentTranslationUITestBase.php b/core/modules/content_translation/src/Tests/ContentTranslationUITestBase.php index 1fbced6b0c..47e33e6f66 100644 --- a/core/modules/content_translation/src/Tests/ContentTranslationUITestBase.php +++ b/core/modules/content_translation/src/Tests/ContentTranslationUITestBase.php @@ -325,7 +325,7 @@ protected function doTestAuthoringInfo() { $user = $this->drupalCreateUser(); $values[$langcode] = [ 'uid' => $user->id(), - 'created' => REQUEST_TIME - mt_rand(0, 1000), + 'created' => $this->container->get('datetime.time')->getRequestTime() - mt_rand(0, 1000), ]; $edit = [ 'content_translation[uid]' => $user->getAccountName(), diff --git a/core/modules/content_translation/tests/src/Functional/ContentTranslationUITestBase.php b/core/modules/content_translation/tests/src/Functional/ContentTranslationUITestBase.php index 5e7954086f..a814836127 100644 --- a/core/modules/content_translation/tests/src/Functional/ContentTranslationUITestBase.php +++ b/core/modules/content_translation/tests/src/Functional/ContentTranslationUITestBase.php @@ -318,7 +318,7 @@ protected function doTestAuthoringInfo() { $user = $this->drupalCreateUser(); $values[$langcode] = [ 'uid' => $user->id(), - 'created' => REQUEST_TIME - mt_rand(0, 1000), + 'created' => \Drupal::time()->getRequestTime() - mt_rand(0, 1000), ]; $edit = [ 'content_translation[uid]' => $user->getAccountName(), diff --git a/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php b/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php index 3264069008..2c3ac8e90d 100644 --- a/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php +++ b/core/modules/datetime/src/Plugin/Field/FieldType/DateTimeItem.php @@ -107,7 +107,7 @@ public static function generateSampleValue(FieldDefinitionInterface $field_defin // Just pick a date in the past year. No guidance is provided by this Field // type. - $timestamp = REQUEST_TIME - mt_rand(0, 86400 * 365); + $timestamp = \Drupal::time()->getRequestTime() - mt_rand(0, 86400 * 365); if ($type == DateTimeItem::DATETIME_TYPE_DATE) { $values['value'] = gmdate(static::DATE_STORAGE_FORMAT, $timestamp); } diff --git a/core/modules/datetime/tests/src/Functional/DateTimeFieldTest.php b/core/modules/datetime/tests/src/Functional/DateTimeFieldTest.php index fd55a918f3..e65f0a986b 100644 --- a/core/modules/datetime/tests/src/Functional/DateTimeFieldTest.php +++ b/core/modules/datetime/tests/src/Functional/DateTimeFieldTest.php @@ -184,7 +184,7 @@ public function testDateField() { // 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 timezone. - $timestamp = REQUEST_TIME - 87654321; + $timestamp = \Drupal::time()->getRequestTime() - 87654321; $entity = EntityTest::load($id); $field_name = $this->fieldStorage->getName(); $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC'); @@ -214,7 +214,7 @@ public function testDateField() { // 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 timezone. - $timestamp = REQUEST_TIME + 87654321; + $timestamp = \Drupal::time()->getRequestTime() + 87654321; $entity = EntityTest::load($id); $field_name = $this->fieldStorage->getName(); $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC'); @@ -341,7 +341,7 @@ public function testDatetimeField() { // 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 timezone. - $timestamp = REQUEST_TIME - 87654321; + $timestamp = \Drupal::time()->getRequestTime() - 87654321; $entity = EntityTest::load($id); $field_name = $this->fieldStorage->getName(); $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC'); @@ -368,7 +368,7 @@ public function testDatetimeField() { // 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 timezone. - $timestamp = REQUEST_TIME + 87654321; + $timestamp = \Drupal::time()->getRequestTime() + 87654321; $entity = EntityTest::load($id); $field_name = $this->fieldStorage->getName(); $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC'); diff --git a/core/modules/datetime/tests/src/Kernel/Views/FilterDateTimeTest.php b/core/modules/datetime/tests/src/Kernel/Views/FilterDateTimeTest.php index 13b2759bb0..73742cb71b 100644 --- a/core/modules/datetime/tests/src/Kernel/Views/FilterDateTimeTest.php +++ b/core/modules/datetime/tests/src/Kernel/Views/FilterDateTimeTest.php @@ -38,7 +38,7 @@ class FilterDateTimeTest extends DateTimeHandlerTestBase { protected function setUp($import_test_views = TRUE) { parent::setUp($import_test_views); - static::$date = REQUEST_TIME + 86400; + static::$date = \Drupal::time()->getRequestTime() + 86400; // Set the timezone. date_default_timezone_set(static::$timezone); diff --git a/core/modules/datetime_range/src/Plugin/Field/FieldType/DateRangeItem.php b/core/modules/datetime_range/src/Plugin/Field/FieldType/DateRangeItem.php index 7c34ed127c..3a7d742525 100644 --- a/core/modules/datetime_range/src/Plugin/Field/FieldType/DateRangeItem.php +++ b/core/modules/datetime_range/src/Plugin/Field/FieldType/DateRangeItem.php @@ -94,7 +94,7 @@ public static function generateSampleValue(FieldDefinitionInterface $field_defin // Just pick a date in the past year. No guidance is provided by this Field // type. - $start = REQUEST_TIME - mt_rand(0, 86400 * 365) - 86400; + $start = \Drupal::time()->getRequestTime() - mt_rand(0, 86400 * 365) - 86400; $end = $start + 86400; if ($type == static::DATETIME_TYPE_DATETIME) { $values['value'] = gmdate(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, $start); diff --git a/core/modules/dblog/tests/src/Functional/DbLogTest.php b/core/modules/dblog/tests/src/Functional/DbLogTest.php index 9f7475b82d..8648390713 100644 --- a/core/modules/dblog/tests/src/Functional/DbLogTest.php +++ b/core/modules/dblog/tests/src/Functional/DbLogTest.php @@ -115,7 +115,7 @@ public function testLogEventPage() { 'channel' => 'testing', 'link' => 'foo/bar', 'ip' => '0.0.1.0', - 'timestamp' => REQUEST_TIME, + 'timestamp' => \Drupal::time()->getRequestTime(), ]; \Drupal::service('logger.dblog')->log(RfcLogLevel::NOTICE, 'Test message', $context); $wid = Database::getConnection()->query('SELECT MAX(wid) FROM {watchdog}')->fetchField(); @@ -545,7 +545,7 @@ public function testDBLogAddAndClear() { 'request_uri' => $base_root . \Drupal::request()->getRequestUri(), 'referer' => \Drupal::request()->server->get('HTTP_REFERER'), 'ip' => '127.0.0.1', - 'timestamp' => REQUEST_TIME, + 'timestamp' => \Drupal::time()->getRequestTime(), ]; // Add a watchdog entry. $this->container->get('logger.dblog')->log($log['severity'], $log['message'], $log); diff --git a/core/modules/dblog/tests/src/Functional/FakeLogEntries.php b/core/modules/dblog/tests/src/Functional/FakeLogEntries.php index 588510eebc..1d548f6bf6 100644 --- a/core/modules/dblog/tests/src/Functional/FakeLogEntries.php +++ b/core/modules/dblog/tests/src/Functional/FakeLogEntries.php @@ -50,7 +50,7 @@ private function generateLogEntries($count, $options = []) { 'request_uri' => $base_root . \Drupal::request()->getRequestUri(), 'referer' => \Drupal::request()->server->get('HTTP_REFERER'), 'ip' => '127.0.0.1', - 'timestamp' => REQUEST_TIME, + 'timestamp' => \Drupal::time()->getRequestTime(), ]; $logger = $this->container->get('logger.dblog'); diff --git a/core/modules/field/tests/src/Functional/FieldImportDeleteUninstallUiTest.php b/core/modules/field/tests/src/Functional/FieldImportDeleteUninstallUiTest.php index 1307422bc0..d6ed51ad91 100644 --- a/core/modules/field/tests/src/Functional/FieldImportDeleteUninstallUiTest.php +++ b/core/modules/field/tests/src/Functional/FieldImportDeleteUninstallUiTest.php @@ -67,7 +67,7 @@ public function testImportDeleteUninstall() { $entity = EntityTest::create(); $value = '+0123456789'; $entity->field_tel = $value; - $entity->field_date = time(); + $entity->field_date = \Drupal::time()->getCurrentTime(); $entity->name->value = $this->randomMachineName(); $entity->save(); diff --git a/core/modules/field/tests/src/Functional/NestedFormTest.php b/core/modules/field/tests/src/Functional/NestedFormTest.php index 0a646e3d5c..6776234670 100644 --- a/core/modules/field/tests/src/Functional/NestedFormTest.php +++ b/core/modules/field/tests/src/Functional/NestedFormTest.php @@ -191,11 +191,11 @@ public function testNestedEntityFormEntityLevelValidation() { // Display the 'combined form'. $this->drupalGet("test-entity-constraints/nested/{$entity_1->id()}/{$entity_2->id()}"); - $assert_session->hiddenFieldValueEquals('entity_2[changed]', REQUEST_TIME); + $assert_session->hiddenFieldValueEquals('entity_2[changed]', \Drupal::time()->getRequestTime()); // Submit the form and check that the entities are updated accordingly. $assert_session->hiddenFieldExists('entity_2[changed]') - ->setValue(REQUEST_TIME - 86400); + ->setValue(\Drupal::time()->getRequestTime() - 86400); $page->pressButton(t('Save')); $elements = $this->cssSelect('.entity-2.error'); diff --git a/core/modules/field/tests/src/Functional/Update/FieldUpdateTest.php b/core/modules/field/tests/src/Functional/Update/FieldUpdateTest.php index bec6e96546..dc386272c1 100644 --- a/core/modules/field/tests/src/Functional/Update/FieldUpdateTest.php +++ b/core/modules/field/tests/src/Functional/Update/FieldUpdateTest.php @@ -180,7 +180,7 @@ public function testFieldUpdate8500() { $this->assertArrayHasKey($field_storage_uuid, $deleted_field_storages); // Ensure that cron does not run automatically after running the updates. - $this->state->set('system.cron_last', REQUEST_TIME + 100); + $this->state->set('system.cron_last', \Drupal::time()->getRequestTime() + 100); // Run updates. $this->runUpdates(); diff --git a/core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php b/core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php index d7a771729d..e67e7ce381 100644 --- a/core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php +++ b/core/modules/field/tests/src/Kernel/Timestamp/TimestampFormatterTest.php @@ -118,7 +118,7 @@ public function testTimestampFormatter() { $timezone = NULL; } - $value = REQUEST_TIME - 87654321; + $value = \Drupal::time()->getRequestTime() - 87654321; $expected = \Drupal::service('date.formatter')->format($value, $date_format, $custom_date_format, $timezone); $component = $this->display->getComponent($this->fieldName); diff --git a/core/modules/file/file.module b/core/modules/file/file.module index c0abe888b4..a7d3b5115d 100644 --- a/core/modules/file/file.module +++ b/core/modules/file/file.module @@ -739,7 +739,7 @@ function file_cron() { if ($age) { $fids = Drupal::entityQuery('file') ->condition('status', FILE_STATUS_PERMANENT, '<>') - ->condition('changed', REQUEST_TIME - $age, '<') + ->condition('changed', \Drupal::time()->getRequestTime() - $age, '<') ->range(0, 100) ->execute(); $files = $file_storage->loadMultiple($fids); diff --git a/core/modules/file/tests/src/Functional/FileFieldPathTest.php b/core/modules/file/tests/src/Functional/FileFieldPathTest.php index f89e9982b8..0eabc67f30 100644 --- a/core/modules/file/tests/src/Functional/FileFieldPathTest.php +++ b/core/modules/file/tests/src/Functional/FileFieldPathTest.php @@ -40,8 +40,8 @@ public function testUploadPath() { $date_formatter = $this->container->get('date.formatter'); $expected_filename = 'public://' . - $date_formatter->format(REQUEST_TIME, 'custom', 'Y') . '-' . - $date_formatter->format(REQUEST_TIME, 'custom', 'm') . '/' . + $date_formatter->format(\Drupal::time()->getRequestTime(), 'custom', 'Y') . '-' . + $date_formatter->format(\Drupal::time()->getRequestTime(), 'custom', 'm') . '/' . $test_file->getFilename(); $this->assertPathMatch($expected_filename, $node_file->getFileUri(), new FormattableMarkup('The file %file was uploaded to the correct path.', ['%file' => $node_file->getFileUri()])); diff --git a/core/modules/file/tests/src/Functional/FileFieldRevisionTest.php b/core/modules/file/tests/src/Functional/FileFieldRevisionTest.php index 39136b2f55..e41273149e 100644 --- a/core/modules/file/tests/src/Functional/FileFieldRevisionTest.php +++ b/core/modules/file/tests/src/Functional/FileFieldRevisionTest.php @@ -128,7 +128,7 @@ public function testRevisions() { $connection = Database::getConnection(); $connection->update('file_managed') ->fields([ - 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), + 'changed' => \Drupal::time()->getRequestTime() - ($this->config('system.file')->get('temporary_maximum_age') + 1), ]) ->condition('fid', $node_file_r3->id()) ->execute(); @@ -145,7 +145,7 @@ public function testRevisions() { // would set the timestamp. $connection->update('file_managed') ->fields([ - 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), + 'changed' => \Drupal::time()->getRequestTime() - ($this->config('system.file')->get('temporary_maximum_age') + 1), ]) ->condition('fid', $node_file_r1->id()) ->execute(); diff --git a/core/modules/file/tests/src/Kernel/DeleteTest.php b/core/modules/file/tests/src/Kernel/DeleteTest.php index e8be244534..c5e9519eae 100644 --- a/core/modules/file/tests/src/Kernel/DeleteTest.php +++ b/core/modules/file/tests/src/Kernel/DeleteTest.php @@ -65,7 +65,7 @@ public function testInUse() { // would set the timestamp. Database::getConnection()->update('file_managed') ->fields([ - 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), + 'changed' => \Drupal::time()->getRequestTime() - ($this->config('system.file')->get('temporary_maximum_age') + 1), ]) ->condition('fid', $file->id()) ->execute(); @@ -92,7 +92,7 @@ public function testCronDeleteNonExistingTemporary() { // configuration value. \Drupal::database()->update('file_managed') ->fields([ - 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), + 'changed' => \Drupal::time()->getRequestTime() - ($this->config('system.file')->get('temporary_maximum_age') + 1), ]) ->condition('fid', $file->id()) ->execute(); diff --git a/core/modules/file/tests/src/Kernel/UsageTest.php b/core/modules/file/tests/src/Kernel/UsageTest.php index cc64cd8107..f33c0ad42e 100644 --- a/core/modules/file/tests/src/Kernel/UsageTest.php +++ b/core/modules/file/tests/src/Kernel/UsageTest.php @@ -159,7 +159,7 @@ public function createTempFiles() { $connection->update('file_managed') ->fields([ 'status' => 0, - 'changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1, + 'changed' => \Drupal::time()->getRequestTime() - $this->config('system.file')->get('temporary_maximum_age') - 1, ]) ->condition('fid', $temp_old->id()) ->execute(); @@ -176,7 +176,7 @@ public function createTempFiles() { // Permanent file that is old. $perm_old = file_save_data(''); $connection->update('file_managed') - ->fields(['changed' => REQUEST_TIME - $this->config('system.file')->get('temporary_maximum_age') - 1]) + ->fields(['changed' => \Drupal::time()->getRequestTime() - $this->config('system.file')->get('temporary_maximum_age') - 1]) ->condition('fid', $temp_old->id()) ->execute(); $this->assertTrue(file_exists($perm_old->getFileUri()), 'Old permanent file was created correctly.'); diff --git a/core/modules/file/tests/src/Kernel/Views/FileViewsFieldAccessTest.php b/core/modules/file/tests/src/Kernel/Views/FileViewsFieldAccessTest.php index 539cb5d41f..46aa131aa5 100644 --- a/core/modules/file/tests/src/Kernel/Views/FileViewsFieldAccessTest.php +++ b/core/modules/file/tests/src/Kernel/Views/FileViewsFieldAccessTest.php @@ -64,7 +64,7 @@ public function testFileFields() { $this->assertFieldAccess('file', 'filesize', '4 bytes'); $this->assertFieldAccess('file', 'status', t('Permanent')); // $this->assertFieldAccess('file', 'created', \Drupal::service('date.formatter')->format(123456)); - // $this->assertFieldAccess('file', 'changed', \Drupal::service('date.formatter')->format(REQUEST_TIME)); + // $this->assertFieldAccess('file', 'changed', \Drupal::service('date.formatter')->format(\Drupal::time()->getRequestTime())); } } diff --git a/core/modules/history/history.module b/core/modules/history/history.module index 11a45307bb..e415a4ad06 100644 --- a/core/modules/history/history.module +++ b/core/modules/history/history.module @@ -115,11 +115,11 @@ function history_write($nid, $account = NULL) { 'uid' => $account->id(), 'nid' => $nid, ]) - ->fields(['timestamp' => REQUEST_TIME]) + ->fields(['timestamp' => \Drupal::time()->getRequestTime()]) ->execute(); // Update static cache. $history = &drupal_static('history_read_multiple', []); - $history[$nid] = REQUEST_TIME; + $history[$nid] = \Drupal::time()->getRequestTime(); } } diff --git a/core/modules/history/src/Plugin/views/filter/HistoryUserTimestamp.php b/core/modules/history/src/Plugin/views/filter/HistoryUserTimestamp.php index 02288da1c4..a01b1b21d8 100644 --- a/core/modules/history/src/Plugin/views/filter/HistoryUserTimestamp.php +++ b/core/modules/history/src/Plugin/views/filter/HistoryUserTimestamp.php @@ -81,7 +81,7 @@ public function query() { // Hey, Drupal kills old history, so nodes that haven't been updated // since HISTORY_READ_LIMIT are bzzzzzzzt outta here! - $limit = REQUEST_TIME - HISTORY_READ_LIMIT; + $limit = \Drupal::time()->getRequestTime() - HISTORY_READ_LIMIT; $this->ensureMyTable(); $field = "$this->tableAlias.$this->realField"; diff --git a/core/modules/history/tests/src/Kernel/HistoryLegacyTest.php b/core/modules/history/tests/src/Kernel/HistoryLegacyTest.php index 82d0b3345f..756f3feed9 100644 --- a/core/modules/history/tests/src/Kernel/HistoryLegacyTest.php +++ b/core/modules/history/tests/src/Kernel/HistoryLegacyTest.php @@ -54,7 +54,7 @@ public function testHistoryAttachTimestamp() { history_write(1); $render = history_attach_timestamp(1); - $this->assertEquals(REQUEST_TIME, $render['#attached']['drupalSettings']['history']['lastReadTimestamps'][1]); + $this->assertEquals(\Drupal::time()->getRequestTime(), $render['#attached']['drupalSettings']['history']['lastReadTimestamps'][1]); } } diff --git a/core/modules/history/tests/src/Kernel/Views/HistoryTimestampTest.php b/core/modules/history/tests/src/Kernel/Views/HistoryTimestampTest.php index 9baeff7b29..3735f7a8d9 100644 --- a/core/modules/history/tests/src/Kernel/Views/HistoryTimestampTest.php +++ b/core/modules/history/tests/src/Kernel/Views/HistoryTimestampTest.php @@ -73,14 +73,14 @@ public function testHandlers() { ->fields([ 'uid' => $account->id(), 'nid' => $nodes[0]->id(), - 'timestamp' => REQUEST_TIME - 100, + 'timestamp' => \Drupal::time()->getRequestTime() - 100, ])->execute(); $connection->insert('history') ->fields([ 'uid' => $account->id(), 'nid' => $nodes[1]->id(), - 'timestamp' => REQUEST_TIME + 100, + 'timestamp' => \Drupal::time()->getRequestTime() + 100, ])->execute(); $column_map = [ diff --git a/core/modules/image/image.admin.inc b/core/modules/image/image.admin.inc index e43bd48765..fccc54b81b 100644 --- a/core/modules/image/image.admin.inc +++ b/core/modules/image/image.admin.inc @@ -23,7 +23,7 @@ function template_preprocess_image_style_preview(&$variables) { $variables['style_name'] = $style->label(); // Cache bypass token. - $variables['cache_bypass'] = REQUEST_TIME; + $variables['cache_bypass'] = \Drupal::time()->getRequestTime(); // Sample image info. $sample_width = 160; diff --git a/core/modules/layout_builder/tests/modules/layout_builder_test/src/Plugin/Block/TestAjaxBlock.php b/core/modules/layout_builder/tests/modules/layout_builder_test/src/Plugin/Block/TestAjaxBlock.php index 1f1eeb0d7f..9866f17d67 100644 --- a/core/modules/layout_builder/tests/modules/layout_builder_test/src/Plugin/Block/TestAjaxBlock.php +++ b/core/modules/layout_builder/tests/modules/layout_builder_test/src/Plugin/Block/TestAjaxBlock.php @@ -29,7 +29,7 @@ public function blockForm($form, FormStateInterface $form_state) { '#prefix' => '
', '#suffix' => '
', '#title' => $this->t('Time in this ajax test is @time', [ - '@time' => time(), + '@time' => \Drupal::time()->getCurrentTime(), ]), '#ajax' => [ 'wrapper' => 'test-ajax-wrapper', diff --git a/core/modules/locale/locale.batch.inc b/core/modules/locale/locale.batch.inc index 4829363b6b..6aeb611ac4 100644 --- a/core/modules/locale/locale.batch.inc +++ b/core/modules/locale/locale.batch.inc @@ -118,7 +118,7 @@ function locale_translation_batch_status_finished($success, $results) { if (!isset($results['failed_files']) && !isset($results['files'])) { \Drupal::messenger()->addStatus(t('Nothing to check.')); } - \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME); + \Drupal::state()->set('locale.translation_last_checked', \Drupal::time()->getRequestTime()); } else { \Drupal::messenger()->addError(t('An error occurred trying to check available interface translation updates.')); @@ -218,7 +218,7 @@ function locale_translation_batch_fetch_import($project, $langcode, $options, &$ function locale_translation_batch_fetch_finished($success, $results) { module_load_include('bulk.inc', 'locale'); if ($success) { - \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME); + \Drupal::state()->set('locale.translation_last_checked', \Drupal::time()->getRequestTime()); } return locale_translate_batch_finished($success, $results); } diff --git a/core/modules/locale/locale.bulk.inc b/core/modules/locale/locale.bulk.inc index 37c4522092..f2afdd042a 100644 --- a/core/modules/locale/locale.bulk.inc +++ b/core/modules/locale/locale.bulk.inc @@ -285,7 +285,7 @@ function locale_translate_batch_import_save($context) { // translation files are not tracked and are therefore not stored in this // table. if ($file->project && $file->version) { - $file->last_checked = REQUEST_TIME; + $file->last_checked = \Drupal::time()->getRequestTime(); locale_translation_update_file_history($file); } } diff --git a/core/modules/locale/locale.compare.inc b/core/modules/locale/locale.compare.inc index 317b45adb5..c60514bf0b 100644 --- a/core/modules/locale/locale.compare.inc +++ b/core/modules/locale/locale.compare.inc @@ -190,7 +190,7 @@ function locale_translation_check_projects($projects = [], $langcodes = []) { else { // Retrieve and save the status of local translations only. locale_translation_check_projects_local($projects, $langcodes); - \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME); + \Drupal::state()->set('locale.translation_last_checked', \Drupal::time()->getRequestTime()); } } diff --git a/core/modules/locale/locale.module b/core/modules/locale/locale.module index 40cd9d2491..1c7182b6b6 100644 --- a/core/modules/locale/locale.module +++ b/core/modules/locale/locale.module @@ -942,14 +942,14 @@ function locale_translation_status_save($project, $langcode, $type, $data) { if (isset($data->timestamp) && $data->timestamp) { if ($data->timestamp > $status[$project][$langcode]->timestamp) { $status[$project][$langcode]->timestamp = $data->timestamp; - $status[$project][$langcode]->last_checked = REQUEST_TIME; + $status[$project][$langcode]->last_checked = \Drupal::time()->getRequestTime(); $status[$project][$langcode]->type = $type; } } break; case LOCALE_TRANSLATION_CURRENT: - $data->last_checked = REQUEST_TIME; + $data->last_checked = \Drupal::time()->getRequestTime(); $status[$project][$langcode]->timestamp = $data->timestamp; $status[$project][$langcode]->last_checked = $data->last_checked; $status[$project][$langcode]->type = $type; @@ -958,7 +958,7 @@ function locale_translation_status_save($project, $langcode, $type, $data) { } \Drupal::keyValue('locale.translation_status')->set($project, $status[$project]); - \Drupal::state()->set('locale.translation_last_checked', REQUEST_TIME); + \Drupal::state()->set('locale.translation_last_checked', \Drupal::time()->getRequestTime()); } } diff --git a/core/modules/locale/locale.translation.inc b/core/modules/locale/locale.translation.inc index 2672d5c38a..be8734dc6d 100644 --- a/core/modules/locale/locale.translation.inc +++ b/core/modules/locale/locale.translation.inc @@ -331,7 +331,7 @@ function locale_cron_fill_queue() { $config = \Drupal::config('locale.settings'); // Determine which project+language should be updated. - $last = REQUEST_TIME - $config->get('translation.update_interval_days') * 3600 * 24; + $last = \Drupal::time()->getRequestTime() - $config->get('translation.update_interval_days') * 3600 * 24; $projects = \Drupal::service('locale.project')->getAll(); $projects = array_filter($projects, function ($project) { return $project['status'] == 1; @@ -348,7 +348,7 @@ function locale_cron_fill_queue() { // Update the last_checked timestamp of the project+language that will // be checked for updates. $connection->update('locale_file') - ->fields(['last_checked' => REQUEST_TIME]) + ->fields(['last_checked' => \Drupal::time()->getRequestTime()]) ->condition('project', $file->project) ->condition('langcode', $file->langcode) ->execute(); diff --git a/core/modules/locale/src/Form/TranslationStatusForm.php b/core/modules/locale/src/Form/TranslationStatusForm.php index a6d914afe9..2986ea9c91 100644 --- a/core/modules/locale/src/Form/TranslationStatusForm.php +++ b/core/modules/locale/src/Form/TranslationStatusForm.php @@ -280,7 +280,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { // translation updates. If the status is expired we clear it an run a batch to // update the status and then fetch the translation updates. $last_checked = $this->state->get('locale.translation_last_checked'); - if ($last_checked < REQUEST_TIME - LOCALE_TRANSLATION_STATUS_TTL) { + if ($last_checked < \Drupal::time()->getRequestTime() - LOCALE_TRANSLATION_STATUS_TTL) { locale_translation_clear_status(); $batch = locale_translation_batch_update_build([], $langcodes, $options); batch_set($batch); diff --git a/core/modules/locale/tests/src/Functional/LocalePluralFormatTest.php b/core/modules/locale/tests/src/Functional/LocalePluralFormatTest.php index b85e737a06..4b54dcdba4 100644 --- a/core/modules/locale/tests/src/Functional/LocalePluralFormatTest.php +++ b/core/modules/locale/tests/src/Functional/LocalePluralFormatTest.php @@ -170,7 +170,7 @@ public function testPluralEditDateFormatter() { // Visit User Info page before updating translation strings. Change the // created time to ensure that the we're dealing in seconds and it can't be // exactly 1 minute. - $this->adminUser->set('created', time() - 1)->save(); + $this->adminUser->set('created', \Drupal::time()->getCurrentTime() - 1)->save(); $this->drupalGet('user'); // Member for time should be translated. @@ -214,7 +214,7 @@ public function testPluralEditDateFormatter() { // Member for time should be translated. Change the created time to ensure // that the we're dealing in multiple seconds and it can't be exactly 1 // second or minute. - $this->adminUser->set('created', time() - 2)->save(); + $this->adminUser->set('created', \Drupal::time()->getCurrentTime() - 2)->save(); $this->drupalGet('user'); $this->assertText("secondes updated", "'Member for' text is translated."); } diff --git a/core/modules/locale/tests/src/Functional/LocaleUpdateBase.php b/core/modules/locale/tests/src/Functional/LocaleUpdateBase.php index 2e2d82b633..d4087c4d54 100644 --- a/core/modules/locale/tests/src/Functional/LocaleUpdateBase.php +++ b/core/modules/locale/tests/src/Functional/LocaleUpdateBase.php @@ -56,10 +56,10 @@ protected function setUp() { parent::setUp(); // Setup timestamps to identify old and new translation sources. - $this->timestampOld = REQUEST_TIME - 300; - $this->timestampMedium = REQUEST_TIME - 200; - $this->timestampNew = REQUEST_TIME - 100; - $this->timestampNow = REQUEST_TIME; + $this->timestampOld = \Drupal::time()->getRequestTime() - 300; + $this->timestampMedium = \Drupal::time()->getRequestTime() - 200; + $this->timestampNew = \Drupal::time()->getRequestTime() - 100; + $this->timestampNow = \Drupal::time()->getRequestTime(); // Enable import of translations. By default this is disabled for automated // tests. @@ -109,7 +109,7 @@ protected function addLanguage($langcode) { * in source and translations strings. */ protected function makePoFile($path, $filename, $timestamp = NULL, array $translations = []) { - $timestamp = $timestamp ? $timestamp : REQUEST_TIME; + $timestamp = $timestamp ? $timestamp : \Drupal::time()->getRequestTime(); $path = 'public://' . $path; $text = ''; $po_header = <<realpath($contrib_module_two_uri), REQUEST_TIME); + touch(\Drupal::service('file_system')->realpath($contrib_module_two_uri), \Drupal::time()->getRequestTime()); // Prepare for test: Simulate that the file has not been checked for a long // time. Set the last_check timestamp to zero. diff --git a/core/modules/locale/tests/src/Functional/LocaleUpdateInterfaceTest.php b/core/modules/locale/tests/src/Functional/LocaleUpdateInterfaceTest.php index 516d5b6386..3c7fb55bfd 100644 --- a/core/modules/locale/tests/src/Functional/LocaleUpdateInterfaceTest.php +++ b/core/modules/locale/tests/src/Functional/LocaleUpdateInterfaceTest.php @@ -110,7 +110,7 @@ public function testInterface() { // Override Drupal core translation status as 'translations available'. $status = locale_translation_get_status(); $status['drupal']['de']->type = 'local'; - $status['drupal']['de']->files['local']->timestamp = REQUEST_TIME; + $status['drupal']['de']->files['local']->timestamp = \Drupal::time()->getRequestTime(); $status['drupal']['de']->files['local']->info['version'] = '8.1.1'; \Drupal::keyValue('locale.translation_status')->set('drupal', $status['drupal']); @@ -119,7 +119,7 @@ public function testInterface() { $this->assertText(t('Updates for: @project', ['@project' => t('Drupal core')]), 'Translations found'); $this->assertText(new FormattableMarkup('@module (@date)', [ '@module' => t('Drupal core'), - '@date' => $this->container->get('date.formatter')->format(REQUEST_TIME, 'html_date'), + '@date' => $this->container->get('date.formatter')->format(\Drupal::time()->getRequestTime(), 'html_date'), ]), 'Core translation update'); $update_button = $this->xpath('//input[@type="submit"][@value="' . t('Update translations') . '"]'); $this->assertNotEmpty($update_button, 'Update translations button'); diff --git a/core/modules/menu_link_content/tests/src/Kernel/MenuLinksTest.php b/core/modules/menu_link_content/tests/src/Kernel/MenuLinksTest.php index c5bf428eb7..87aa99f097 100644 --- a/core/modules/menu_link_content/tests/src/Kernel/MenuLinksTest.php +++ b/core/modules/menu_link_content/tests/src/Kernel/MenuLinksTest.php @@ -137,7 +137,7 @@ public function testCreateLink() { $link = MenuLinkContent::create($options); $link->save(); // Make sure the changed timestamp is set. - $this->assertEqual($link->getChangedTime(), REQUEST_TIME, 'Creating a menu link sets the "changed" timestamp.'); + $this->assertEqual($link->getChangedTime(), \Drupal::time()->getRequestTime(), 'Creating a menu link sets the "changed" timestamp.'); $options = [ 'title' => 'Test Link', ]; @@ -145,7 +145,7 @@ public function testCreateLink() { $link->changed->value = 0; $link->save(); // Make sure the changed timestamp is updated. - $this->assertEqual($link->getChangedTime(), REQUEST_TIME, 'Changing a menu link sets "changed" timestamp.'); + $this->assertEqual($link->getChangedTime(), \Drupal::time()->getRequestTime(), 'Changing a menu link sets "changed" timestamp.'); } /** diff --git a/core/modules/migrate/src/Plugin/migrate/id_map/Sql.php b/core/modules/migrate/src/Plugin/migrate/id_map/Sql.php index 3e30634437..4fbcd54a69 100644 --- a/core/modules/migrate/src/Plugin/migrate/id_map/Sql.php +++ b/core/modules/migrate/src/Plugin/migrate/id_map/Sql.php @@ -640,7 +640,7 @@ public function saveIdMapping(Row $row, array $destination_id_values, $source_ro return; } if ($this->migration->getTrackLastImported()) { - $fields['last_imported'] = time(); + $fields['last_imported'] = \Drupal::time()->getCurrentTime(); } $keys = [$this::SOURCE_IDS_HASH => $this->getSourceIdsHash($source_id_values)]; // Notify anyone listening of the map row we're about to save. diff --git a/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php b/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php index c9c19a5c30..d66c4cb71e 100644 --- a/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php +++ b/core/modules/migrate_drupal_ui/src/Batch/MigrateUpgradeImportBatch.php @@ -286,7 +286,7 @@ public static function finished($success, $results, $operations, $elapsed) { */ public static function onPostRowSave(MigratePostRowSaveEvent $event) { // We want to interrupt this batch and start a fresh one. - if ((time() - REQUEST_TIME) > static::$maxExecTime) { + if ((time() - \Drupal::time()->getRequestTime()) > static::$maxExecTime) { $event->getMigration()->interruptMigration(MigrationInterface::RESULT_INCOMPLETE); } } @@ -317,7 +317,7 @@ public static function onPostImport(MigrateImportEvent $event) { */ public static function onPostRowDelete(MigrateRowDeleteEvent $event) { // We want to interrupt this batch and start a fresh one. - if ((time() - REQUEST_TIME) > static::$maxExecTime) { + if ((time() - \Drupal::time()->getRequestTime()) > static::$maxExecTime) { $event->getMigration()->interruptMigration(MigrationInterface::RESULT_INCOMPLETE); } } diff --git a/core/modules/migrate_drupal_ui/src/Form/ReviewForm.php b/core/modules/migrate_drupal_ui/src/Form/ReviewForm.php index 5be85c42f2..74072e721a 100644 --- a/core/modules/migrate_drupal_ui/src/Form/ReviewForm.php +++ b/core/modules/migrate_drupal_ui/src/Form/ReviewForm.php @@ -244,7 +244,7 @@ public function submitForm(array &$form, FormStateInterface $form_state) { batch_set($batch); $form_state->setRedirect(''); $this->store->set('step', 'overview'); - $this->state->set('migrate_drupal_ui.performed', REQUEST_TIME); + $this->state->set('migrate_drupal_ui.performed', \Drupal::time()->getRequestTime()); } /** diff --git a/core/modules/node/tests/src/Functional/NodeAdminTest.php b/core/modules/node/tests/src/Functional/NodeAdminTest.php index 9cbb42d9d1..09bec0e16b 100644 --- a/core/modules/node/tests/src/Functional/NodeAdminTest.php +++ b/core/modules/node/tests/src/Functional/NodeAdminTest.php @@ -72,7 +72,7 @@ protected function setUp() { public function testContentAdminSort() { $this->drupalLogin($this->adminUser); - $changed = REQUEST_TIME; + $changed = \Drupal::time()->getRequestTime(); $connection = Database::getConnection(); foreach (['dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB'] as $prefix) { $changed += 1000; @@ -125,7 +125,7 @@ public function testContentAdminPages() { // admin listing. We want these to appear in the table in the same order as // they appear in the following code, and the 'content' View has a table // style configuration with a default sort on the 'changed' field DESC. - $time = time(); + $time = \Drupal::time()->getCurrentTime(); $nodes['published_page'] = $this->drupalCreateNode(['type' => 'page', 'changed' => $time--]); $nodes['published_article'] = $this->drupalCreateNode(['type' => 'article', 'changed' => $time--]); $nodes['unpublished_page_1'] = $this->drupalCreateNode(['type' => 'page', 'changed' => $time--, 'uid' => $this->baseUser1->id(), 'status' => 0]); diff --git a/core/modules/node/tests/src/Functional/NodeRevisionsAllTest.php b/core/modules/node/tests/src/Functional/NodeRevisionsAllTest.php index 85440bbfcd..109cd07e03 100644 --- a/core/modules/node/tests/src/Functional/NodeRevisionsAllTest.php +++ b/core/modules/node/tests/src/Functional/NodeRevisionsAllTest.php @@ -190,7 +190,7 @@ public function testRevisions() { // Set the revision timestamp to an older date to make sure that the // confirmation message correctly displays the stored revision date. - $old_revision_date = REQUEST_TIME - 86400; + $old_revision_date = \Drupal::time()->getRequestTime() - 86400; $connection->update('node_revision') ->condition('vid', $nodes[2]->getRevisionId()) ->fields([ diff --git a/core/modules/node/tests/src/Functional/NodeRevisionsTest.php b/core/modules/node/tests/src/Functional/NodeRevisionsTest.php index 55d6f86721..dac4523dd9 100644 --- a/core/modules/node/tests/src/Functional/NodeRevisionsTest.php +++ b/core/modules/node/tests/src/Functional/NodeRevisionsTest.php @@ -196,7 +196,7 @@ public function testRevisions() { // Set the revision timestamp to an older date to make sure that the // confirmation message correctly displays the stored revision date. - $old_revision_date = REQUEST_TIME - 86400; + $old_revision_date = \Drupal::time()->getRequestTime() - 86400; $connection->update('node_revision') ->condition('vid', $nodes[2]->getRevisionId()) ->fields([ diff --git a/core/modules/node/tests/src/Functional/NodeSaveTest.php b/core/modules/node/tests/src/Functional/NodeSaveTest.php index c4b5243f72..395a401c56 100644 --- a/core/modules/node/tests/src/Functional/NodeSaveTest.php +++ b/core/modules/node/tests/src/Functional/NodeSaveTest.php @@ -91,8 +91,8 @@ public function testTimestamps() { Node::create($edit)->save(); $node = $this->drupalGetNodeByTitle($edit['title']); - $this->assertEqual($node->getCreatedTime(), REQUEST_TIME, 'Creating a node sets default "created" timestamp.'); - $this->assertEqual($node->getChangedTime(), REQUEST_TIME, 'Creating a node sets default "changed" timestamp.'); + $this->assertEqual($node->getCreatedTime(), \Drupal::time()->getRequestTime(), 'Creating a node sets default "created" timestamp.'); + $this->assertEqual($node->getChangedTime(), \Drupal::time()->getRequestTime(), 'Creating a node sets default "changed" timestamp.'); // Store the timestamps. $created = $node->getCreatedTime(); diff --git a/core/modules/node/tests/src/Functional/NodeTranslationUITest.php b/core/modules/node/tests/src/Functional/NodeTranslationUITest.php index 2201d727d8..b1e0e56cf7 100644 --- a/core/modules/node/tests/src/Functional/NodeTranslationUITest.php +++ b/core/modules/node/tests/src/Functional/NodeTranslationUITest.php @@ -200,7 +200,7 @@ protected function doTestAuthoringInfo() { $user = $this->drupalCreateUser(); $values[$langcode] = [ 'uid' => $user->id(), - 'created' => REQUEST_TIME - mt_rand(0, 1000), + 'created' => \Drupal::time()->getRequestTime() - mt_rand(0, 1000), 'sticky' => (bool) mt_rand(0, 1), 'promote' => (bool) mt_rand(0, 1), ]; diff --git a/core/modules/node/tests/src/Functional/Views/FrontPageTest.php b/core/modules/node/tests/src/Functional/Views/FrontPageTest.php index 5671d1ead8..35bf560cca 100644 --- a/core/modules/node/tests/src/Functional/Views/FrontPageTest.php +++ b/core/modules/node/tests/src/Functional/Views/FrontPageTest.php @@ -96,7 +96,7 @@ public function testFrontPage() { $values['promote'] = TRUE; $values['status'] = TRUE; // Test descending sort order. - $values['created'] = REQUEST_TIME - $i; + $values['created'] = \Drupal::time()->getRequestTime() - $i; // Test the sticky order. if ($i == 5) { $values['sticky'] = TRUE; diff --git a/core/modules/node/tests/src/Functional/Views/NodeIntegrationTest.php b/core/modules/node/tests/src/Functional/Views/NodeIntegrationTest.php index 965e2b3b92..112d3d35d8 100644 --- a/core/modules/node/tests/src/Functional/Views/NodeIntegrationTest.php +++ b/core/modules/node/tests/src/Functional/Views/NodeIntegrationTest.php @@ -34,7 +34,7 @@ public function testNodeViewTypeArgument() { for ($j = 0; $j < 5; $j++) { // Ensure the right order of the nodes. - $node = $this->drupalCreateNode(['type' => $type->id(), 'created' => REQUEST_TIME - ($i * 5 + $j)]); + $node = $this->drupalCreateNode(['type' => $type->id(), 'created' => \Drupal::time()->getRequestTime() - ($i * 5 + $j)]); $nodes[$type->id()][$node->id()] = $node; $all_nids[] = $node->id(); } diff --git a/core/modules/node/tests/src/Functional/Views/NodeRevisionWizardTest.php b/core/modules/node/tests/src/Functional/Views/NodeRevisionWizardTest.php index b7af626a06..f96ab81268 100644 --- a/core/modules/node/tests/src/Functional/Views/NodeRevisionWizardTest.php +++ b/core/modules/node/tests/src/Functional/Views/NodeRevisionWizardTest.php @@ -26,24 +26,24 @@ public function testViewAdd() { // Create two nodes with two revision. $node_storage = \Drupal::entityTypeManager()->getStorage('node'); /** @var \Drupal\node\NodeInterface $node */ - $node = $node_storage->create(['title' => $this->randomString(), 'type' => 'article', 'changed' => REQUEST_TIME + 40]); + $node = $node_storage->create(['title' => $this->randomString(), 'type' => 'article', 'changed' => \Drupal::time()->getRequestTime() + 40]); $node->save(); $node = $node->createDuplicate(); $node->setNewRevision(); - $node->changed->value = REQUEST_TIME + 20; + $node->changed->value = \Drupal::time()->getRequestTime() + 20; $node->save(); - $node = $node_storage->create(['title' => $this->randomString(), 'type' => 'article', 'changed' => REQUEST_TIME + 30]); + $node = $node_storage->create(['title' => $this->randomString(), 'type' => 'article', 'changed' => \Drupal::time()->getRequestTime() + 30]); $node->save(); $node = $node->createDuplicate(); $node->setNewRevision(); - $node->changed->value = REQUEST_TIME + 10; + $node->changed->value = \Drupal::time()->getRequestTime() + 10; $node->save(); $this->drupalCreateContentType(['type' => 'not-article']); - $node = $node_storage->create(['title' => $this->randomString(), 'type' => 'not-article', 'changed' => REQUEST_TIME + 80]); + $node = $node_storage->create(['title' => $this->randomString(), 'type' => 'not-article', 'changed' => \Drupal::time()->getRequestTime() + 80]); $node->save(); $type = [ diff --git a/core/modules/node/tests/src/Kernel/Views/NodeViewsFieldAccessTest.php b/core/modules/node/tests/src/Kernel/Views/NodeViewsFieldAccessTest.php index 9240cf7596..8dd6a856ae 100644 --- a/core/modules/node/tests/src/Kernel/Views/NodeViewsFieldAccessTest.php +++ b/core/modules/node/tests/src/Kernel/Views/NodeViewsFieldAccessTest.php @@ -68,7 +68,7 @@ public function testNodeFields() { $this->assertFieldAccess('node', 'sticky', 'Off'); // $this->assertFieldAccess('node', 'created', \Drupal::service('date.formatter')->format(123456)); - // $this->assertFieldAccess('node', 'changed', \Drupal::service('date.formatter')->format(REQUEST_TIME)); + // $this->assertFieldAccess('node', 'changed', \Drupal::service('date.formatter')->format(\Drupal::time()->getRequestTime())); } } diff --git a/core/modules/search/search.services.yml b/core/modules/search/search.services.yml index 49ec2acb7b..4ba5ba929b 100644 --- a/core/modules/search/search.services.yml +++ b/core/modules/search/search.services.yml @@ -9,4 +9,4 @@ services: search.index: class: Drupal\search\SearchIndex - arguments: ['@config.factory', '@database','@database.replica', '@cache_tags.invalidator'] + arguments: ['@config.factory', '@database','@database.replica', '@cache_tags.invalidator', '@datetime.time'] diff --git a/core/modules/search/src/SearchIndex.php b/core/modules/search/src/SearchIndex.php index e5655d4974..f0d56a9c69 100644 --- a/core/modules/search/src/SearchIndex.php +++ b/core/modules/search/src/SearchIndex.php @@ -2,6 +2,7 @@ namespace Drupal\search; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\CacheTagsInvalidatorInterface; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Database\Connection; @@ -41,6 +42,13 @@ class SearchIndex implements SearchIndexInterface { */ protected $cacheTagsInvalidator; + /** + * The time service. + * + * @var \Drupal\Component\Datetime\TimeInterface + */ + protected $time; + /** * SearchIndex constructor. * @@ -52,12 +60,15 @@ class SearchIndex implements SearchIndexInterface { * The database replica connection. * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_tags_invalidator * The cache tags invalidator. + * @param \Drupal\Component\Datetime\TimeInterface $time + * The time service. */ - public function __construct(ConfigFactoryInterface $config_factory, Connection $connection, Connection $replica, CacheTagsInvalidatorInterface $cache_tags_invalidator) { + public function __construct(ConfigFactoryInterface $config_factory, Connection $connection, Connection $replica, CacheTagsInvalidatorInterface $cache_tags_invalidator, TimeInterface $time) { $this->configFactory = $config_factory; $this->connection = $connection; $this->replica = $replica; $this->cacheTagsInvalidator = $cache_tags_invalidator; + $this->time = $time; } /** @@ -256,7 +267,7 @@ public function markForReindex($type = NULL, $sid = NULL, $langcode = NULL) { try { $query = $this->connection->update('search_dataset') - ->fields(['reindex' => REQUEST_TIME]) + ->fields(['reindex' => $this->time->getRequestTime()]) // Only mark items that were not previously marked for reindex, so that // marked items maintain their priority by request time. ->condition('reindex', 0); diff --git a/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php b/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php index 4377ef0b75..18464a97e8 100644 --- a/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php +++ b/core/modules/search/tests/src/Functional/SearchMultilingualEntityTest.php @@ -210,7 +210,7 @@ public function testMultilingualSearch() { // The request time is always the same throughout test runs. Update the // request time to a previous time, to simulate it having been marked // previously. - $current = REQUEST_TIME; + $current = \Drupal::time()->getRequestTime(); $old = $current - 10; $connection = Database::getConnection(); $connection->update('search_dataset') diff --git a/core/modules/search/tests/src/Functional/SearchRankingTest.php b/core/modules/search/tests/src/Functional/SearchRankingTest.php index 884359b3d0..95baa6117f 100644 --- a/core/modules/search/tests/src/Functional/SearchRankingTest.php +++ b/core/modules/search/tests/src/Functional/SearchRankingTest.php @@ -70,7 +70,7 @@ public function testRankings() { 'title' => 'Drupal rocks', 'body' => [['value' => "Drupal's search rocks"]], // Node is one day old. - 'created' => REQUEST_TIME - 24 * 3600, + 'created' => \Drupal::time()->getRequestTime() - 24 * 3600, 'sticky' => 0, 'promote' => 0, ]; @@ -86,7 +86,7 @@ public function testRankings() { break; case 'recent': // Node is 1 hour hold. - $settings['created'] = REQUEST_TIME - 3600; + $settings['created'] = \Drupal::time()->getRequestTime() - 3600; break; case 'comments': $settings['comment'][0]['status'] = CommentItemInterface::OPEN; @@ -113,7 +113,7 @@ public function testRankings() { // counter for this node. $nid = $nodes['views'][1]->id(); Database::getConnection()->insert('node_counter') - ->fields(['totalcount' => 5, 'daycount' => 5, 'timestamp' => REQUEST_TIME, 'nid' => $nid]) + ->fields(['totalcount' => 5, 'daycount' => 5, 'timestamp' => \Drupal::time()->getRequestTime(), 'nid' => $nid]) ->execute(); // Run cron to update the search index and comment/statistics totals. diff --git a/core/modules/simpletest/src/TestBase.php b/core/modules/simpletest/src/TestBase.php index 969e227041..2fe02117c0 100644 --- a/core/modules/simpletest/src/TestBase.php +++ b/core/modules/simpletest/src/TestBase.php @@ -1211,7 +1211,7 @@ private function restoreEnvironment() { if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) { session_destroy(); $params = session_get_cookie_params(); - setcookie(session_name(), '', REQUEST_TIME - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']); + setcookie(session_name(), '', \Drupal::time()->getRequestTime() - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']); } session_name($this->originalSessionName); diff --git a/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php b/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php index b0f6334425..7a58e1ae70 100644 --- a/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php +++ b/core/modules/statistics/tests/src/Functional/StatisticsAdminTest.php @@ -160,8 +160,9 @@ public function testExpiredLogs() { $this->assertText('1 view', 'Node is viewed once.'); // statistics_cron() will subtract - // statistics.settings:accesslog.max_lifetime config from REQUEST_TIME in - // the delete query, so wait two secs here to make sure the access log will + // statistics.settings:accesslog.max_lifetime config + // from \Drupal::time()->getRequestTime() in the delete query, + // so wait two secs here to make sure the access log will // be flushed for the node just hit. sleep(2); $this->cronRun(); diff --git a/core/modules/system/src/DateFormatListBuilder.php b/core/modules/system/src/DateFormatListBuilder.php index 0c94a64197..cf65b21c13 100644 --- a/core/modules/system/src/DateFormatListBuilder.php +++ b/core/modules/system/src/DateFormatListBuilder.php @@ -64,7 +64,7 @@ public function buildHeader() { */ public function buildRow(EntityInterface $entity) { $row['label'] = $entity->label(); - $row['pattern'] = $this->dateFormatter->format(REQUEST_TIME, $entity->id()); + $row['pattern'] = $this->dateFormatter->format(\Drupal::time()->getRequestTime(), $entity->id()); return $row + parent::buildRow($entity); } diff --git a/core/modules/system/src/Form/DateFormatDeleteForm.php b/core/modules/system/src/Form/DateFormatDeleteForm.php index 1558032825..39fd6dbb86 100644 --- a/core/modules/system/src/Form/DateFormatDeleteForm.php +++ b/core/modules/system/src/Form/DateFormatDeleteForm.php @@ -45,7 +45,7 @@ public static function create(ContainerInterface $container) { public function getQuestion() { return t('Are you sure you want to delete the format %name : %format?', [ '%name' => $this->entity->label(), - '%format' => $this->dateFormatter->format(REQUEST_TIME, $this->entity->id()), + '%format' => $this->dateFormatter->format(\Drupal::time()->getRequestTime(), $this->entity->id()), ]); } diff --git a/core/modules/system/src/Form/DateFormatEditForm.php b/core/modules/system/src/Form/DateFormatEditForm.php index d6ad88e8ea..083b117492 100644 --- a/core/modules/system/src/Form/DateFormatEditForm.php +++ b/core/modules/system/src/Form/DateFormatEditForm.php @@ -17,7 +17,7 @@ class DateFormatEditForm extends DateFormatFormBase { public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); - $now = t('Displayed as %date', ['%date' => $this->dateFormatter->format(REQUEST_TIME, $this->entity->id())]); + $now = t('Displayed as %date', ['%date' => $this->dateFormatter->format(\Drupal::time()->getRequestTime(), $this->entity->id())]); $form['date_format_pattern']['#field_suffix'] = ' ' . $now . ''; $form['date_format_pattern']['#default_value'] = $this->entity->getPattern(); diff --git a/core/modules/system/src/Tests/Cache/GenericCacheBackendUnitTestBase.php b/core/modules/system/src/Tests/Cache/GenericCacheBackendUnitTestBase.php index 4abca9e576..b623833101 100644 --- a/core/modules/system/src/Tests/Cache/GenericCacheBackendUnitTestBase.php +++ b/core/modules/system/src/Tests/Cache/GenericCacheBackendUnitTestBase.php @@ -143,25 +143,25 @@ public function testSetGet() { $this->assertIdentical($with_backslash, $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); // We need to round because microtime may be rounded up in the backend. - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.'); $this->assertIdentical(FALSE, $backend->get('test2'), "Backend does not contain data for cache id test2."); - $backend->set('test2', ['value' => 3], REQUEST_TIME + 3); + $backend->set('test2', ['value' => 3], \Drupal::time()->getRequestTime() + 3); $cached = $backend->get('test2'); $this->assert(is_object($cached), "Backend returned an object for cache id test2."); $this->assertIdentical(['value' => 3], $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); - $this->assertEqual($cached->expire, REQUEST_TIME + 3, 'Expire time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertEqual($cached->expire, \Drupal::time()->getRequestTime() + 3, 'Expire time is correct.'); - $backend->set('test3', 'foobar', REQUEST_TIME - 3); + $backend->set('test3', 'foobar', \Drupal::time()->getRequestTime() - 3); $this->assertFalse($backend->get('test3'), 'Invalid item not returned.'); $cached = $backend->get('test3', TRUE); $this->assert(is_object($cached), 'Backend returned an object for cache id test3.'); $this->assertFalse($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); - $this->assertEqual($cached->expire, REQUEST_TIME - 3, 'Expire time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertEqual($cached->expire, \Drupal::time()->getRequestTime() - 3, 'Expire time is correct.'); $this->assertIdentical(FALSE, $backend->get('test4'), "Backend does not contain data for cache id test4."); $with_eof = ['foo' => "\nEOF\ndata"]; @@ -170,7 +170,7 @@ public function testSetGet() { $this->assert(is_object($cached), "Backend returned an object for cache id test4."); $this->assertIdentical($with_eof, $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.'); $this->assertIdentical(FALSE, $backend->get('test5'), "Backend does not contain data for cache id test5."); @@ -180,7 +180,7 @@ public function testSetGet() { $this->assert(is_object($cached), "Backend returned an object for cache id test5."); $this->assertIdentical($with_eof_and_semicolon, $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.'); $with_variable = ['foo' => '$bar']; @@ -322,7 +322,7 @@ public function testGetMultiple() { $this->assert(isset($ret['test7']), "Existing cache id test7 is set."); // Test return - ensure that objects has expected properties. $this->assertTrue($ret['test2']->valid, 'Item is marked as valid.'); - $this->assertTrue($ret['test2']->created >= REQUEST_TIME && $ret['test2']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($ret['test2']->created >= \Drupal::time()->getRequestTime() && $ret['test2']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($ret['test2']->expire, Cache::PERMANENT, 'Expire time is correct.'); // Test return - ensure it does not contain nonexistent cache ids. $this->assertFalse(isset($ret['test19']), "Nonexistent cache id test19 is not set."); @@ -383,7 +383,7 @@ public function testGetMultiple() { public function testSetMultiple() { $backend = $this->getCacheBackend(); - $future_expiration = REQUEST_TIME + 100; + $future_expiration = \Drupal::time()->getRequestTime() + 100; // Set multiple testing keys. $backend->set('cid_1', 'Some other value'); @@ -400,7 +400,7 @@ public function testSetMultiple() { $this->assertEqual($cached['cid_1']->data, $items['cid_1']['data'], 'Over-written cache item set correctly.'); $this->assertTrue($cached['cid_1']->valid, 'Item is marked as valid.'); - $this->assertTrue($cached['cid_1']->created >= REQUEST_TIME && $cached['cid_1']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached['cid_1']->created >= \Drupal::time()->getRequestTime() && $cached['cid_1']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached['cid_1']->expire, CacheBackendInterface::CACHE_PERMANENT, 'Cache expiration defaults to permanent.'); $this->assertEqual($cached['cid_2']->data, $items['cid_2']['data'], 'New cache item set correctly.'); @@ -487,7 +487,7 @@ public function testDeleteAll() { // Set both expiring and permanent keys. $backend_a->set('test1', 1, Cache::PERMANENT); - $backend_a->set('test2', 3, time() + 1000); + $backend_a->set('test2', 3, \Drupal::time()->getCurrentTime() + 1000); $backend_b->set('test3', 4, Cache::PERMANENT); $backend_a->deleteAll(); @@ -596,7 +596,7 @@ public function testInvalidateAll() { // Set both expiring and permanent keys. $backend_a->set('test1', 1, Cache::PERMANENT); - $backend_a->set('test2', 3, time() + 1000); + $backend_a->set('test2', 3, \Drupal::time()->getCurrentTime() + 1000); $backend_b->set('test3', 4, Cache::PERMANENT); $backend_a->invalidateAll(); @@ -617,7 +617,7 @@ public function testRemoveBin() { // Set both expiring and permanent keys. $backend_a->set('test1', 1, Cache::PERMANENT); - $backend_a->set('test2', 3, time() + 1000); + $backend_a->set('test2', 3, \Drupal::time()->getCurrentTime() + 1000); $backend_b->set('test3', 4, Cache::PERMANENT); $backend_a->removeBin(); diff --git a/core/modules/system/system.install b/core/modules/system/system.install index daf78612ee..1d64617d0d 100644 --- a/core/modules/system/system.install +++ b/core/modules/system/system.install @@ -582,10 +582,10 @@ function system_requirements($phase) { // Determine severity based on time since cron last ran. $severity = REQUIREMENT_INFO; - if (REQUEST_TIME - $cron_last > $threshold_error) { + if (\Drupal::time()->getRequestTime() - $cron_last > $threshold_error) { $severity = REQUIREMENT_ERROR; } - elseif (REQUEST_TIME - $cron_last > $threshold_warning) { + elseif (\Drupal::time()->getRequestTime() - $cron_last > $threshold_warning) { $severity = REQUIREMENT_WARNING; } diff --git a/core/modules/system/system.tokens.inc b/core/modules/system/system.tokens.inc index c55e106b76..66a0b43bf1 100644 --- a/core/modules/system/system.tokens.inc +++ b/core/modules/system/system.tokens.inc @@ -56,15 +56,15 @@ function system_token_info() { // Date related tokens. $date['short'] = [ 'name' => t("Short format"), - 'description' => t("A date in 'short' format. (%date)", ['%date' => $date_formatter->format(REQUEST_TIME, 'short')]), + 'description' => t("A date in 'short' format. (%date)", ['%date' => $date_formatter->format(\Drupal::time()->getRequestTime(), 'short')]), ]; $date['medium'] = [ 'name' => t("Medium format"), - 'description' => t("A date in 'medium' format. (%date)", ['%date' => $date_formatter->format(REQUEST_TIME, 'medium')]), + 'description' => t("A date in 'medium' format. (%date)", ['%date' => $date_formatter->format(\Drupal::time()->getRequestTime(), 'medium')]), ]; $date['long'] = [ 'name' => t("Long format"), - 'description' => t("A date in 'long' format. (%date)", ['%date' => $date_formatter->format(REQUEST_TIME, 'long')]), + 'description' => t("A date in 'long' format. (%date)", ['%date' => $date_formatter->format(\Drupal::time()->getRequestTime(), 'long')]), ]; $date['custom'] = [ 'name' => t("Custom format"), @@ -72,11 +72,11 @@ function system_token_info() { ]; $date['since'] = [ 'name' => t("Time-since"), - 'description' => t("A date in 'time-since' format. (%date)", ['%date' => $date_formatter->formatTimeDiffSince(REQUEST_TIME - 360)]), + 'description' => t("A date in 'time-since' format. (%date)", ['%date' => $date_formatter->formatTimeDiffSince(\Drupal::time()->getRequestTime() - 360)]), ]; $date['raw'] = [ 'name' => t("Raw timestamp"), - 'description' => t("A date in UNIX timestamp format (%date)", ['%date' => REQUEST_TIME]), + 'description' => t("A date in UNIX timestamp format (%date)", ['%date' => \Drupal::time()->getRequestTime()]), ]; return [ @@ -157,7 +157,7 @@ function system_tokens($type, $tokens, array $data, array $options, BubbleableMe elseif ($type == 'date') { if (empty($data['date'])) { - $date = REQUEST_TIME; + $date = \Drupal::time()->getRequestTime(); // We depend on the current request time, so the tokens are not cacheable // at all. $bubbleable_metadata->setCacheMaxAge(0); diff --git a/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php b/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php index 0e0a46c16b..c20db391cc 100644 --- a/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php +++ b/core/modules/system/tests/modules/entity_test/src/Plugin/Field/FieldType/ChangedTestItem.php @@ -27,7 +27,7 @@ class ChangedTestItem extends ChangedItem { public function preSave() { parent::preSave(); - if ($this->value == REQUEST_TIME) { + if ($this->value == \Drupal::time()->getRequestTime()) { // During a test the request time is immutable. To allow tests of the // algorithm of // Drupal\Core\Field\Plugin\Field\FieldType\ChangedItem::preSave() we need @@ -37,9 +37,9 @@ public function preSave() { // @todo mock the time service in https://www.drupal.org/node/2908210. if ($this->getEntity()->language()->isDefault()) { // Wait 1.1 seconds because time_sleep_until() is not reliable. - time_sleep_until(time() + 1.1); + time_sleep_until(\Drupal::time()->getCurrentTime() + 1.1); } - $this->value = time(); + $this->value = \Drupal::time()->getCurrentTime(); } } diff --git a/core/modules/system/tests/src/Functional/Entity/EntityRevisionsTest.php b/core/modules/system/tests/src/Functional/Entity/EntityRevisionsTest.php index 18bfc18249..90905ab497 100644 --- a/core/modules/system/tests/src/Functional/Entity/EntityRevisionsTest.php +++ b/core/modules/system/tests/src/Functional/Entity/EntityRevisionsTest.php @@ -121,7 +121,7 @@ protected function runRevisionsTests($entity_type) { $this->randomMachineName(32), $this->randomMachineName(32), ], - 'created' => time() + $i + 1, + 'created' => \Drupal::time()->getCurrentTime() + $i + 1, ]; $entity->set('name', $values['en'][$i]['name']); $entity->set('translatable_test_field', $values['en'][$i]['translatable_test_field']); diff --git a/core/modules/system/tests/src/Functional/System/CronRunTest.php b/core/modules/system/tests/src/Functional/System/CronRunTest.php index eecd9db7f7..2af8dc7cc7 100644 --- a/core/modules/system/tests/src/Functional/System/CronRunTest.php +++ b/core/modules/system/tests/src/Functional/System/CronRunTest.php @@ -48,8 +48,8 @@ public function testCronRun() { /** * Ensure that the automated cron run module is working. * - * In these tests we do not use REQUEST_TIME to track start time, because we - * need the exact time when cron is triggered. + * In these tests we do not use \Drupal::time()->getRequestTime() + * to track start time, because we need the exact time when cron is triggered. */ public function testAutomatedCron() { // Test with a logged in user; anonymous users likely don't cause Drupal to @@ -60,7 +60,7 @@ public function testAutomatedCron() { // Ensure cron does not run when a non-zero cron interval is specified and // was not passed. - $cron_last = time(); + $cron_last = \Drupal::time()->getCurrentTime(); $cron_safe_interval = 100; \Drupal::state()->set('system.cron_last', $cron_last); $this->config('automated_cron.settings') @@ -70,7 +70,7 @@ public function testAutomatedCron() { $this->assertTrue($cron_last == \Drupal::state()->get('system.cron_last'), 'Cron does not run when the cron interval is not passed.'); // Test if cron runs when the cron interval was passed. - $cron_last = time() - 200; + $cron_last = \Drupal::time()->getCurrentTime() - 200; \Drupal::state()->set('system.cron_last', $cron_last); $this->drupalGet(''); sleep(1); @@ -82,7 +82,7 @@ public function testAutomatedCron() { $this->drupalLogout(); // Test if cron does not run when the cron interval is set to zero. - $cron_last = time() - 200; + $cron_last = \Drupal::time()->getCurrentTime() - 200; \Drupal::state()->set('system.cron_last', $cron_last); $this->drupalGet(''); $this->assertTrue($cron_last == \Drupal::state()->get('system.cron_last'), 'Cron does not run when the cron threshold is disabled.'); @@ -113,7 +113,7 @@ public function testCronUI() { // the time will start at 1 January 1970. $this->assertNoText('years'); - $cron_last = time() - 200; + $cron_last = \Drupal::time()->getCurrentTime() - 200; \Drupal::state()->set('system.cron_last', $cron_last); $this->drupalPostForm(NULL, [], 'Save configuration'); diff --git a/core/modules/system/tests/src/Kernel/System/CronQueueTest.php b/core/modules/system/tests/src/Kernel/System/CronQueueTest.php index 81f0375898..a200b28d3d 100644 --- a/core/modules/system/tests/src/Kernel/System/CronQueueTest.php +++ b/core/modules/system/tests/src/Kernel/System/CronQueueTest.php @@ -65,14 +65,16 @@ public function testExceptions() { // The item should be left in the queue. $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.'); - // Expire the queue item manually. system_cron() relies in REQUEST_TIME to - // find queue items whose expire field needs to be reset to 0. This is a - // Kernel test, so REQUEST_TIME won't change when cron runs. + // Expire the queue item manually. system_cron() relies in + // \Drupal::time()->getRequestTime() to find queue items + // whose expire field needs to be reset to 0. This is a + // Kernel test, so \Drupal::time()->getRequestTime() won't change + // when cron runs. // @see system_cron() // @see \Drupal\Core\Cron::processQueues() $this->connection->update('queue') ->condition('name', 'cron_queue_test_exception') - ->fields(['expire' => REQUEST_TIME - 1]) + ->fields(['expire' => \Drupal::time()->getRequestTime() - 1]) ->execute(); $this->cron->run(); $this->assertEqual(\Drupal::state()->get('cron_queue_test_exception'), 2); diff --git a/core/modules/system/tests/src/Kernel/Token/TokenReplaceKernelTest.php b/core/modules/system/tests/src/Kernel/Token/TokenReplaceKernelTest.php index 1f86dd386a..962103610b 100644 --- a/core/modules/system/tests/src/Kernel/Token/TokenReplaceKernelTest.php +++ b/core/modules/system/tests/src/Kernel/Token/TokenReplaceKernelTest.php @@ -133,7 +133,7 @@ public function testSystemSiteTokenReplacement() { */ public function testSystemDateTokenReplacement() { // Set time to one hour before request. - $date = REQUEST_TIME - 3600; + $date = \Drupal::time()->getRequestTime() - 3600; // Generate and test tokens. $tests = []; diff --git a/core/modules/toolbar/src/Controller/ToolbarController.php b/core/modules/toolbar/src/Controller/ToolbarController.php index c94e35b307..494d0f34bf 100644 --- a/core/modules/toolbar/src/Controller/ToolbarController.php +++ b/core/modules/toolbar/src/Controller/ToolbarController.php @@ -34,7 +34,7 @@ public function subtreesAjax() { $response->setMaxAge($max_age); $expires = new \DateTime(); - $expires->setTimestamp(REQUEST_TIME + $max_age); + $expires->setTimestamp(\Drupal::time()->getRequestTime() + $max_age); $response->setExpires($expires); return $response; diff --git a/core/modules/update/src/UpdateProcessor.php b/core/modules/update/src/UpdateProcessor.php index 25dfc7a004..862dbb823c 100644 --- a/core/modules/update/src/UpdateProcessor.php +++ b/core/modules/update/src/UpdateProcessor.php @@ -118,7 +118,7 @@ public function createFetchTask($project) { if (empty($this->fetchTasks[$project['name']])) { $this->fetchQueue->createItem($project); $this->fetchTaskStore->set($project['name'], $project); - $this->fetchTasks[$project['name']] = REQUEST_TIME; + $this->fetchTasks[$project['name']] = \Drupal::time()->getRequestTime(); } } @@ -126,8 +126,8 @@ public function createFetchTask($project) { * {@inheritdoc} */ public function fetchData() { - $end = time() + $this->updateSettings->get('fetch.timeout'); - while (time() < $end && ($item = $this->fetchQueue->claimItem())) { + $end = \Drupal::time()->getCurrentTime() + $this->updateSettings->get('fetch.timeout'); + while (\Drupal::time()->getCurrentTime() < $end && ($item = $this->fetchQueue->claimItem())) { $this->processFetchTask($item->data); $this->fetchQueue->deleteItem($item); } @@ -139,9 +139,9 @@ public function fetchData() { public function processFetchTask($project) { global $base_url; - // This can be in the middle of a long-running batch, so REQUEST_TIME won't - // necessarily be valid. - $request_time_difference = time() - REQUEST_TIME; + // This can be in the middle of a long-running batch, + // so \Drupal::time()->getRequestTime() won't necessarily be valid. + $request_time_difference = \Drupal::time()->getCurrentTime() - \Drupal::time()->getRequestTime(); if (empty($this->failed)) { // If we have valid data about release history XML servers that we have // failed to fetch from on previous attempts, load that. @@ -179,14 +179,14 @@ public function processFetchTask($project) { } $frequency = $this->updateSettings->get('check.interval_days'); - $available['last_fetch'] = REQUEST_TIME + $request_time_difference; + $available['last_fetch'] = \Drupal::time()->getRequestTime() + $request_time_difference; $this->availableReleasesTempStore->setWithExpire($project_name, $available, $request_time_difference + (60 * 60 * 24 * $frequency)); // Stash the $this->failed data back in the DB for the next 5 minutes. $this->tempStore->setWithExpire('fetch_failures', $this->failed, $request_time_difference + (60 * 5)); // Whether this worked or not, we did just (try to) check for updates. - $this->stateStore->set('update.last_check', REQUEST_TIME + $request_time_difference); + $this->stateStore->set('update.last_check', \Drupal::time()->getRequestTime() + $request_time_difference); // Now that we processed the fetch task for this project, clear out the // record for this task so we're willing to fetch again. diff --git a/core/modules/update/tests/src/Functional/UpdateCoreTest.php b/core/modules/update/tests/src/Functional/UpdateCoreTest.php index 8322cf8840..e08e459c98 100644 --- a/core/modules/update/tests/src/Functional/UpdateCoreTest.php +++ b/core/modules/update/tests/src/Functional/UpdateCoreTest.php @@ -365,7 +365,7 @@ public function testDatestampMismatch() { '#all' => [ // We need to think we're running a -dev snapshot to see dates. 'version' => '8.1.0-dev', - 'datestamp' => time(), + 'datestamp' => \Drupal::time()->getCurrentTime(), ], 'block' => [ // This is 2001-09-09 01:46:40 GMT, so test for "2001-Sep-". diff --git a/core/modules/update/tests/src/Kernel/UpdateDeleteFileIfStaleTest.php b/core/modules/update/tests/src/Kernel/UpdateDeleteFileIfStaleTest.php index ac9352a01a..56a9754f74 100644 --- a/core/modules/update/tests/src/Kernel/UpdateDeleteFileIfStaleTest.php +++ b/core/modules/update/tests/src/Kernel/UpdateDeleteFileIfStaleTest.php @@ -30,8 +30,8 @@ public function testUpdateDeleteFileIfStale() { // During testing the file change and the stale checking occurs in the same // request, so the beginning of request will be before the file changes and - // REQUEST_TIME - $filectime is negative or zero. Set the maximum age to a - // number even smaller than that. + // \Drupal::time()->getRequestTime() - $filectime is negative or zero. + // Set the maximum age to a number even smaller than that. $this->config('system.file') ->set('temporary_maximum_age', -100000) ->save(); diff --git a/core/modules/update/update.fetch.inc b/core/modules/update/update.fetch.inc index b418d9c3ec..5107eb83e0 100644 --- a/core/modules/update/update.fetch.inc +++ b/core/modules/update/update.fetch.inc @@ -44,7 +44,7 @@ function _update_cron_notify() { // Track when the last mail was successfully sent to avoid sending // too many emails. if ($message['result']) { - \Drupal::state()->set('update.last_email_notification', REQUEST_TIME); + \Drupal::state()->set('update.last_email_notification', \Drupal::time()->getRequestTime()); } } } diff --git a/core/modules/update/update.module b/core/modules/update/update.module index df1f7ef1d7..fcf99455dd 100644 --- a/core/modules/update/update.module +++ b/core/modules/update/update.module @@ -264,7 +264,7 @@ function update_cron() { $frequency = $update_config->get('check.interval_days'); $interval = 60 * 60 * 24 * $frequency; $last_check = \Drupal::state()->get('update.last_check') ?: 0; - if ((REQUEST_TIME - $last_check) > $interval) { + if ((\Drupal::time()->getRequestTime() - $last_check) > $interval) { // If the configured update interval has elapsed, we want to invalidate // the data for all projects, attempt to re-fetch, and trigger any // configured notifications about the new status. @@ -277,7 +277,7 @@ function update_cron() { update_get_available(TRUE); } $last_email_notice = \Drupal::state()->get('update.last_email_notification') ?: 0; - if ((REQUEST_TIME - $last_email_notice) > $interval) { + if ((\Drupal::time()->getRequestTime() - $last_email_notice) > $interval) { // If configured time between notifications elapsed, send email about // updates possibly available. module_load_include('inc', 'update', 'update.fetch'); @@ -838,7 +838,7 @@ function update_delete_file_if_stale($path) { $filectime = filectime($path); $max_age = \Drupal::config('system.file')->get('temporary_maximum_age'); - if (REQUEST_TIME - $filectime > $max_age || (preg_match('/.*-dev\.(tar\.gz|zip)/i', $path) && REQUEST_TIME - $filectime > 300)) { + if (\Drupal::time()->getRequestTime() - $filectime > $max_age || (preg_match('/.*-dev\.(tar\.gz|zip)/i', $path) && \Drupal::time()->getRequestTime() - $filectime > 300)) { try { \Drupal::service('file_system')->deleteRecursive($path); } diff --git a/core/modules/user/src/Controller/UserController.php b/core/modules/user/src/Controller/UserController.php index 7516da93c6..da7cc672c5 100644 --- a/core/modules/user/src/Controller/UserController.php +++ b/core/modules/user/src/Controller/UserController.php @@ -225,7 +225,7 @@ public function getResetPassForm(Request $request, $uid) { */ public function resetPassLogin($uid, $timestamp, $hash) { // The current user is not logged in, so check the parameters. - $current = REQUEST_TIME; + $current = \Drupal::time()->getRequestTime(); /** @var \Drupal\user\UserInterface $user */ $user = $this->userStorage->load($uid); @@ -337,7 +337,7 @@ public function logout() { public function confirmCancel(UserInterface $user, $timestamp = 0, $hashed_pass = '') { // Time out in seconds until cancel URL expires; 24 hours = 86400 seconds. $timeout = 86400; - $current = REQUEST_TIME; + $current = \Drupal::time()->getRequestTime(); // Basic validation of arguments. $account_data = $this->userData->get('user', $user->id()); diff --git a/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php b/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php index bf0e621ac1..bf5cc57640 100644 --- a/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php +++ b/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php @@ -55,11 +55,11 @@ public function __construct(AccountInterface $account, EntityTypeManagerInterfac * The event to process. */ public function onKernelTerminate(PostResponseEvent $event) { - if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) { + if ($this->account->isAuthenticated() && \Drupal::time()->getRequestTime() - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) { // Do that no more than once per 180 seconds. /** @var \Drupal\user\UserStorageInterface $storage */ $storage = $this->entityTypeManager->getStorage('user'); - $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME); + $storage->updateLastAccessTimestamp($this->account, \Drupal::time()->getRequestTime()); } } diff --git a/core/modules/user/tests/src/Functional/UserBlocksTest.php b/core/modules/user/tests/src/Functional/UserBlocksTest.php index 0f9b82b8fb..f20e23834e 100644 --- a/core/modules/user/tests/src/Functional/UserBlocksTest.php +++ b/core/modules/user/tests/src/Functional/UserBlocksTest.php @@ -131,7 +131,8 @@ public function testUserLoginBlock() { /** * Updates the access column for a user. */ - private function updateAccess($uid, $access = REQUEST_TIME) { + private function updateAccess($uid, $access = NULL) { + $access = !empty($access) ? $access : \Drupal::time()->getRequestTime(); Database::getConnection()->update('users_field_data') ->condition('uid', $uid) ->fields(['access' => $access]) diff --git a/core/modules/user/tests/src/Functional/UserCancelTest.php b/core/modules/user/tests/src/Functional/UserCancelTest.php index 1d8e40c752..7e383a52e3 100644 --- a/core/modules/user/tests/src/Functional/UserCancelTest.php +++ b/core/modules/user/tests/src/Functional/UserCancelTest.php @@ -143,7 +143,7 @@ public function testUserCancelInvalid() { $this->drupalPostForm('user/' . $account->id() . '/edit', NULL, t('Cancel account')); // Confirm account cancellation. - $timestamp = time(); + $timestamp = \Drupal::time()->getCurrentTime(); $this->drupalPostForm(NULL, NULL, t('Cancel account')); $this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.'); @@ -192,7 +192,7 @@ public function testUserBlock() { $this->assertNoText(t('Select the method to cancel the account above.'), 'Does not allow user to select account cancellation method.'); // Confirm account cancellation. - $timestamp = time(); + $timestamp = \Drupal::time()->getCurrentTime(); $this->drupalPostForm(NULL, NULL, t('Cancel account')); $this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.'); @@ -251,7 +251,7 @@ public function testUserBlockUnpublish() { $this->assertText(t('Your account will be blocked and you will no longer be able to log in. All of your content will be hidden from everyone but administrators.'), 'Informs that all content will be unpublished.'); // Confirm account cancellation. - $timestamp = time(); + $timestamp = \Drupal::time()->getCurrentTime(); $this->drupalPostForm(NULL, NULL, t('Cancel account')); $this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.'); @@ -331,7 +331,7 @@ public function testUserAnonymize() { $this->assertRaw(t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $this->config('user.settings')->get('anonymous')]), 'Informs that all content will be attributed to anonymous account.'); // Confirm account cancellation. - $timestamp = time(); + $timestamp = \Drupal::time()->getCurrentTime(); $this->drupalPostForm(NULL, NULL, t('Cancel account')); $this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.'); @@ -391,7 +391,7 @@ public function testUserAnonymizeBatch() { $this->assertRaw(t('Your account will be removed and all account information deleted. All of your content will be assigned to the %anonymous-name user.', ['%anonymous-name' => $this->config('user.settings')->get('anonymous')]), 'Informs that all content will be attributed to anonymous account.'); // Confirm account cancellation. - $timestamp = time(); + $timestamp = \Drupal::time()->getCurrentTime(); $this->drupalPostForm(NULL, NULL, t('Cancel account')); $this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.'); @@ -458,7 +458,7 @@ public function testUserDelete() { $this->assertText(t('Your account will be removed and all account information deleted. All of your content will also be deleted.'), 'Informs that all content will be deleted.'); // Confirm account cancellation. - $timestamp = time(); + $timestamp = \Drupal::time()->getCurrentTime(); $this->drupalPostForm(NULL, NULL, t('Cancel account')); $this->assertText(t('A confirmation request to cancel your account has been sent to your email address.'), 'Account cancellation request mailed message displayed.'); diff --git a/core/modules/user/tests/src/Functional/UserCreateTest.php b/core/modules/user/tests/src/Functional/UserCreateTest.php index fceb1af1d6..875e688798 100644 --- a/core/modules/user/tests/src/Functional/UserCreateTest.php +++ b/core/modules/user/tests/src/Functional/UserCreateTest.php @@ -38,8 +38,8 @@ public function testUserAdd() { $user = $this->drupalCreateUser(['administer users']); $this->drupalLogin($user); - $this->assertEqual($user->getCreatedTime(), REQUEST_TIME, 'Creating a user sets default "created" timestamp.'); - $this->assertEqual($user->getChangedTime(), REQUEST_TIME, 'Creating a user sets default "changed" timestamp.'); + $this->assertEqual($user->getCreatedTime(), \Drupal::time()->getRequestTime(), 'Creating a user sets default "created" timestamp.'); + $this->assertEqual($user->getChangedTime(), \Drupal::time()->getRequestTime(), 'Creating a user sets default "changed" timestamp.'); // Create a field. $field_name = 'test_field'; diff --git a/core/modules/user/tests/src/Functional/UserEditTest.php b/core/modules/user/tests/src/Functional/UserEditTest.php index 6a71927a96..88b67ef324 100644 --- a/core/modules/user/tests/src/Functional/UserEditTest.php +++ b/core/modules/user/tests/src/Functional/UserEditTest.php @@ -80,7 +80,7 @@ public function testUserEdit() { $this->assertRaw(t("The changes have been saved.")); // Make sure the changed timestamp is updated. - $this->assertEqual($user1->getChangedTime(), REQUEST_TIME, 'Changing a user sets "changed" timestamp.'); + $this->assertEqual($user1->getChangedTime(), \Drupal::time()->getRequestTime(), 'Changing a user sets "changed" timestamp.'); // Make sure the user can log in with their new password. $this->drupalLogout(); diff --git a/core/modules/user/tests/src/Functional/UserPasswordResetTest.php b/core/modules/user/tests/src/Functional/UserPasswordResetTest.php index f6033a8e1e..43b029afb6 100644 --- a/core/modules/user/tests/src/Functional/UserPasswordResetTest.php +++ b/core/modules/user/tests/src/Functional/UserPasswordResetTest.php @@ -59,7 +59,7 @@ protected function setUp() { // Set the last login time that is used to generate the one-time link so // that it is definitely over a second ago. - $account->login = REQUEST_TIME - mt_rand(10, 100000); + $account->login = \Drupal::time()->getRequestTime() - mt_rand(10, 100000); Database::getConnection()->update('users_field_data') ->fields(['login' => $account->getLastLoginTime()]) ->condition('uid', $account->id()) @@ -144,14 +144,14 @@ public function testUserPasswordReset() { // Create a password reset link as if the request time was 60 seconds older than the allowed limit. $timeout = $this->config('user.settings')->get('password_reset_timeout'); - $bogus_timestamp = REQUEST_TIME - $timeout - 60; + $bogus_timestamp = \Drupal::time()->getRequestTime() - $timeout - 60; $_uid = $this->account->id(); $this->drupalGet("user/reset/$_uid/$bogus_timestamp/" . user_pass_rehash($this->account, $bogus_timestamp)); $this->drupalPostForm(NULL, NULL, t('Log in')); $this->assertText(t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'Expired password reset request rejected.'); // Create a user, block the account, and verify that a login link is denied. - $timestamp = REQUEST_TIME - 1; + $timestamp = \Drupal::time()->getRequestTime() - 1; $blocked_account = $this->drupalCreateUser()->block(); $blocked_account->save(); $this->drupalGet("user/reset/" . $blocked_account->id() . "/$timestamp/" . user_pass_rehash($blocked_account, $timestamp)); @@ -190,7 +190,7 @@ public function testUserPasswordReset() { // Ensure blocked and deleted accounts can't access the user.reset.login // route. $this->drupalLogout(); - $timestamp = REQUEST_TIME - 1; + $timestamp = \Drupal::time()->getRequestTime() - 1; $blocked_account = $this->drupalCreateUser()->block(); $blocked_account->save(); $this->drupalGet("user/reset/" . $blocked_account->id() . "/$timestamp/" . user_pass_rehash($blocked_account, $timestamp) . '/login'); @@ -257,7 +257,7 @@ public function testUserPasswordResetLoggedIn() { // Logged in users should not be able to access the user.reset.login or the // user.reset.form routes. - $timestamp = REQUEST_TIME - 1; + $timestamp = \Drupal::time()->getRequestTime() - 1; $this->drupalGet("user/reset/" . $this->account->id() . "/$timestamp/" . user_pass_rehash($this->account, $timestamp) . '/login'); $this->assertResponse(403); $this->drupalGet("user/reset/" . $this->account->id()); diff --git a/core/modules/user/tests/src/Functional/UserPictureTest.php b/core/modules/user/tests/src/Functional/UserPictureTest.php index 9aa5e45ae4..c0ac594979 100644 --- a/core/modules/user/tests/src/Functional/UserPictureTest.php +++ b/core/modules/user/tests/src/Functional/UserPictureTest.php @@ -84,7 +84,7 @@ public function testCreateDeletePicture() { // would set the timestamp. Database::getConnection()->update('file_managed') ->fields([ - 'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1), + 'changed' => \Drupal::time()->getRequestTime() - ($this->config('system.file')->get('temporary_maximum_age') + 1), ]) ->condition('fid', $file->id()) ->execute(); diff --git a/core/modules/user/tests/src/Functional/UserRegistrationTest.php b/core/modules/user/tests/src/Functional/UserRegistrationTest.php index 760836b307..acb88cb5c1 100644 --- a/core/modules/user/tests/src/Functional/UserRegistrationTest.php +++ b/core/modules/user/tests/src/Functional/UserRegistrationTest.php @@ -260,7 +260,7 @@ public function testRegistrationDefaultValues() { $new_user = reset($accounts); $this->assertEqual($new_user->getAccountName(), $name, 'Username matches.'); $this->assertEqual($new_user->getEmail(), $mail, 'Email address matches.'); - $this->assertTrue(($new_user->getCreatedTime() > REQUEST_TIME - 20), 'Correct creation time.'); + $this->assertTrue(($new_user->getCreatedTime() > \Drupal::time()->getRequestTime() - 20), 'Correct creation time.'); $this->assertEqual($new_user->isActive(), $config_user_settings->get('register') == UserInterface::REGISTER_VISITORS ? 1 : 0, 'Correct status field.'); $this->assertEqual($new_user->getTimezone(), $config_system_date->get('timezone.default'), 'Correct time zone field.'); $this->assertEqual($new_user->langcode->value, \Drupal::languageManager()->getDefaultLanguage()->getId(), 'Correct language field.'); diff --git a/core/modules/user/tests/src/Functional/Views/UserChangedTest.php b/core/modules/user/tests/src/Functional/Views/UserChangedTest.php index d22d2b4710..de2c154076 100644 --- a/core/modules/user/tests/src/Functional/Views/UserChangedTest.php +++ b/core/modules/user/tests/src/Functional/Views/UserChangedTest.php @@ -49,7 +49,7 @@ public function testChangedField() { $this->drupalGet($path, $options); - $this->assertText(t('Updated date') . ': ' . date('Y-m-d', REQUEST_TIME)); + $this->assertText(t('Updated date') . ': ' . date('Y-m-d', \Drupal::time()->getRequestTime())); } } diff --git a/core/modules/user/tests/src/FunctionalJavascript/UserPasswordResetTest.php b/core/modules/user/tests/src/FunctionalJavascript/UserPasswordResetTest.php index f9ea85efa9..dac15a1773 100644 --- a/core/modules/user/tests/src/FunctionalJavascript/UserPasswordResetTest.php +++ b/core/modules/user/tests/src/FunctionalJavascript/UserPasswordResetTest.php @@ -65,7 +65,7 @@ protected function setUp() { // Set the last login time that is used to generate the one-time link so // that it is definitely over a second ago. - $account->login = REQUEST_TIME - mt_rand(10, 100000); + $account->login = \Drupal::time()->getRequestTime() - mt_rand(10, 100000); Database::getConnection()->update('users_field_data') ->fields(['login' => $account->getLastLoginTime()]) ->condition('uid', $account->id()) diff --git a/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php b/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php index 5a41180276..ef87d95d78 100644 --- a/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php +++ b/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php @@ -139,7 +139,7 @@ public function testUserTempStore() { // Now manually expire the item (this is not exposed by the API) and then // assert it is no longer accessible. Database::getConnection()->update('key_value_expire') - ->fields(['expire' => REQUEST_TIME - 1]) + ->fields(['expire' => \Drupal::time()->getRequestTime() - 1]) ->condition('collection', "user.shared_tempstore.$collection") ->condition('name', $key) ->execute(); diff --git a/core/modules/user/tests/src/Kernel/Views/UserViewsFieldAccessTest.php b/core/modules/user/tests/src/Kernel/Views/UserViewsFieldAccessTest.php index f14779e26b..69c2e90a2e 100644 --- a/core/modules/user/tests/src/Kernel/Views/UserViewsFieldAccessTest.php +++ b/core/modules/user/tests/src/Kernel/Views/UserViewsFieldAccessTest.php @@ -61,7 +61,7 @@ public function testUserFields() { $this->assertFieldAccess('user', 'timezone', 'ut1'); $this->assertFieldAccess('user', 'status', 'On'); // $this->assertFieldAccess('user', 'created', \Drupal::service('date.formatter')->format(123456)); - // $this->assertFieldAccess('user', 'changed', \Drupal::service('date.formatter')->format(REQUEST_TIME)); + // $this->assertFieldAccess('user', 'changed', \Drupal::service('date.formatter')->format(\Drupal::time()->getRequestTime())); } } diff --git a/core/modules/user/user.api.php b/core/modules/user/user.api.php index 88812ea4fa..f80099f647 100644 --- a/core/modules/user/user.api.php +++ b/core/modules/user/user.api.php @@ -169,7 +169,7 @@ function hook_user_logout(AccountInterface $account) { \Drupal::database()->insert('logouts') ->fields([ 'uid' => $account->id(), - 'time' => time(), + 'time' => \Drupal::time()->getCurrentTime(), ]) ->execute(); } diff --git a/core/modules/user/user.module b/core/modules/user/user.module index 950b3d25ca..81c4930a07 100644 --- a/core/modules/user/user.module +++ b/core/modules/user/user.module @@ -553,7 +553,7 @@ function user_login_finalize(UserInterface $account) { \Drupal::logger('user')->notice('Session opened for %name.', ['%name' => $account->getAccountName()]); // Update the user table timestamp noting user has logged in. // This is also used to invalidate one-time login links. - $account->setLastLoginTime(REQUEST_TIME); + $account->setLastLoginTime(\Drupal::time()->getRequestTime()); \Drupal::entityTypeManager() ->getStorage('user') ->updateLastLoginTimestamp($account); @@ -600,7 +600,7 @@ function user_user_logout(AccountInterface $account) { * they can change their password. */ function user_pass_reset_url($account, $options = []) { - $timestamp = REQUEST_TIME; + $timestamp = \Drupal::time()->getRequestTime(); $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode(); return Url::fromRoute('user.reset', [ @@ -633,7 +633,7 @@ function user_pass_reset_url($account, $options = []) { * @see \Drupal\user\Controller\UserController::confirmCancel() */ function user_cancel_url(UserInterface $account, $options = []) { - $timestamp = REQUEST_TIME; + $timestamp = \Drupal::time()->getRequestTime(); $langcode = isset($options['langcode']) ? $options['langcode'] : $account->getPreferredLangcode(); $url_options = ['absolute' => TRUE, 'language' => \Drupal::languageManager()->getLanguage($langcode)]; return Url::fromRoute('user.cancel_confirm', [ @@ -658,7 +658,7 @@ function user_cancel_url(UserInterface $account, $options = []) { * @param \Drupal\user\UserInterface $account * An object containing the user account. * @param int $timestamp - * A UNIX timestamp, typically REQUEST_TIME. + * A UNIX timestamp, typically \Drupal::time()->getRequestTime(). * * @return string * A string that is safe for use in URLs and SQL statements. @@ -1341,7 +1341,7 @@ function user_modules_uninstalled($modules) { function user_cookie_save(array $values) { foreach ($values as $field => $value) { // Set cookie for 365 days. - setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), REQUEST_TIME + 31536000, '/'); + setrawcookie('Drupal.visitor.' . $field, rawurlencode($value), \Drupal::time()->getRequestTime() + 31536000, '/'); } } @@ -1352,7 +1352,7 @@ function user_cookie_save(array $values) { * A cookie name such as 'homepage'. */ function user_cookie_delete($cookie_name) { - setrawcookie('Drupal.visitor.' . $cookie_name, '', REQUEST_TIME - 3600, '/'); + setrawcookie('Drupal.visitor.' . $cookie_name, '', \Drupal::time()->getRequestTime() - 3600, '/'); } /** diff --git a/core/modules/views/src/Plugin/views/argument/Date.php b/core/modules/views/src/Plugin/views/argument/Date.php index 852e21f04b..8d994e26a7 100644 --- a/core/modules/views/src/Plugin/views/argument/Date.php +++ b/core/modules/views/src/Plugin/views/argument/Date.php @@ -107,7 +107,7 @@ public function defaultArgumentForm(&$form, FormStateInterface $form_state) { */ public function getDefaultArgument($raw = FALSE) { if (!$raw && $this->options['default_argument_type'] == 'date') { - return date($this->argFormat, REQUEST_TIME); + return date($this->argFormat, \Drupal::time()->getRequestTime()); } elseif (!$raw && in_array($this->options['default_argument_type'], ['node_created', 'node_changed'])) { $node = $this->routeMatch->getParameter('node'); diff --git a/core/modules/views/src/Plugin/views/cache/Time.php b/core/modules/views/src/Plugin/views/cache/Time.php index 962693d921..2f31a59096 100644 --- a/core/modules/views/src/Plugin/views/cache/Time.php +++ b/core/modules/views/src/Plugin/views/cache/Time.php @@ -156,7 +156,7 @@ protected function getLifespan($type) { protected function cacheExpire($type) { $lifespan = $this->getLifespan($type); if ($lifespan) { - $cutoff = REQUEST_TIME - $lifespan; + $cutoff = \Drupal::time()->getRequestTime() - $lifespan; return $cutoff; } else { diff --git a/core/modules/views/src/Plugin/views/field/Date.php b/core/modules/views/src/Plugin/views/field/Date.php index 639bc2329a..0d2b45eae2 100644 --- a/core/modules/views/src/Plugin/views/field/Date.php +++ b/core/modules/views/src/Plugin/views/field/Date.php @@ -85,7 +85,7 @@ public function buildOptionsForm(&$form, FormStateInterface $form_state) { $date_formats = []; foreach ($this->dateFormatStorage->loadMultiple() as $machine_name => $value) { - $date_formats[$machine_name] = $this->t('@name format: @date', ['@name' => $value->label(), '@date' => $this->dateFormatter->format(REQUEST_TIME, $machine_name)]); + $date_formats[$machine_name] = $this->t('@name format: @date', ['@name' => $value->label(), '@date' => $this->dateFormatter->format(\Drupal::time()->getRequestTime(), $machine_name)]); } $form['date_format'] = [ @@ -145,7 +145,7 @@ public function render(ResultRow $values) { $timezone = !empty($this->options['timezone']) ? $this->options['timezone'] : NULL; // Will be positive for a datetime in the past (ago), and negative for a // datetime in the future (hence). - $time_diff = REQUEST_TIME - $value; + $time_diff = \Drupal::time()->getRequestTime() - $value; switch ($format) { case 'raw time ago': return $this->dateFormatter->formatTimeDiffSince($value, ['granularity' => is_numeric($custom_format) ? $custom_format : 2]); diff --git a/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php b/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php index 26c1ffe0b5..5859d78b87 100644 --- a/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php +++ b/core/modules/views/src/Tests/AssertViewsCacheTagsTrait.php @@ -45,7 +45,7 @@ protected function assertViewsCacheTags(ViewExecutable $view, $expected_results_ /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */ $request_stack = \Drupal::service('request_stack'); $request = new Request(); - $request->server->set('REQUEST_TIME', REQUEST_TIME); + $request->server->set('REQUEST_TIME', \Drupal::time()->getRequestTime()); $view->setRequest($request); $request_stack->push($request); $renderer->renderRoot($build); @@ -128,7 +128,7 @@ protected function assertViewsCacheTagsFromStaticRenderArray(ViewExecutable $vie /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */ $request_stack = \Drupal::service('request_stack'); $request = new Request(); - $request->server->set('REQUEST_TIME', REQUEST_TIME); + $request->server->set('REQUEST_TIME', \Drupal::time()->getRequestTime()); $request_stack->push($request); $renderer->renderRoot($build); diff --git a/core/modules/views/src/ViewExecutable.php b/core/modules/views/src/ViewExecutable.php index 9ee37041c0..716067623e 100644 --- a/core/modules/views/src/ViewExecutable.php +++ b/core/modules/views/src/ViewExecutable.php @@ -1686,7 +1686,7 @@ public function preExecute($args = []) { \Drupal::moduleHandler()->invokeAll('views_pre_view', [$this, $display_id, &$this->args]); // Allow hook_views_pre_view() to set the dom_id, then ensure it is set. - $this->dom_id = !empty($this->dom_id) ? $this->dom_id : hash('sha256', $this->storage->id() . REQUEST_TIME . mt_rand()); + $this->dom_id = !empty($this->dom_id) ? $this->dom_id : hash('sha256', $this->storage->id() . \Drupal::time()->getRequestTime() . mt_rand()); // Allow the display handler to set up for execution $this->display_handler->preExecute(); diff --git a/core/modules/views/tests/src/Functional/BulkFormTest.php b/core/modules/views/tests/src/Functional/BulkFormTest.php index 8f49155b88..b7e31930ed 100644 --- a/core/modules/views/tests/src/Functional/BulkFormTest.php +++ b/core/modules/views/tests/src/Functional/BulkFormTest.php @@ -41,7 +41,7 @@ public function testBulkForm() { for ($i = 0; $i < 10; $i++) { // Ensure nodes are sorted in the same order they are inserted in the // array. - $timestamp = REQUEST_TIME - $i; + $timestamp = \Drupal::time()->getRequestTime() - $i; $nodes[] = $this->drupalCreateNode([ 'sticky' => FALSE, 'created' => $timestamp, diff --git a/core/modules/views/tests/src/Functional/DefaultViewsTest.php b/core/modules/views/tests/src/Functional/DefaultViewsTest.php index 071786a470..a800617d7d 100644 --- a/core/modules/views/tests/src/Functional/DefaultViewsTest.php +++ b/core/modules/views/tests/src/Functional/DefaultViewsTest.php @@ -79,7 +79,7 @@ protected function setUp($import_test_views = TRUE) { $this->createEntityReferenceField('node', 'page', $field_name, NULL, 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED); // Create a time in the past for the archive. - $time = REQUEST_TIME - 3600; + $time = \Drupal::time()->getRequestTime() - 3600; $this->addDefaultCommentField('node', 'page'); @@ -202,7 +202,7 @@ public function testArchiveView() { $columns = ['nid', 'created_year_month', 'num_records']; $column_map = array_combine($columns, $columns); // Create time of additional nodes created in the setup method. - $created_year_month = date('Ym', REQUEST_TIME - 3600); + $created_year_month = date('Ym', \Drupal::time()->getRequestTime() - 3600); $expected_result = [ [ 'nid' => 1, diff --git a/core/modules/views/tests/src/Functional/Handler/FilterDateTest.php b/core/modules/views/tests/src/Functional/Handler/FilterDateTest.php index 0ef10459b6..da1f5e9164 100644 --- a/core/modules/views/tests/src/Functional/Handler/FilterDateTest.php +++ b/core/modules/views/tests/src/Functional/Handler/FilterDateTest.php @@ -74,7 +74,7 @@ protected function setUp($import_test_views = TRUE) { $this->nodes[] = $this->drupalCreateNode(['created' => 100000, 'field_date' => 10000]); $this->nodes[] = $this->drupalCreateNode(['created' => 200000, 'field_date' => 20000]); $this->nodes[] = $this->drupalCreateNode(['created' => 300000, 'field_date' => 30000]); - $this->nodes[] = $this->drupalCreateNode(['created' => time() + 86400, 'field_date' => time() + 86400]); + $this->nodes[] = $this->drupalCreateNode(['created' => \Drupal::time()->getCurrentTime() + 86400, 'field_date' => \Drupal::time()->getCurrentTime() + 86400]); $this->map = [ 'nid' => 'nid', diff --git a/core/modules/views/tests/src/Functional/Wizard/ItemsPerPageTest.php b/core/modules/views/tests/src/Functional/Wizard/ItemsPerPageTest.php index 4ab72da1df..165544227d 100644 --- a/core/modules/views/tests/src/Functional/Wizard/ItemsPerPageTest.php +++ b/core/modules/views/tests/src/Functional/Wizard/ItemsPerPageTest.php @@ -29,14 +29,14 @@ public function testItemsPerPage() { // Create articles, each with a different creation time so that we can do a // meaningful sort. - $node1 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME]); - $node2 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 1]); - $node3 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 2]); - $node4 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 3]); - $node5 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 4]); + $node1 = $this->drupalCreateNode(['type' => 'article', 'created' => \Drupal::time()->getRequestTime()]); + $node2 = $this->drupalCreateNode(['type' => 'article', 'created' => \Drupal::time()->getRequestTime() + 1]); + $node3 = $this->drupalCreateNode(['type' => 'article', 'created' => \Drupal::time()->getRequestTime() + 2]); + $node4 = $this->drupalCreateNode(['type' => 'article', 'created' => \Drupal::time()->getRequestTime() + 3]); + $node5 = $this->drupalCreateNode(['type' => 'article', 'created' => \Drupal::time()->getRequestTime() + 4]); // Create a page. This should never appear in the view created below. - $page_node = $this->drupalCreateNode(['type' => 'page', 'created' => REQUEST_TIME + 2]); + $page_node = $this->drupalCreateNode(['type' => 'page', 'created' => \Drupal::time()->getRequestTime() + 2]); // Create a view that sorts newest first, and shows 4 items in the page and // 3 in the block. diff --git a/core/modules/views/tests/src/Functional/Wizard/PagerTest.php b/core/modules/views/tests/src/Functional/Wizard/PagerTest.php index 92bc0035ed..7edee51aba 100644 --- a/core/modules/views/tests/src/Functional/Wizard/PagerTest.php +++ b/core/modules/views/tests/src/Functional/Wizard/PagerTest.php @@ -22,7 +22,7 @@ public function testPager() { // conditions that are meaningful for the use of a pager. $this->drupalCreateContentType(['type' => 'page']); for ($i = 0; $i < 12; $i++) { - $this->drupalCreateNode(['created' => REQUEST_TIME - $i]); + $this->drupalCreateNode(['created' => \Drupal::time()->getRequestTime() - $i]); } // Make a View that uses a pager. diff --git a/core/modules/views/tests/src/Functional/Wizard/SortingTest.php b/core/modules/views/tests/src/Functional/Wizard/SortingTest.php index af8b0a12c9..38ad5f8f9d 100644 --- a/core/modules/views/tests/src/Functional/Wizard/SortingTest.php +++ b/core/modules/views/tests/src/Functional/Wizard/SortingTest.php @@ -27,9 +27,9 @@ public function testSorting() { // Create nodes, each with a different creation time so that we can do a // meaningful sort. $this->drupalCreateContentType(['type' => 'page']); - $node1 = $this->drupalCreateNode(['created' => REQUEST_TIME]); - $node2 = $this->drupalCreateNode(['created' => REQUEST_TIME + 1]); - $node3 = $this->drupalCreateNode(['created' => REQUEST_TIME + 2]); + $node1 = $this->drupalCreateNode(['created' => \Drupal::time()->getRequestTime()]); + $node2 = $this->drupalCreateNode(['created' => \Drupal::time()->getRequestTime() + 1]); + $node3 = $this->drupalCreateNode(['created' => \Drupal::time()->getRequestTime() + 2]); // Create a view that sorts oldest first. $view1 = []; diff --git a/core/modules/views/tests/src/FunctionalJavascript/ClickSortingAJAXTest.php b/core/modules/views/tests/src/FunctionalJavascript/ClickSortingAJAXTest.php index 19c48a7093..93f6613ba3 100644 --- a/core/modules/views/tests/src/FunctionalJavascript/ClickSortingAJAXTest.php +++ b/core/modules/views/tests/src/FunctionalJavascript/ClickSortingAJAXTest.php @@ -39,8 +39,8 @@ protected function setUp() { // Create a Content type and two test nodes. $this->createContentType(['type' => 'page']); - $this->createNode(['title' => 'Page A', 'changed' => REQUEST_TIME]); - $this->createNode(['title' => 'Page B', 'changed' => REQUEST_TIME + 1000]); + $this->createNode(['title' => 'Page A', 'changed' => \Drupal::time()->getRequestTime()]); + $this->createNode(['title' => 'Page B', 'changed' => \Drupal::time()->getRequestTime() + 1000]); // Create a user privileged enough to view content. $user = $this->drupalCreateUser([ diff --git a/core/modules/views/tests/src/Kernel/Handler/FieldDropbuttonTest.php b/core/modules/views/tests/src/Kernel/Handler/FieldDropbuttonTest.php index d764ea511c..b759cfcdad 100644 --- a/core/modules/views/tests/src/Kernel/Handler/FieldDropbuttonTest.php +++ b/core/modules/views/tests/src/Kernel/Handler/FieldDropbuttonTest.php @@ -92,21 +92,21 @@ protected function setUp($import_test_views = TRUE) { 'title' => 'bazs', 'status' => 1, 'uid' => $admin->id(), - 'created' => REQUEST_TIME - 10, + 'created' => \Drupal::time()->getRequestTime() - 10, ]); $this->node2 = $this->createNode([ 'type' => 'foo', 'title' => 'foos', 'status' => 1, 'uid' => $admin->id(), - 'created' => REQUEST_TIME - 5, + 'created' => \Drupal::time()->getRequestTime() - 5, ]); $this->node3 = $this->createNode([ 'type' => 'bar', 'title' => 'bars', 'status' => 1, 'uid' => $admin->id(), - 'created' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), ]); // Now create a user with the ability to edit bar but not foo. diff --git a/core/modules/views/tests/src/Kernel/Handler/FieldFieldTest.php b/core/modules/views/tests/src/Kernel/Handler/FieldFieldTest.php index 03ad765c46..7a2b2aa8a5 100644 --- a/core/modules/views/tests/src/Kernel/Handler/FieldFieldTest.php +++ b/core/modules/views/tests/src/Kernel/Handler/FieldFieldTest.php @@ -82,7 +82,7 @@ protected function setUp($import_test_views = TRUE) { $this->testUsers[$i] = User::create([ 'name' => 'test ' . $i, 'timezone' => User::getAllowedTimezones()[$i], - 'created' => REQUEST_TIME - rand(0, 3600), + 'created' => \Drupal::time()->getRequestTime() - rand(0, 3600), ]); $this->testUsers[$i]->save(); } diff --git a/core/modules/views/tests/src/Kernel/Handler/SortRandomTest.php b/core/modules/views/tests/src/Kernel/Handler/SortRandomTest.php index 941ed8d9ef..e67a4e8944 100644 --- a/core/modules/views/tests/src/Kernel/Handler/SortRandomTest.php +++ b/core/modules/views/tests/src/Kernel/Handler/SortRandomTest.php @@ -38,7 +38,7 @@ protected function dataSet() { 'name' => 'name_' . $i, 'age' => $i, 'job' => 'job_' . $i, - 'created' => rand(0, time()), + 'created' => rand(0, \Drupal::time()->getCurrentTime()), 'status' => 1, ]; } diff --git a/core/modules/views/tests/src/Kernel/Plugin/CacheTest.php b/core/modules/views/tests/src/Kernel/Plugin/CacheTest.php index c8793bc882..2494c3c020 100644 --- a/core/modules/views/tests/src/Kernel/Plugin/CacheTest.php +++ b/core/modules/views/tests/src/Kernel/Plugin/CacheTest.php @@ -42,7 +42,7 @@ protected function setUp($import_test_views = TRUE) { $this->installEntitySchema('user'); // Setup the current time properly. - \Drupal::request()->server->set('REQUEST_TIME', time()); + \Drupal::request()->server->set('REQUEST_TIME', \Drupal::time()->getCurrentTime()); } /** diff --git a/core/modules/views/views.api.php b/core/modules/views/views.api.php index f875cf7a55..05e4e31d9a 100644 --- a/core/modules/views/views.api.php +++ b/core/modules/views/views.api.php @@ -661,7 +661,7 @@ function hook_views_query_substitutions(ViewExecutable $view) { // Example from views_views_query_substitutions(). return [ '***CURRENT_VERSION***' => \Drupal::VERSION, - '***CURRENT_TIME***' => REQUEST_TIME, + '***CURRENT_TIME***' => \Drupal::time()->getRequestTime(), '***LANGUAGE_language_content***' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId(), PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT => \Drupal::languageManager()->getDefaultLanguage()->getId(), ]; diff --git a/core/modules/views/views.theme.inc b/core/modules/views/views.theme.inc index 509a146e03..a4855a2fc0 100644 --- a/core/modules/views/views.theme.inc +++ b/core/modules/views/views.theme.inc @@ -937,7 +937,7 @@ function template_preprocess_views_view_opml(&$variables) { } $variables['title'] = $title; $variables['items'] = $items; - $variables['updated'] = gmdate(DATE_RFC2822, REQUEST_TIME); + $variables['updated'] = gmdate(DATE_RFC2822, \Drupal::time()->getRequestTime()); // During live preview we don't want to output the header since the contents // of the feed are being displayed inside a normal HTML page. diff --git a/core/modules/views/views.views_execution.inc b/core/modules/views/views.views_execution.inc index 60b1adc04c..3647f52abc 100644 --- a/core/modules/views/views.views_execution.inc +++ b/core/modules/views/views.views_execution.inc @@ -20,7 +20,7 @@ function views_views_query_substitutions(ViewExecutable $view) { $substitutions = [ '***CURRENT_VERSION***' => \Drupal::VERSION, - '***CURRENT_TIME***' => REQUEST_TIME, + '***CURRENT_TIME***' => \Drupal::time()->getRequestTime(), ] + PluginBase::queryLanguageSubstitutions(); return $substitutions; diff --git a/core/rebuild.php b/core/rebuild.php index 6c64b241da..b7f6056a98 100644 --- a/core/rebuild.php +++ b/core/rebuild.php @@ -39,8 +39,8 @@ if (Settings::get('rebuild_access', FALSE) || ($request->query->get('token') && $request->query->get('timestamp') && - ((REQUEST_TIME - $request->query->get('timestamp')) < 300) && - hash_equals(Crypt::hmacBase64($request->query->get('timestamp'), Settings::get('hash_salt')), $request->query->get('token')) + ((\Drupal::time()->getRequestTime() - $request->query->get('timestamp')) < 300) && + Crypt::hashEquals(Crypt::hmacBase64($request->query->get('timestamp'), Settings::get('hash_salt')), $request->query->get('token')) )) { // Clear user cache for all major platforms. $user_caches = [ diff --git a/core/scripts/rebuild_token_calculator.sh b/core/scripts/rebuild_token_calculator.sh index 362be3d5fd..b25fffc43a 100755 --- a/core/scripts/rebuild_token_calculator.sh +++ b/core/scripts/rebuild_token_calculator.sh @@ -21,7 +21,7 @@ $request = Request::createFromGlobals(); Settings::initialize(DRUPAL_ROOT, DrupalKernel::findSitePath($request), $autoloader); -$timestamp = time(); +$timestamp = \Drupal::time()->getCurrentTime(); $token = Crypt::hmacBase64($timestamp, Settings::get('hash_salt')); print "timestamp=$timestamp&token=$token\n"; diff --git a/core/tests/Drupal/KernelTests/Core/Cache/GenericCacheBackendUnitTestBase.php b/core/tests/Drupal/KernelTests/Core/Cache/GenericCacheBackendUnitTestBase.php index 1cbc64b607..92a4508009 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/GenericCacheBackendUnitTestBase.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/GenericCacheBackendUnitTestBase.php @@ -138,25 +138,25 @@ public function testSetGet() { $this->assertSame($with_backslash, $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); // We need to round because microtime may be rounded up in the backend. - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.'); $this->assertSame(FALSE, $backend->get('test2'), "Backend does not contain data for cache id test2."); - $backend->set('test2', ['value' => 3], REQUEST_TIME + 3); + $backend->set('test2', ['value' => 3], \Drupal::time()->getRequestTime() + 3); $cached = $backend->get('test2'); $this->assert(is_object($cached), "Backend returned an object for cache id test2."); $this->assertSame(['value' => 3], $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); - $this->assertEqual($cached->expire, REQUEST_TIME + 3, 'Expire time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertEqual($cached->expire, \Drupal::time()->getRequestTime() + 3, 'Expire time is correct.'); - $backend->set('test3', 'foobar', REQUEST_TIME - 3); + $backend->set('test3', 'foobar', \Drupal::time()->getRequestTime() - 3); $this->assertFalse($backend->get('test3'), 'Invalid item not returned.'); $cached = $backend->get('test3', TRUE); $this->assert(is_object($cached), 'Backend returned an object for cache id test3.'); $this->assertFalse($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); - $this->assertEqual($cached->expire, REQUEST_TIME - 3, 'Expire time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertEqual($cached->expire, \Drupal::time()->getRequestTime() - 3, 'Expire time is correct.'); $this->assertSame(FALSE, $backend->get('test4'), "Backend does not contain data for cache id test4."); $with_eof = ['foo' => "\nEOF\ndata"]; @@ -165,7 +165,7 @@ public function testSetGet() { $this->assert(is_object($cached), "Backend returned an object for cache id test4."); $this->assertSame($with_eof, $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.'); $this->assertSame(FALSE, $backend->get('test5'), "Backend does not contain data for cache id test5."); @@ -175,7 +175,7 @@ public function testSetGet() { $this->assert(is_object($cached), "Backend returned an object for cache id test5."); $this->assertSame($with_eof_and_semicolon, $cached->data); $this->assertTrue($cached->valid, 'Item is marked as valid.'); - $this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached->created >= \Drupal::time()->getRequestTime() && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.'); $with_variable = ['foo' => '$bar']; @@ -317,7 +317,7 @@ public function testGetMultiple() { $this->assert(isset($ret['test7']), "Existing cache id test7 is set."); // Test return - ensure that objects has expected properties. $this->assertTrue($ret['test2']->valid, 'Item is marked as valid.'); - $this->assertTrue($ret['test2']->created >= REQUEST_TIME && $ret['test2']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($ret['test2']->created >= \Drupal::time()->getRequestTime() && $ret['test2']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($ret['test2']->expire, Cache::PERMANENT, 'Expire time is correct.'); // Test return - ensure it does not contain nonexistent cache ids. $this->assertFalse(isset($ret['test19']), "Nonexistent cache id test19 is not set."); @@ -378,7 +378,7 @@ public function testGetMultiple() { public function testSetMultiple() { $backend = $this->getCacheBackend(); - $future_expiration = REQUEST_TIME + 100; + $future_expiration = \Drupal::time()->getRequestTime() + 100; // Set multiple testing keys. $backend->set('cid_1', 'Some other value'); @@ -395,7 +395,7 @@ public function testSetMultiple() { $this->assertEqual($cached['cid_1']->data, $items['cid_1']['data'], 'Over-written cache item set correctly.'); $this->assertTrue($cached['cid_1']->valid, 'Item is marked as valid.'); - $this->assertTrue($cached['cid_1']->created >= REQUEST_TIME && $cached['cid_1']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); + $this->assertTrue($cached['cid_1']->created >= \Drupal::time()->getRequestTime() && $cached['cid_1']->created <= round(microtime(TRUE), 3), 'Created time is correct.'); $this->assertEqual($cached['cid_1']->expire, CacheBackendInterface::CACHE_PERMANENT, 'Cache expiration defaults to permanent.'); $this->assertEqual($cached['cid_2']->data, $items['cid_2']['data'], 'New cache item set correctly.'); @@ -482,7 +482,7 @@ public function testDeleteAll() { // Set both expiring and permanent keys. $backend_a->set('test1', 1, Cache::PERMANENT); - $backend_a->set('test2', 3, time() + 1000); + $backend_a->set('test2', 3, \Drupal::time()->getCurrentTime() + 1000); $backend_b->set('test3', 4, Cache::PERMANENT); $backend_a->deleteAll(); @@ -591,7 +591,7 @@ public function testInvalidateAll() { // Set both expiring and permanent keys. $backend_a->set('test1', 1, Cache::PERMANENT); - $backend_a->set('test2', 3, time() + 1000); + $backend_a->set('test2', 3, \Drupal::time()->getCurrentTime() + 1000); $backend_b->set('test3', 4, Cache::PERMANENT); $backend_a->invalidateAll(); @@ -612,7 +612,7 @@ public function testRemoveBin() { // Set both expiring and permanent keys. $backend_a->set('test1', 1, Cache::PERMANENT); - $backend_a->set('test2', 3, time() + 1000); + $backend_a->set('test2', 3, \Drupal::time()->getCurrentTime() + 1000); $backend_b->set('test3', 4, Cache::PERMANENT); $backend_a->removeBin(); diff --git a/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityChangedTest.php b/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityChangedTest.php index 6956af2e81..5b15af7f88 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityChangedTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/ContentEntityChangedTest.php @@ -68,7 +68,7 @@ public function testChanged() { $entity->save(); $this->assertTrue( - $entity->getChangedTime() >= REQUEST_TIME, + $entity->getChangedTime() >= \Drupal::time()->getRequestTime(), 'Changed time of original language is valid.' ); @@ -78,7 +78,7 @@ public function testChanged() { // between the created time and now. $this->assertTrue( ($entity->getChangedTime() >= $entity->get('created')->value) && - (($entity->getChangedTime() - $entity->get('created')->value) <= time() - REQUEST_TIME), + (($entity->getChangedTime() - $entity->get('created')->value) <= \Drupal::time()->getCurrentTime() - \Drupal::time()->getRequestTime()), 'Changed and created time of original language can be assumed to be identical.' ); @@ -297,7 +297,7 @@ public function testRevisionChanged() { $entity->save(); $this->assertTrue( - $entity->getChangedTime() >= REQUEST_TIME, + $entity->getChangedTime() >= \Drupal::time()->getRequestTime(), 'Changed time of original language is valid.' ); @@ -306,7 +306,7 @@ public function testRevisionChanged() { // timestamp every time. $this->assertTrue( ($entity->getChangedTime() >= $entity->get('created')->value) && - (($entity->getChangedTime() - $entity->get('created')->value) <= time() - REQUEST_TIME), + (($entity->getChangedTime() - $entity->get('created')->value) <= \Drupal::time()->getCurrentTime() - \Drupal::time()->getRequestTime()), 'Changed and created time of original language can be assumed to be identical.' ); diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityCrudHookTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityCrudHookTest.php index a3566fdd6c..db89ce3270 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/EntityCrudHookTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityCrudHookTest.php @@ -154,8 +154,8 @@ public function testCommentHooks() { 'promote' => 0, 'sticky' => 0, 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, - 'created' => REQUEST_TIME, - 'changed' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), + 'changed' => \Drupal::time()->getRequestTime(), ]); $node->save(); $nid = $node->id(); @@ -169,8 +169,8 @@ public function testCommentHooks() { 'field_name' => 'comment', 'uid' => $account->id(), 'subject' => 'Test comment', - 'created' => REQUEST_TIME, - 'changed' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), + 'changed' => \Drupal::time()->getRequestTime(), 'status' => 1, 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, ]); @@ -236,8 +236,8 @@ public function testFileHooks() { 'filemime' => 'text/plain', 'filesize' => filesize($url), 'status' => 1, - 'created' => REQUEST_TIME, - 'changed' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), + 'changed' => \Drupal::time()->getRequestTime(), ]); $this->assertHookMessageOrder([ @@ -299,8 +299,8 @@ public function testNodeHooks() { 'promote' => 0, 'sticky' => 0, 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, - 'created' => REQUEST_TIME, - 'changed' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), + 'changed' => \Drupal::time()->getRequestTime(), ]); $this->assertHookMessageOrder([ @@ -484,7 +484,7 @@ public function testUserHooks() { $account = User::create([ 'name' => 'Test user', 'mail' => 'test@example.com', - 'created' => REQUEST_TIME, + 'created' => \Drupal::time()->getRequestTime(), 'status' => 1, 'language' => 'en', ]); diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php index 05b7b87bc4..d6fc985258 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityQueryTest.php @@ -1177,7 +1177,7 @@ public function testConditionOnRevisionMetadataKeys() { /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */ $storage = $entity_type_manager->getStorage('entity_test_revlog'); - $revision_created_timestamp = time(); + $revision_created_timestamp = \Drupal::time()->getCurrentTime(); $revision_created_field_name = $entity_type->getRevisionMetadataKey('revision_created'); $entity = $storage->create([ 'type' => 'entity_test', diff --git a/core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php b/core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php index 7dd98da1fc..b4e3f2374b 100644 --- a/core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php +++ b/core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php @@ -64,7 +64,7 @@ public function testConstraintValidation() { $violations = $entity->validate(); $this->assertEqual($violations->count(), 0, 'Validation passed.'); $entity->save(); - $entity->changed->value = REQUEST_TIME - 86400; + $entity->changed->value = \Drupal::time()->getRequestTime() - 86400; $violations = $entity->validate(); $this->assertEqual($violations->count(), 1, 'Validation failed.'); $this->assertEqual($violations[0]->getMessage(), t('The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.')); diff --git a/core/tests/Drupal/KernelTests/Core/KeyValueStore/GarbageCollectionTest.php b/core/tests/Drupal/KernelTests/Core/KeyValueStore/GarbageCollectionTest.php index 3c8615205e..e4ab7e6745 100644 --- a/core/tests/Drupal/KernelTests/Core/KeyValueStore/GarbageCollectionTest.php +++ b/core/tests/Drupal/KernelTests/Core/KeyValueStore/GarbageCollectionTest.php @@ -50,7 +50,7 @@ public function testGarbageCollection() { 'collection' => $collection, ]) ->fields([ - 'expire' => REQUEST_TIME - 1, + 'expire' => \Drupal::time()->getRequestTime() - 1, ]) ->execute(); } diff --git a/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php b/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php index c9e3cfe647..8817b0e43a 100644 --- a/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php +++ b/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php @@ -130,7 +130,7 @@ public function testSharedTempStore() { // Now manually expire the item (this is not exposed by the API) and then // assert it is no longer accessible. $database->update('key_value_expire') - ->fields(['expire' => REQUEST_TIME - 1]) + ->fields(['expire' => \Drupal::time()->getRequestTime() - 1]) ->condition('collection', "tempstore.shared.$collection") ->condition('name', $key) ->execute(); diff --git a/core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php b/core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php index 760b2d081d..75bdc5cccc 100644 --- a/core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php +++ b/core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php @@ -199,12 +199,12 @@ public function testGetAndSet() { $this->assertNull($typed_data->getDateTime()); // Timestamp type. - $value = REQUEST_TIME; + $value = \Drupal::time()->getRequestTime(); $typed_data = $this->createTypedData(['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; + $new_value = \Drupal::time()->getRequestTime() + 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); @@ -214,10 +214,10 @@ public function testGetAndSet() { $typed_data->setValue('invalid'); $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.'); // Check implementation of DateTimeInterface. - $typed_data = $this->createTypedData(['type' => 'timestamp'], REQUEST_TIME); + $typed_data = $this->createTypedData(['type' => 'timestamp'], \Drupal::time()->getRequestTime()); $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->setDateTime(DrupalDateTime::createFromTimestamp(\Drupal::time()->getRequestTime() + 1)); + $this->assertEqual($typed_data->getValue(), \Drupal::time()->getRequestTime() + 1); $typed_data->setValue(NULL); $this->assertNull($typed_data->getDateTime()); diff --git a/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php b/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php index 0a2a74a6e6..3b37caa59e 100644 --- a/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php +++ b/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php @@ -7,6 +7,7 @@ namespace Drupal\Tests\Core\Render; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\Cache; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Cache\Context\ContextCacheKeys; @@ -111,6 +112,13 @@ abstract class RendererTestBase extends UnitTestCase { ], ]; + /** + * System time service. + * + * @var \Drupal\Component\Datetime\TimeInterface + */ + protected $datetimeTime; + /** * {@inheritdoc} */ @@ -170,11 +178,13 @@ protected function setUp() { $this->placeholderGenerator = new PlaceholderGenerator($this->rendererConfig); $this->renderCache = new PlaceholderingRenderCache($this->requestStack, $this->cacheFactory, $this->cacheContextsManager, $this->placeholderGenerator); $this->renderer = new Renderer($this->controllerResolver, $this->themeManager, $this->elementInfo, $this->placeholderGenerator, $this->renderCache, $this->requestStack, $this->rendererConfig); + $this->datetimeTime = new Time($this->requestStack); $container = new ContainerBuilder(); $container->set('cache_contexts_manager', $this->cacheContextsManager); $container->set('render_cache', $this->renderCache); $container->set('renderer', $this->renderer); + $container->set('datetime.time', $this->datetimeTime); \Drupal::setContainer($container); }