From fd75fa213472e2029fded744e26886a1c045e5ef Mon Sep 17 00:00:00 2001 From: catch <catch@35733.no-reply.drupal.org> Date: Tue, 13 Feb 2024 10:15:33 +0000 Subject: [PATCH] Issue #3113971 by Spokje, mondrake, acbramley, phenaproxima, andypost, murilohp, mpdonadio, ravi.shankar, pavnish, pifagor, vladbo, JeroenT, voleger, Taran2L: Replace REQUEST_TIME in services --- composer.lock | 5 +- core/composer.json | 3 +- core/core.services.yml | 21 +++--- .../Core/Asset/JsCollectionRenderer.php | 15 +++- core/lib/Drupal/Core/Batch/BatchStorage.php | 2 +- core/lib/Drupal/Core/Cache/ApcuBackend.php | 20 ++++-- .../Drupal/Core/Cache/ApcuBackendFactory.php | 11 ++- .../lib/Drupal/Core/Cache/DatabaseBackend.php | 20 ++++-- .../Core/Cache/DatabaseBackendFactory.php | 17 ++++- core/lib/Drupal/Core/Cache/MemoryBackend.php | 31 +++++--- .../Core/Cache/MemoryBackendFactory.php | 17 ++++- .../Core/Cache/MemoryCache/MemoryCache.php | 4 +- .../Cache/MemoryCache/MemoryCacheFactory.php | 16 ++++- .../Cache/MemoryCounterBackendFactory.php | 17 ++++- core/lib/Drupal/Core/Cache/PhpBackend.php | 13 +++- .../Drupal/Core/Cache/PhpBackendFactory.php | 12 +++- .../Drupal/Core/Config/StorageComparer.php | 7 +- core/lib/Drupal/Core/DrupalKernel.php | 8 +++ .../FinishResponseSubscriber.php | 24 ++++++- .../lib/Drupal/Core/Flood/DatabaseBackend.php | 19 +++-- .../NormalInstallerServiceProvider.php | 3 +- .../KeyValueDatabaseExpirableFactory.php | 15 +++- .../Drupal/Core/Session/SessionHandler.php | 13 +++- .../Drupal/Core/Session/SessionManager.php | 25 ++++++- core/modules/comment/comment.services.yml | 3 +- .../modules/comment/src/CommentStatistics.php | 29 ++++++-- .../src/Unit/CommentStatisticsUnitTest.php | 3 +- .../src/Kernel/MigrateSqlSourceTestBase.php | 5 +- .../tests/src/Kernel/mysql/DbDumpTest.php | 4 +- .../path_alias/path_alias.services.yml | 2 +- core/modules/path_alias/src/AliasManager.php | 25 ++++++- .../path_alias/tests/src/Kernel/AliasTest.php | 7 +- .../tests/src/Unit/AliasManagerTest.php | 3 +- core/modules/search/search.services.yml | 2 +- core/modules/search/src/SearchIndex.php | 18 ++++- core/modules/system/system.services.yml | 1 + .../tests/src/Kernel/System/FloodTest.php | 7 +- core/modules/update/src/UpdateProcessor.php | 18 ++++- core/modules/update/update.services.yml | 2 +- .../EventSubscriber/UserRequestSubscriber.php | 13 +++- core/modules/user/user.services.yml | 2 +- core/phpstan-baseline.neon | 70 ------------------- .../Core/Cache/ApcuBackendTest.php | 3 +- .../Core/Cache/BackendChainTest.php | 8 ++- .../Core/Cache/ChainedFastBackendTest.php | 5 +- .../Core/Cache/DatabaseBackendTest.php | 10 ++- .../Cache/EndOfTransactionQueriesTest.php | 4 +- .../Core/Cache/MemoryBackendTest.php | 3 +- .../KernelTests/Core/Cache/PhpBackendTest.php | 4 +- .../DrupalKernel/DrupalKernelSiteTest.php | 5 ++ .../Core/Plugin/PluginTestBase.php | 3 +- .../Core/Routing/RouteProviderTest.php | 3 +- .../Drupal/KernelTests/KernelTestBase.php | 5 +- .../Tests/Core/Asset/AssetResolverTest.php | 3 +- .../BackendChainImplementationUnitTest.php | 8 ++- .../Core/Cache/ChainedFastBackendTest.php | 3 +- .../Core/Cache/DatabaseBackendFactoryTest.php | 4 +- .../Tests/Core/Cache/VariationCacheTest.php | 3 +- .../Config/Entity/ConfigEntityStorageTest.php | 3 +- .../KeyValueEntityStorageTest.php | 3 +- .../Sql/SqlContentEntityStorageTest.php | 11 +-- .../FinishResponseSubscriberTest.php | 11 +++ .../Core/Render/RendererBubblingTest.php | 5 +- .../Tests/Core/Render/RendererTestBase.php | 3 +- .../Tests/Core/Session/UserSessionTest.php | 3 +- 65 files changed, 469 insertions(+), 196 deletions(-) diff --git a/composer.lock b/composer.lock index ccd477eac316..9454b2e82ca6 100644 --- a/composer.lock +++ b/composer.lock @@ -495,7 +495,7 @@ "dist": { "type": "path", "url": "core", - "reference": "cc2af7de02a19bfde449293a84468f5fb1e33cea" + "reference": "52e04d4f59d5d77f898e4a3d2a63c1d809f139f7" }, "require": { "asm89/stack-cors": "^2.1", @@ -630,7 +630,8 @@ "lib/Drupal/Core/DrupalKernel.php", "lib/Drupal/Core/DrupalKernelInterface.php", "lib/Drupal/Core/Installer/InstallerRedirectTrait.php", - "lib/Drupal/Core/Site/Settings.php" + "lib/Drupal/Core/Site/Settings.php", + "lib/Drupal/Component/Datetime/Time.php" ], "files": [ "includes/bootstrap.inc" diff --git a/core/composer.json b/core/composer.json index 9ae3cab9bee5..44fe4bada636 100644 --- a/core/composer.json +++ b/core/composer.json @@ -105,7 +105,8 @@ "lib/Drupal/Core/DrupalKernel.php", "lib/Drupal/Core/DrupalKernelInterface.php", "lib/Drupal/Core/Installer/InstallerRedirectTrait.php", - "lib/Drupal/Core/Site/Settings.php" + "lib/Drupal/Core/Site/Settings.php", + "lib/Drupal/Component/Datetime/Time.php" ], "files": [ "includes/bootstrap.inc" diff --git a/core/core.services.yml b/core/core.services.yml index 8b98f2442884..2eaf74d271f7 100644 --- a/core/core.services.yml +++ b/core/core.services.yml @@ -228,19 +228,21 @@ services: - [setContainer, ['@service_container']] cache.backend.database: class: Drupal\Core\Cache\DatabaseBackendFactory - arguments: ['@database', '@cache_tags.invalidator.checksum', '@settings', '@serialization.phpserialize'] + arguments: ['@database', '@cache_tags.invalidator.checksum', '@settings', '@serialization.phpserialize', '@datetime.time'] tags: - { name: backend_overridable } cache.backend.apcu: class: Drupal\Core\Cache\ApcuBackendFactory - arguments: ['%app.root%', '%site.path%', '@cache_tags.invalidator.checksum'] + arguments: ['%app.root%', '%site.path%', '@cache_tags.invalidator.checksum', '@datetime.time'] cache.backend.php: class: Drupal\Core\Cache\PhpBackendFactory - arguments: ['@cache_tags.invalidator.checksum'] + arguments: ['@cache_tags.invalidator.checksum', '@datetime.time'] cache.backend.memory: class: Drupal\Core\Cache\MemoryBackendFactory + arguments: ['@datetime.time'] cache.backend.memory.memory: class: Drupal\Core\Cache\MemoryCache\MemoryCacheFactory + arguments: ['@datetime.time'] # A special cache bin that does not persist beyond the length of the request. cache.static: class: Drupal\Core\Cache\CacheBackendInterface @@ -490,7 +492,7 @@ services: arguments: ['@service_container', '%factory.keyvalue.expirable%'] keyvalue.expirable.database: class: Drupal\Core\KeyValueStore\KeyValueDatabaseExpirableFactory - arguments: ['@serialization.phpserialize', '@database'] + arguments: ['@serialization.phpserialize', '@database', '@datetime.time'] logger.factory: class: Drupal\Core\Logger\LoggerChannelFactory parent: container.trait @@ -686,6 +688,7 @@ services: Drupal\Core\Extension\ThemeInstallerInterface: '@theme_installer' entity.memory_cache: class: Drupal\Core\Cache\MemoryCache\MemoryCache + arguments: ['@datetime.time'] Drupal\Core\Cache\MemoryCache\MemoryCacheInterface: '@entity.memory_cache' entity_type.manager: class: Drupal\Core\Entity\EntityTypeManager @@ -1377,7 +1380,7 @@ services: arguments: ['@html_response.attachments_processor'] finish_response_subscriber: class: Drupal\Core\EventSubscriber\FinishResponseSubscriber - arguments: ['@language_manager', '@config.factory', '@page_cache_request_policy', '@page_cache_response_policy', '@cache_contexts_manager', '%http.response.debug_cacheability_headers%'] + arguments: ['@language_manager', '@config.factory', '@page_cache_request_policy', '@page_cache_response_policy', '@cache_contexts_manager', '@datetime.time', '%http.response.debug_cacheability_headers%'] response_generator_subscriber: class: Drupal\Core\EventSubscriber\ResponseGeneratorSubscriber redirect_response_subscriber: @@ -1457,7 +1460,7 @@ services: arguments: [null, '@module_handler'] flood: class: Drupal\Core\Flood\DatabaseBackend - arguments: ['@database', '@request_stack'] + arguments: ['@database', '@request_stack', '@datetime.time'] tags: - { name: backend_overridable } Drupal\Core\Flood\FloodInterface: '@flood' @@ -1610,7 +1613,7 @@ services: alias: session_handler.storage session_handler.storage: class: Drupal\Core\Session\SessionHandler - arguments: ['@request_stack', '@database'] + arguments: ['@request_stack', '@database', '@datetime.time'] tags: - { name: backend_overridable } session_handler.write_safe: @@ -1620,7 +1623,7 @@ services: Drupal\Core\Session\WriteSafeSessionHandlerInterface: '@session_handler.write_safe' session_manager: class: Drupal\Core\Session\SessionManager - arguments: ['@request_stack', '@database', '@session_manager.metadata_bag', '@session_configuration', '@session_handler'] + arguments: ['@request_stack', '@database', '@session_manager.metadata_bag', '@session_configuration', '@datetime.time', '@session_handler'] tags: - { name: backend_overridable } calls: @@ -1646,7 +1649,7 @@ services: arguments: ['@file_system'] asset.js.collection_renderer: class: Drupal\Core\Asset\JsCollectionRenderer - arguments: [ '@asset.query_string','@file_url_generator' ] + arguments: [ '@asset.query_string','@file_url_generator', '@datetime.time' ] asset.js.collection_optimizer: class: Drupal\Core\Asset\JsCollectionOptimizerLazy arguments: [ '@asset.js.collection_grouper', '@asset.js.optimizer', '@theme.manager', '@library.dependency_resolver', '@request_stack', '@file_system', '@config.factory', '@file_url_generator', '@datetime.time', '@language_manager'] diff --git a/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php b/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php index 9b866f1b42ff..d5b2191aa8c5 100644 --- a/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php +++ b/core/lib/Drupal/Core/Asset/JsCollectionRenderer.php @@ -2,6 +2,7 @@ namespace Drupal\Core\Asset; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\Serialization\Json; use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait; use Drupal\Core\File\FileUrlGeneratorInterface; @@ -40,14 +41,24 @@ class JsCollectionRenderer implements AssetCollectionRendererInterface { * The asset query string. * @param \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator * The file URL generator. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(AssetQueryStringInterface|StateInterface $asset_query_string, FileUrlGeneratorInterface $file_url_generator) { + public function __construct( + AssetQueryStringInterface|StateInterface $asset_query_string, + FileUrlGeneratorInterface $file_url_generator, + protected ?TimeInterface $time = NULL, + ) { if ($asset_query_string instanceof StateInterface) { @trigger_error('Calling ' . __METHOD__ . '() with the $asset_query_string argument as \Drupal\Core\State\StateInterface instead of \Drupal\Core\Asset\AssetQueryStringInterface is deprecated in drupal:10.2.0 and will be required in drupal:11.0.0. See https://www.drupal.org/node/3358337', E_USER_DEPRECATED); $asset_query_string = \Drupal::service('asset.query_string'); } $this->assetQueryString = $asset_query_string; $this->fileUrlGenerator = $file_url_generator; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -99,7 +110,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 : $this->time->getRequestTime()); } break; diff --git a/core/lib/Drupal/Core/Batch/BatchStorage.php b/core/lib/Drupal/Core/Batch/BatchStorage.php index a7733535bad9..48c30a809cb5 100644 --- a/core/lib/Drupal/Core/Batch/BatchStorage.php +++ b/core/lib/Drupal/Core/Batch/BatchStorage.php @@ -58,7 +58,7 @@ public function __construct(Connection $connection, SessionInterface $session, C $this->session = $session; $this->csrfToken = $csrf_token; if (!$time) { - @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. See https://www.drupal.org/node/3220378', E_USER_DEPRECATED); + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. See https://www.drupal.org/node/3220378', E_USER_DEPRECATED); $time = \Drupal::service('datetime.time'); } $this->time = $time; diff --git a/core/lib/Drupal/Core/Cache/ApcuBackend.php b/core/lib/Drupal/Core/Cache/ApcuBackend.php index fc6fab38bfa9..13ba59eec8b0 100644 --- a/core/lib/Drupal/Core/Cache/ApcuBackend.php +++ b/core/lib/Drupal/Core/Cache/ApcuBackend.php @@ -3,6 +3,7 @@ namespace Drupal\Core\Cache; use Drupal\Component\Assertion\Inspector; +use Drupal\Component\Datetime\TimeInterface; /** * Stores cache items in the Alternative PHP Cache User Cache (APCu). @@ -48,12 +49,23 @@ class ApcuBackend implements CacheBackendInterface { * The prefix to use for all keys in the storage that belong to this site. * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider * The cache tags checksum provider. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct($bin, $site_prefix, CacheTagsChecksumInterface $checksum_provider) { + public function __construct( + $bin, + $site_prefix, + CacheTagsChecksumInterface $checksum_provider, + protected ?TimeInterface $time = NULL, + ) { $this->bin = $bin; $this->sitePrefix = $site_prefix; $this->checksumProvider = $checksum_provider; $this->binPrefix = $this->sitePrefix . '::' . $this->bin . '::'; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -145,7 +157,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 >= $this->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 +247,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, $this->time->getRequestTime() - 1); } } @@ -245,7 +257,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'], $this->time->getRequestTime() - 1); } } diff --git a/core/lib/Drupal/Core/Cache/ApcuBackendFactory.php b/core/lib/Drupal/Core/Cache/ApcuBackendFactory.php index 58b29015d7e1..b6a969a4106c 100644 --- a/core/lib/Drupal/Core/Cache/ApcuBackendFactory.php +++ b/core/lib/Drupal/Core/Cache/ApcuBackendFactory.php @@ -2,6 +2,7 @@ namespace Drupal\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Site\Settings; class ApcuBackendFactory implements CacheFactoryInterface { @@ -36,11 +37,17 @@ class ApcuBackendFactory implements CacheFactoryInterface { * The site path. * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider * The cache tags checksum provider. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct($root, $site_path, CacheTagsChecksumInterface $checksum_provider) { + public function __construct($root, $site_path, CacheTagsChecksumInterface $checksum_provider, protected ?TimeInterface $time = NULL) { $this->sitePrefix = Settings::getApcuPrefix('apcu_backend', $root, $site_path); $this->checksumProvider = $checksum_provider; $this->backendClass = 'Drupal\Core\Cache\ApcuBackend'; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -53,7 +60,7 @@ public function __construct($root, $site_path, CacheTagsChecksumInterface $check * The cache backend object for the specified cache bin. */ public function get($bin) { - return new $this->backendClass($bin, $this->sitePrefix, $this->checksumProvider); + return new $this->backendClass($bin, $this->sitePrefix, $this->checksumProvider, $this->time); } } diff --git a/core/lib/Drupal/Core/Cache/DatabaseBackend.php b/core/lib/Drupal/Core/Cache/DatabaseBackend.php index 13103c1664c1..dddb3a61ab35 100644 --- a/core/lib/Drupal/Core/Cache/DatabaseBackend.php +++ b/core/lib/Drupal/Core/Cache/DatabaseBackend.php @@ -4,6 +4,7 @@ use Drupal\Component\Serialization\ObjectAwareSerializationInterface; use Drupal\Component\Assertion\Inspector; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\Utility\Crypt; use Drupal\Core\Database\Connection; use Drupal\Core\Database\DatabaseException; @@ -78,6 +79,8 @@ class DatabaseBackend implements CacheBackendInterface { * The cache bin for which the object is created. * @param \Drupal\Component\Serialization\ObjectAwareSerializationInterface|int|string|null $serializer * (optional) The serializer to use. + * @param \Drupal\Component\Datetime\TimeInterface|int|string|null $time + * The time service. * @param int $max_rows * (optional) The maximum number of rows that are allowed in this cache bin * table. @@ -87,6 +90,7 @@ public function __construct( CacheTagsChecksumInterface $checksum_provider, $bin, protected ObjectAwareSerializationInterface|int|string|null $serializer = NULL, + protected TimeInterface|int|string|null $time = NULL, $max_rows = NULL, ) { // All cache tables should be prefixed with 'cache_'. @@ -104,6 +108,13 @@ public function __construct( @trigger_error('Calling ' . __METHOD__ . ' without the $serializer argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3014684', E_USER_DEPRECATED); $this->serializer = \Drupal::service('serialization.phpserialize'); } + if (!$this->time instanceof TimeInterface) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be the 5th argument in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + if (is_int($time) || is_string($time)) { + $max_rows = $time; + } + $this->time = \Drupal::service(TimeInterface::class); + } $this->maxRows = $max_rows === NULL ? static::DEFAULT_MAX_ROWS : $max_rows; } @@ -174,7 +185,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 >= $this->time->getRequestTime(); // Check if invalidateTags() has been called with any of the item's tags. if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) { @@ -363,9 +374,10 @@ public function invalidateMultiple(array $cids) { $cids = array_values(array_map([$this, 'normalizeCid'], $cids)); try { // Update in chunks when a large array is passed. + $requestTime = $this->time->getRequestTime(); foreach (array_chunk($cids, 1000) as $cids_chunk) { $this->connection->update($this->bin) - ->fields(['expire' => REQUEST_TIME - 1]) + ->fields(['expire' => $requestTime - 1]) ->condition('cid', $cids_chunk, 'IN') ->execute(); } @@ -381,7 +393,7 @@ public function invalidateMultiple(array $cids) { public function invalidateAll() { try { $this->connection->update($this->bin) - ->fields(['expire' => REQUEST_TIME - 1]) + ->fields(['expire' => $this->time->getRequestTime() - 1]) ->execute(); } catch (\Exception $e) { @@ -412,7 +424,7 @@ public function garbageCollection() { $this->connection->delete($this->bin) ->condition('expire', Cache::PERMANENT, '<>') - ->condition('expire', REQUEST_TIME, '<') + ->condition('expire', $this->time->getRequestTime(), '<') ->execute(); } catch (\Exception $e) { diff --git a/core/lib/Drupal/Core/Cache/DatabaseBackendFactory.php b/core/lib/Drupal/Core/Cache/DatabaseBackendFactory.php index fd176e045ebe..5fe87d83ffbb 100644 --- a/core/lib/Drupal/Core/Cache/DatabaseBackendFactory.php +++ b/core/lib/Drupal/Core/Cache/DatabaseBackendFactory.php @@ -2,6 +2,7 @@ namespace Drupal\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\Serialization\ObjectAwareSerializationInterface; use Drupal\Core\Database\Connection; use Drupal\Core\Site\Settings; @@ -33,10 +34,18 @@ class DatabaseBackendFactory implements CacheFactoryInterface { * (optional) The site settings. * @param \Drupal\Component\Serialization\ObjectAwareSerializationInterface|null $serializer * (optional) The serializer to use. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. * * @throws \BadMethodCallException */ - public function __construct(Connection $connection, CacheTagsChecksumInterface $checksum_provider, protected ?Settings $settings = NULL, protected ?ObjectAwareSerializationInterface $serializer = NULL) { + public function __construct( + Connection $connection, + CacheTagsChecksumInterface $checksum_provider, + protected ?Settings $settings = NULL, + protected ?ObjectAwareSerializationInterface $serializer = NULL, + protected ?TimeInterface $time = NULL, + ) { $this->connection = $connection; $this->checksumProvider = $checksum_provider; if ($this->settings === NULL) { @@ -47,6 +56,10 @@ public function __construct(Connection $connection, CacheTagsChecksumInterface $ @trigger_error('Calling ' . __METHOD__ . ' without the $serializer argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3014684', E_USER_DEPRECATED); $this->serializer = \Drupal::service('serialization.phpserialize'); } + if ($this->time === NULL) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -60,7 +73,7 @@ public function __construct(Connection $connection, CacheTagsChecksumInterface $ */ public function get($bin) { $max_rows = $this->getMaxRowsForBin($bin); - return new DatabaseBackend($this->connection, $this->checksumProvider, $bin, $this->serializer, $max_rows); + return new DatabaseBackend($this->connection, $this->checksumProvider, $bin, $this->serializer, $this->time, $max_rows); } /** diff --git a/core/lib/Drupal/Core/Cache/MemoryBackend.php b/core/lib/Drupal/Core/Cache/MemoryBackend.php index 18e3658d3237..267ccd1b6b12 100644 --- a/core/lib/Drupal/Core/Cache/MemoryBackend.php +++ b/core/lib/Drupal/Core/Cache/MemoryBackend.php @@ -3,6 +3,7 @@ namespace Drupal\Core\Cache; use Drupal\Component\Assertion\Inspector; +use Drupal\Component\Datetime\TimeInterface; /** * Defines a memory cache implementation. @@ -26,6 +27,19 @@ class MemoryBackend implements CacheBackendInterface, CacheTagsInvalidatorInterf */ protected $cache = []; + /** + * Constructs a MemoryBackend object. + * + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. + */ + public function __construct(protected ?TimeInterface $time = NULL) { + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } + } + /** * {@inheritdoc} */ @@ -87,7 +101,7 @@ protected function prepareItem($cache, $allow_invalid) { $prepared->data = unserialize($prepared->data); // Check expire time. - $prepared->valid = $prepared->expire == Cache::PERMANENT || $prepared->expire >= $this->getRequestTime(); + $prepared->valid = $prepared->expire == Cache::PERMANENT || $prepared->expire >= $this->time->getRequestTime(); if (!$allow_invalid && !$prepared->valid) { return FALSE; @@ -107,7 +121,7 @@ public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) { $this->cache[$cid] = (object) [ 'cid' => $cid, 'data' => serialize($data), - 'created' => $this->getRequestTime(), + 'created' => $this->time->getRequestTime(), 'expire' => $expire, 'tags' => $tags, ]; @@ -148,7 +162,7 @@ public function deleteAll() { */ public function invalidate($cid) { if (isset($this->cache[$cid])) { - $this->cache[$cid]->expire = $this->getRequestTime() - 1; + $this->cache[$cid]->expire = $this->time->getRequestTime() - 1; } } @@ -158,7 +172,7 @@ public function invalidate($cid) { public function invalidateMultiple(array $cids) { $items = array_intersect_key($this->cache, array_flip($cids)); foreach ($items as $cid => $item) { - $this->cache[$cid]->expire = $this->getRequestTime() - 1; + $this->cache[$cid]->expire = $this->time->getRequestTime() - 1; } } @@ -168,7 +182,7 @@ public function invalidateMultiple(array $cids) { public function invalidateTags(array $tags) { foreach ($this->cache as $cid => $item) { if (array_intersect($tags, $item->tags)) { - $this->cache[$cid]->expire = $this->getRequestTime() - 1; + $this->cache[$cid]->expire = $this->time->getRequestTime() - 1; } } } @@ -178,7 +192,7 @@ public function invalidateTags(array $tags) { */ public function invalidateAll() { foreach ($this->cache as $cid => $item) { - $this->cache[$cid]->expire = $this->getRequestTime() - 1; + $this->cache[$cid]->expire = $this->time->getRequestTime() - 1; } } @@ -201,14 +215,15 @@ public function removeBin() { * @return int */ protected function getRequestTime() { - return defined('REQUEST_TIME') ? REQUEST_TIME : (int) $_SERVER['REQUEST_TIME']; + @trigger_error(__METHOD__ . '() is deprecated in drupal:10.3.0 will be removed in drupal:11.0.0. Use the datetime.time service instead. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + return $this->time->getRequestTime(); } /** * Prevents data stored in memory backends from being serialized. */ public function __sleep() { - return []; + return ['time']; } /** diff --git a/core/lib/Drupal/Core/Cache/MemoryBackendFactory.php b/core/lib/Drupal/Core/Cache/MemoryBackendFactory.php index c5c6a950a4ce..1cac2aa11ada 100644 --- a/core/lib/Drupal/Core/Cache/MemoryBackendFactory.php +++ b/core/lib/Drupal/Core/Cache/MemoryBackendFactory.php @@ -2,6 +2,8 @@ namespace Drupal\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; + class MemoryBackendFactory implements CacheFactoryInterface { /** @@ -11,12 +13,25 @@ class MemoryBackendFactory implements CacheFactoryInterface { */ protected $bins = []; + /** + * Constructs a MemoryBackendFactory object. + * + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. + */ + public function __construct(protected ?TimeInterface $time = NULL) { + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } + } + /** * {@inheritdoc} */ public function get($bin) { if (!isset($this->bins[$bin])) { - $this->bins[$bin] = new MemoryBackend(); + $this->bins[$bin] = new MemoryBackend($this->time); } return $this->bins[$bin]; } diff --git a/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCache.php b/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCache.php index 327110821159..a5772e6d3e01 100644 --- a/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCache.php +++ b/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCache.php @@ -35,7 +35,7 @@ protected function prepareItem($cache, $allow_invalid = FALSE) { return FALSE; } // Check expire time. - $cache->valid = $cache->expire == static::CACHE_PERMANENT || $cache->expire >= $this->getRequestTime(); + $cache->valid = $cache->expire == static::CACHE_PERMANENT || $cache->expire >= $this->time->getRequestTime(); if (!$allow_invalid && !$cache->valid) { return FALSE; @@ -54,7 +54,7 @@ public function set($cid, $data, $expire = MemoryCacheInterface::CACHE_PERMANENT $this->cache[$cid] = (object) [ 'cid' => $cid, 'data' => $data, - 'created' => $this->getRequestTime(), + 'created' => $this->time->getRequestTime(), 'expire' => $expire, 'tags' => $tags, ]; diff --git a/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCacheFactory.php b/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCacheFactory.php index 1f2fcb7beabd..94df99fea588 100644 --- a/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCacheFactory.php +++ b/core/lib/Drupal/Core/Cache/MemoryCache/MemoryCacheFactory.php @@ -2,6 +2,7 @@ namespace Drupal\Core\Cache\MemoryCache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\CacheFactoryInterface; class MemoryCacheFactory implements CacheFactoryInterface { @@ -13,12 +14,25 @@ class MemoryCacheFactory implements CacheFactoryInterface { */ protected $bins = []; + /** + * Constructs a MemoryCounterBackendFactory object. + * + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. + */ + public function __construct(protected ?TimeInterface $time = NULL) { + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } + } + /** * {@inheritdoc} */ public function get($bin) { if (!isset($this->bins[$bin])) { - $this->bins[$bin] = new MemoryCache(); + $this->bins[$bin] = new MemoryCache($this->time); } return $this->bins[$bin]; } diff --git a/core/lib/Drupal/Core/Cache/MemoryCounterBackendFactory.php b/core/lib/Drupal/Core/Cache/MemoryCounterBackendFactory.php index 02d0197ea7c5..04691da0bd24 100644 --- a/core/lib/Drupal/Core/Cache/MemoryCounterBackendFactory.php +++ b/core/lib/Drupal/Core/Cache/MemoryCounterBackendFactory.php @@ -2,6 +2,8 @@ namespace Drupal\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; + class MemoryCounterBackendFactory implements CacheFactoryInterface { /** @@ -11,12 +13,25 @@ class MemoryCounterBackendFactory implements CacheFactoryInterface { */ protected $bins = []; + /** + * Constructs a MemoryCounterBackendFactory object. + * + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. + */ + public function __construct(protected ?TimeInterface $time = NULL) { + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } + } + /** * {@inheritdoc} */ public function get($bin) { if (!isset($this->bins[$bin])) { - $this->bins[$bin] = new MemoryCounterBackend(); + $this->bins[$bin] = new MemoryCounterBackend($this->time); } return $this->bins[$bin]; } diff --git a/core/lib/Drupal/Core/Cache/PhpBackend.php b/core/lib/Drupal/Core/Cache/PhpBackend.php index a6b69acface3..059ca05948a7 100644 --- a/core/lib/Drupal/Core/Cache/PhpBackend.php +++ b/core/lib/Drupal/Core/Cache/PhpBackend.php @@ -3,6 +3,7 @@ namespace Drupal\Core\Cache; use Drupal\Component\Assertion\Inspector; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\PhpStorage\PhpStorageInterface; use Drupal\Component\Utility\Crypt; use Drupal\Core\PhpStorage\PhpStorageFactory; @@ -51,10 +52,16 @@ class PhpBackend implements CacheBackendInterface { * The cache bin for which the object is created. * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider * The cache tags checksum provider. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct($bin, CacheTagsChecksumInterface $checksum_provider) { + public function __construct($bin, CacheTagsChecksumInterface $checksum_provider, protected ?TimeInterface $time = NULL) { $this->bin = 'cache_' . $bin; $this->checksumProvider = $checksum_provider; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -132,7 +139,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 >= $this->time->getRequestTime(); // Check if invalidateTags() has been called with any of the item's tags. if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) { @@ -201,7 +208,7 @@ public function invalidate($cid) { */ protected function invalidateByHash($cidhash) { if ($item = $this->getByHash($cidhash)) { - $item->expire = REQUEST_TIME - 1; + $item->expire = $this->time->getRequestTime() - 1; $this->writeItem($cidhash, $item); } } diff --git a/core/lib/Drupal/Core/Cache/PhpBackendFactory.php b/core/lib/Drupal/Core/Cache/PhpBackendFactory.php index 0091ed307ded..de4fd56a0669 100644 --- a/core/lib/Drupal/Core/Cache/PhpBackendFactory.php +++ b/core/lib/Drupal/Core/Cache/PhpBackendFactory.php @@ -2,6 +2,8 @@ namespace Drupal\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; + class PhpBackendFactory implements CacheFactoryInterface { /** @@ -16,9 +18,15 @@ class PhpBackendFactory implements CacheFactoryInterface { * * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider * The cache tags checksum provider. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(CacheTagsChecksumInterface $checksum_provider) { + public function __construct(CacheTagsChecksumInterface $checksum_provider, protected ?TimeInterface $time = NULL) { $this->checksumProvider = $checksum_provider; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -31,7 +39,7 @@ public function __construct(CacheTagsChecksumInterface $checksum_provider) { * The cache backend object for the specified cache bin. */ public function get($bin) { - return new PhpBackend($bin, $this->checksumProvider); + return new PhpBackend($bin, $this->checksumProvider, $this->time); } } diff --git a/core/lib/Drupal/Core/Config/StorageComparer.php b/core/lib/Drupal/Core/Config/StorageComparer.php index 702ca22a37a4..ef2d1945b6c0 100644 --- a/core/lib/Drupal/Core/Config/StorageComparer.php +++ b/core/lib/Drupal/Core/Config/StorageComparer.php @@ -2,6 +2,8 @@ namespace Drupal\Core\Config; +use Drupal\Component\Datetime\Time; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\MemoryBackend; use Drupal\Core\Cache\NullBackend; use Drupal\Core\Config\Entity\ConfigDependencyManager; @@ -112,6 +114,7 @@ public function __construct(StorageInterface $source_storage, StorageInterface $ $target_storage = $target_storage->createCollection(StorageInterface::DEFAULT_COLLECTION); } + $time = \Drupal::hasService(TimeInterface::class) ? \Drupal::service(TimeInterface::class) : new Time(); if ($source_storage instanceof FileStorage) { // FileStorage has its own static cache so that multiple reads of the // same raw configuration object are not costly. @@ -121,14 +124,14 @@ public function __construct(StorageInterface $source_storage, StorageInterface $ else { // Wrap the source storage in a static cache so that multiple reads of the // same raw configuration object are not costly. - $this->sourceCacheStorage = new MemoryBackend(); + $this->sourceCacheStorage = new MemoryBackend($time); $this->sourceStorage = new CachedStorage( $source_storage, $this->sourceCacheStorage ); } - $this->targetCacheStorage = new MemoryBackend(); + $this->targetCacheStorage = new MemoryBackend($time); $this->targetStorage = $target_storage; $this->changelist[StorageInterface::DEFAULT_COLLECTION] = $this->getEmptyChangelist(); } diff --git a/core/lib/Drupal/Core/DrupalKernel.php b/core/lib/Drupal/Core/DrupalKernel.php index b79aee7716f7..d0c661cc89f9 100644 --- a/core/lib/Drupal/Core/DrupalKernel.php +++ b/core/lib/Drupal/Core/DrupalKernel.php @@ -75,6 +75,13 @@ class DrupalKernel implements DrupalKernelInterface, TerminableInterface { 'factory' => 'Drupal\Core\Database\Database::getConnection', 'arguments' => ['default'], ], + 'request_stack' => [ + 'class' => 'Symfony\Component\HttpFoundation\RequestStack', + ], + 'datetime.time' => [ + 'class' => 'Drupal\Component\Datetime\Time', + 'arguments' => ['@request_stack'], + ], 'cache.container' => [ 'class' => 'Drupal\Core\Cache\DatabaseBackend', 'arguments' => [ @@ -82,6 +89,7 @@ class DrupalKernel implements DrupalKernelInterface, TerminableInterface { '@cache_tags_provider.container', 'container', '@serialization.phpserialize', + '@datetime.time', DatabaseBackend::MAXIMUM_NONE, ], ], diff --git a/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php b/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php index da96c9dbfc06..ffa7188fca1c 100644 --- a/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php +++ b/core/lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php @@ -3,6 +3,7 @@ namespace Drupal\Core\EventSubscriber; use Drupal\Component\Datetime\DateTimePlus; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\CacheableResponseInterface; use Drupal\Core\Cache\Context\CacheContextsManager; use Drupal\Core\Config\ConfigFactoryInterface; @@ -74,15 +75,32 @@ class FinishResponseSubscriber implements EventSubscriberInterface { * A policy rule determining the cacheability of a response. * @param \Drupal\Core\Cache\Context\CacheContextsManager $cache_contexts_manager * The cache contexts manager service. + * @param \Drupal\Component\Datetime\TimeInterface|null|bool $time + * The time service. * @param bool $http_response_debug_cacheability_headers * (optional) Whether to send cacheability headers for debugging purposes. */ - public function __construct(LanguageManagerInterface $language_manager, ConfigFactoryInterface $config_factory, RequestPolicyInterface $request_policy, ResponsePolicyInterface $response_policy, CacheContextsManager $cache_contexts_manager, $http_response_debug_cacheability_headers = FALSE) { + public function __construct( + LanguageManagerInterface $language_manager, + ConfigFactoryInterface $config_factory, + RequestPolicyInterface $request_policy, + ResponsePolicyInterface $response_policy, + CacheContextsManager $cache_contexts_manager, + protected TimeInterface|bool|null $time = NULL, + $http_response_debug_cacheability_headers = FALSE, + ) { $this->languageManager = $language_manager; $this->config = $config_factory->get('system.performance'); $this->requestPolicy = $request_policy; $this->responsePolicy = $response_policy; $this->cacheContextsManager = $cache_contexts_manager; + if (!$time || is_bool($time)) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be the 5th argument in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + if (is_bool($time)) { + $http_response_debug_cacheability_headers = $time; + } + $this->time = \Drupal::service(TimeInterface::class); + } $this->debugCacheabilityHeaders = $http_response_debug_cacheability_headers; } @@ -257,8 +275,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 = $this->time->getRequestTime(); + $response->setLastModified(new \DateTime(gmdate(DateTimePlus::RFC7231, $this->time->getRequestTime()))); } else { $timestamp = $response->getLastModified()->getTimestamp(); diff --git a/core/lib/Drupal/Core/Flood/DatabaseBackend.php b/core/lib/Drupal/Core/Flood/DatabaseBackend.php index c69e29caa1d5..fd0a078175a4 100644 --- a/core/lib/Drupal/Core/Flood/DatabaseBackend.php +++ b/core/lib/Drupal/Core/Flood/DatabaseBackend.php @@ -2,9 +2,10 @@ namespace Drupal\Core\Flood; +use Drupal\Component\Datetime\TimeInterface; +use Drupal\Core\Database\Connection; use Drupal\Core\Database\DatabaseException; use Symfony\Component\HttpFoundation\RequestStack; -use Drupal\Core\Database\Connection; /** * Defines the database flood backend. This is the default Drupal backend. @@ -38,10 +39,16 @@ class DatabaseBackend implements FloodInterface, PrefixFloodInterface { * information. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack * The request stack used to retrieve the current request. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(Connection $connection, RequestStack $request_stack) { + public function __construct(Connection $connection, RequestStack $request_stack, protected ?TimeInterface $time = NULL) { $this->connection = $connection; $this->requestStack = $request_stack; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -83,8 +90,8 @@ protected function doInsert($name, $window, $identifier) { ->fields([ 'event' => $name, 'identifier' => $identifier, - 'timestamp' => REQUEST_TIME, - 'expiration' => REQUEST_TIME + $window, + 'timestamp' => $this->time->getRequestTime(), + 'expiration' => $this->time->getRequestTime() + $window, ]) ->execute(); } @@ -133,7 +140,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', $this->time->getRequestTime() - $window, '>') ->countQuery() ->execute() ->fetchField(); @@ -153,7 +160,7 @@ public function isAllowed($name, $threshold, $window = 3600, $identifier = NULL) public function garbageCollection() { try { $this->connection->delete(static::TABLE_NAME) - ->condition('expiration', REQUEST_TIME, '<') + ->condition('expiration', $this->time->getRequestTime(), '<') ->execute(); } catch (\Exception $e) { diff --git a/core/lib/Drupal/Core/Installer/NormalInstallerServiceProvider.php b/core/lib/Drupal/Core/Installer/NormalInstallerServiceProvider.php index 507b27c7c4f8..a8c6ec84aa40 100644 --- a/core/lib/Drupal/Core/Installer/NormalInstallerServiceProvider.php +++ b/core/lib/Drupal/Core/Installer/NormalInstallerServiceProvider.php @@ -2,6 +2,7 @@ namespace Drupal\Core\Installer; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\MemoryBackendFactory; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\DependencyInjection\ServiceProviderInterface; @@ -37,7 +38,7 @@ public function register(ContainerBuilder $container) { // install. $definition = $container->getDefinition('cache_factory'); $definition->setClass(MemoryBackendFactory::class); - $definition->setArguments([]); + $definition->setArguments([new Time()]); $definition->setMethodCalls([]); // Replace lock service with no-op implementation as Drupal installation can diff --git a/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php b/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php index 207a339fcb49..40ec3955518b 100644 --- a/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php +++ b/core/lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php @@ -2,6 +2,7 @@ namespace Drupal\Core\KeyValueStore; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\Serialization\SerializationInterface; use Drupal\Core\Database\Connection; @@ -38,10 +39,20 @@ class KeyValueDatabaseExpirableFactory implements KeyValueExpirableFactoryInterf * The serialization class to use. * @param \Drupal\Core\Database\Connection $connection * The Connection object containing the key-value tables. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(SerializationInterface $serializer, Connection $connection) { + public function __construct( + SerializationInterface $serializer, + Connection $connection, + protected ?TimeInterface $time = NULL, + ) { $this->serializer = $serializer; $this->connection = $connection; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -60,7 +71,7 @@ public function get($collection) { public function garbageCollection() { try { $this->connection->delete('key_value_expire') - ->condition('expire', REQUEST_TIME, '<') + ->condition('expire', $this->time->getRequestTime(), '<') ->execute(); } catch (\Exception $e) { diff --git a/core/lib/Drupal/Core/Session/SessionHandler.php b/core/lib/Drupal/Core/Session/SessionHandler.php index e640ad9d0652..e243c425c6db 100644 --- a/core/lib/Drupal/Core/Session/SessionHandler.php +++ b/core/lib/Drupal/Core/Session/SessionHandler.php @@ -2,6 +2,7 @@ namespace Drupal\Core\Session; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\Utility\Crypt; use Drupal\Core\Database\Connection; use Drupal\Core\DependencyInjection\DependencySerializationTrait; @@ -36,10 +37,16 @@ class SessionHandler extends AbstractProxy implements \SessionHandlerInterface { * The request stack. * @param \Drupal\Core\Database\Connection $connection * The database connection. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(RequestStack $request_stack, Connection $connection) { + public function __construct(RequestStack $request_stack, Connection $connection, protected ?TimeInterface $time = NULL) { $this->requestStack = $request_stack; $this->connection = $connection; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -72,7 +79,7 @@ public function write(#[\SensitiveParameter] string $sid, string $value): bool { 'uid' => $request->getSession()->get('uid', 0), 'hostname' => $request->getClientIP(), 'session' => $value, - 'timestamp' => REQUEST_TIME, + 'timestamp' => $this->time->getRequestTime(), ]; $this->connection->merge('sessions') ->keys(['sid' => Crypt::hashBase64($sid)]) @@ -110,7 +117,7 @@ public function gc(int $lifetime): int|false { // to '1814400'. At that value, only after a user doesn't log in after // three weeks (1814400 seconds) will their session be removed. return $this->connection->delete('sessions') - ->condition('timestamp', REQUEST_TIME - $lifetime, '<') + ->condition('timestamp', $this->time->getRequestTime() - $lifetime, '<') ->execute(); } diff --git a/core/lib/Drupal/Core/Session/SessionManager.php b/core/lib/Drupal/Core/Session/SessionManager.php index e64a060978ca..f00b5ed93442 100644 --- a/core/lib/Drupal/Core/Session/SessionManager.php +++ b/core/lib/Drupal/Core/Session/SessionManager.php @@ -2,10 +2,12 @@ namespace Drupal\Core\Session; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Database\Connection; use Drupal\Core\DependencyInjection\DependencySerializationTrait; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; +use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy; /** * Manages user sessions. @@ -77,15 +79,32 @@ class SessionManager extends NativeSessionStorage implements SessionManagerInter * The session metadata bag. * @param \Drupal\Core\Session\SessionConfigurationInterface $session_configuration * The session configuration interface. + * @param \Drupal\Component\Datetime\TimeInterface|null|\Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy|\SessionHandlerInterface $time + * The time service. * @param \Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy|\SessionHandlerInterface|null $handler * The object to register as a PHP session handler. - * @see \Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage::setSaveHandler() + * + * @see \Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage::setSaveHandler() */ - public function __construct(RequestStack $request_stack, Connection $connection, MetadataBag $metadata_bag, SessionConfigurationInterface $session_configuration, $handler = NULL) { + public function __construct( + RequestStack $request_stack, + Connection $connection, + MetadataBag $metadata_bag, + SessionConfigurationInterface $session_configuration, + protected TimeInterface|AbstractProxy|\SessionHandlerInterface|null $time = NULL, + $handler = NULL, + ) { $options = []; $this->sessionConfiguration = $session_configuration; $this->requestStack = $request_stack; $this->connection = $connection; + if (!$time || $time instanceof AbstractProxy || $time instanceof \SessionHandlerInterface) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be the 5th argument in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + if ($time instanceof AbstractProxy || $time instanceof \SessionHandlerInterface) { + $handler = $time; + } + $this->time = \Drupal::service(TimeInterface::class); + } parent::__construct($options, $handler, $metadata_bag); } @@ -242,7 +261,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, '', $this->time->getRequestTime() - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']); $cookies->remove($session_name); } } diff --git a/core/modules/comment/comment.services.yml b/core/modules/comment/comment.services.yml index 770d4ab28782..9bbf020ec5af 100644 --- a/core/modules/comment/comment.services.yml +++ b/core/modules/comment/comment.services.yml @@ -11,8 +11,9 @@ services: Drupal\comment\CommentManagerInterface: '@comment.manager' comment.statistics: + autowire: true class: Drupal\comment\CommentStatistics - arguments: ['@database', '@current_user', '@entity_type.manager', '@state', '@database.replica'] + arguments: ['@database', '@current_user', '@entity_type.manager', '@state', '@datetime.time', '@database.replica'] tags: - { name: backend_overridable } Drupal\comment\CommentStatisticsInterface: '@comment.statistics' diff --git a/core/modules/comment/src/CommentStatistics.php b/core/modules/comment/src/CommentStatistics.php index 5b38f4549eaf..b26a7e1385bb 100644 --- a/core/modules/comment/src/CommentStatistics.php +++ b/core/modules/comment/src/CommentStatistics.php @@ -2,6 +2,7 @@ namespace Drupal\comment; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Database\Connection; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\FieldableEntityInterface; @@ -59,15 +60,31 @@ class CommentStatistics implements CommentStatisticsInterface { * The entity type manager. * @param \Drupal\Core\State\StateInterface $state * The state service. + * @param \Drupal\Component\Datetime\TimeInterface|null|\Drupal\Core\Database\Connection $time + * The time service. * @param \Drupal\Core\Database\Connection|null $database_replica * (Optional) the replica database connection. */ - public function __construct(Connection $database, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, StateInterface $state, Connection $database_replica = NULL) { + public function __construct( + Connection $database, + AccountInterface $current_user, + EntityTypeManagerInterface $entity_type_manager, + StateInterface $state, + protected TimeInterface|Connection|null $time = NULL, + Connection $database_replica = NULL, + ) { $this->database = $database; - $this->databaseReplica = $database_replica ?: $database; $this->currentUser = $current_user; $this->entityTypeManager = $entity_type_manager; $this->state = $state; + if (!$time || $time instanceof Connection) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be the 4th argument in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + if ($time instanceof Connection) { + $database_replica = $time; + } + $this->time = \Drupal::service(TimeInterface::class); + } + $this->databaseReplica = $database_replica ?: $database; } /** @@ -129,8 +146,8 @@ 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 request time when entity does not have a changed property. + $last_comment_timestamp = $this->time->getRequestTime(); // @todo Make comment statistics language aware and add some tests. See // https://www.drupal.org/node/2318875 if ($entity instanceof EntityChangedInterface) { @@ -251,8 +268,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, + // request time. + 'last_comment_timestamp' => ($entity instanceof EntityChangedInterface) ? $entity->getChangedTimeAcrossTranslations() : $this->time->getRequestTime(), 'last_comment_name' => '', 'last_comment_uid' => $last_comment_uid, ]) diff --git a/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php b/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php index 7658c7d8b091..5683676c03db 100644 --- a/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php +++ b/core/modules/comment/tests/src/Unit/CommentStatisticsUnitTest.php @@ -5,6 +5,7 @@ namespace Drupal\Tests\comment\Unit; use Drupal\comment\CommentStatistics; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Tests\UnitTestCase; @@ -87,7 +88,7 @@ protected function setUp(): void { ->method('select') ->willReturn($this->select); - $this->commentStatistics = new CommentStatistics($this->database, $this->createMock('Drupal\Core\Session\AccountInterface'), $this->createMock(EntityTypeManagerInterface::class), $this->createMock('Drupal\Core\State\StateInterface'), $this->database); + $this->commentStatistics = new CommentStatistics($this->database, $this->createMock('Drupal\Core\Session\AccountInterface'), $this->createMock(EntityTypeManagerInterface::class), $this->createMock('Drupal\Core\State\StateInterface'), $this->createMock(TimeInterface::class), $this->database); } /** diff --git a/core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php b/core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php index da3414ffa857..5d68876f998b 100644 --- a/core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php +++ b/core/modules/migrate/tests/src/Kernel/MigrateSqlSourceTestBase.php @@ -5,6 +5,7 @@ use Drupal\Core\Cache\MemoryCounterBackendFactory; use Drupal\sqlite\Driver\Database\sqlite\Connection; use Drupal\Core\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\Reference; /** * Base class for tests of Migrate source plugins that use a database. @@ -16,7 +17,9 @@ abstract class MigrateSqlSourceTestBase extends MigrateSourceTestBase { */ public function register(ContainerBuilder $container) { parent::register($container); - $container->register('cache_factory', MemoryCounterBackendFactory::class); + $container + ->register('cache_factory', MemoryCounterBackendFactory::class) + ->addArgument(new Reference('datetime.time')); } /** diff --git a/core/modules/mysql/tests/src/Kernel/mysql/DbDumpTest.php b/core/modules/mysql/tests/src/Kernel/mysql/DbDumpTest.php index 7e5c18a41b5c..bc509a13b208 100644 --- a/core/modules/mysql/tests/src/Kernel/mysql/DbDumpTest.php +++ b/core/modules/mysql/tests/src/Kernel/mysql/DbDumpTest.php @@ -2,6 +2,7 @@ namespace Drupal\Tests\mysql\Kernel\mysql; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Command\DbDumpApplication; use Drupal\Core\Config\DatabaseStorage; use Drupal\Core\Database\Database; @@ -75,7 +76,8 @@ public function register(ContainerBuilder $container) { ->addArgument(new Reference('database')) ->addArgument(new Reference('cache_tags.invalidator.checksum')) ->addArgument(new Reference('settings')) - ->addArgument(new Reference('serialization.phpserialize')); + ->addArgument(new Reference('serialization.phpserialize')) + ->addArgument(new Reference(TimeInterface::class)); } /** diff --git a/core/modules/path_alias/path_alias.services.yml b/core/modules/path_alias/path_alias.services.yml index 2d8b59aa96fa..8e9d4c51f43b 100644 --- a/core/modules/path_alias/path_alias.services.yml +++ b/core/modules/path_alias/path_alias.services.yml @@ -12,7 +12,7 @@ services: arguments: ['@path_alias.manager'] path_alias.manager: class: Drupal\path_alias\AliasManager - arguments: ['@path_alias.repository', '@path_alias.whitelist', '@language_manager', '@cache.data'] + arguments: ['@path_alias.repository', '@path_alias.whitelist', '@language_manager', '@cache.data', '@datetime.time'] Drupal\path_alias\AliasManagerInterface: '@path_alias.manager' path_alias.repository: class: Drupal\path_alias\AliasRepository diff --git a/core/modules/path_alias/src/AliasManager.php b/core/modules/path_alias/src/AliasManager.php index 9eea31934b60..56670f1e8962 100644 --- a/core/modules/path_alias/src/AliasManager.php +++ b/core/modules/path_alias/src/AliasManager.php @@ -2,6 +2,7 @@ namespace Drupal\path_alias; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\CacheBackendInterface; use Drupal\Core\Language\LanguageInterface; use Drupal\Core\Language\LanguageManagerInterface; @@ -102,12 +103,24 @@ class AliasManager implements AliasManagerInterface { * The language manager. * @param \Drupal\Core\Cache\CacheBackendInterface $cache * Cache backend. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(AliasRepositoryInterface $alias_repository, AliasWhitelistInterface $whitelist, LanguageManagerInterface $language_manager, CacheBackendInterface $cache) { + public function __construct( + AliasRepositoryInterface $alias_repository, + AliasWhitelistInterface $whitelist, + LanguageManagerInterface $language_manager, + CacheBackendInterface $cache, + protected ?TimeInterface $time = NULL, + ) { $this->pathAliasRepository = $alias_repository; $this->languageManager = $language_manager; $this->whitelist = $whitelist; $this->cache = $cache; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -140,7 +153,7 @@ public function writeCache() { } $twenty_four_hours = 60 * 60 * 24; - $this->cache->set($this->cacheKey, $path_lookups, $this->getRequestTime() + $twenty_four_hours); + $this->cache->set($this->cacheKey, $path_lookups, $this->time->getRequestTime() + $twenty_four_hours); } } @@ -291,9 +304,15 @@ protected function pathAliasWhitelistRebuild($path = NULL) { * Wrapper method for REQUEST_TIME constant. * * @return int + * + * @deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use + * the $this->time->getRequestTime() service instead. + * + * @see https://www.drupal.org/node/3387233 */ protected function getRequestTime() { - return defined('REQUEST_TIME') ? REQUEST_TIME : (int) $_SERVER['REQUEST_TIME']; + @trigger_error(__METHOD__ . '() is deprecated in drupal:10.3.0 and is removed from drupal:11.0.0. Use the $this->time->getRequestTime() instead. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + return $this->time->getRequestTime(); } } diff --git a/core/modules/path_alias/tests/src/Kernel/AliasTest.php b/core/modules/path_alias/tests/src/Kernel/AliasTest.php index c46419f94575..7d9ebbcf0e82 100644 --- a/core/modules/path_alias/tests/src/Kernel/AliasTest.php +++ b/core/modules/path_alias/tests/src/Kernel/AliasTest.php @@ -2,6 +2,7 @@ namespace Drupal\Tests\path_alias\Kernel; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\MemoryCounterBackend; use Drupal\Core\Language\LanguageInterface; use Drupal\KernelTests\KernelTestBase; @@ -358,11 +359,11 @@ public function testLookupPath() { * Tests the alias whitelist. */ public function testWhitelist() { - $memoryCounterBackend = new MemoryCounterBackend(); + $memoryCounterBackend = new MemoryCounterBackend(\Drupal::service(TimeInterface::class)); // Create AliasManager and Path object. $whitelist = new AliasWhitelist('path_alias_whitelist', $memoryCounterBackend, $this->container->get('lock'), $this->container->get('state'), $this->container->get('path_alias.repository')); - $aliasManager = new AliasManager($this->container->get('path_alias.repository'), $whitelist, $this->container->get('language_manager'), $memoryCounterBackend); + $aliasManager = new AliasManager($this->container->get('path_alias.repository'), $whitelist, $this->container->get('language_manager'), $memoryCounterBackend, $this->container->get(TimeInterface::class)); // No alias for user and admin yet, so should be NULL. $this->assertNull($whitelist->get('user')); @@ -419,7 +420,7 @@ public function testWhitelist() { * Tests situation where the whitelist cache is deleted mid-request. */ public function testWhitelistCacheDeletionMidRequest() { - $memoryCounterBackend = new MemoryCounterBackend(); + $memoryCounterBackend = new MemoryCounterBackend(\Drupal::service(TimeInterface::class)); // Create AliasManager and Path object. $whitelist = new AliasWhitelist('path_alias_whitelist', $memoryCounterBackend, $this->container->get('lock'), $this->container->get('state'), $this->container->get('path_alias.repository')); diff --git a/core/modules/path_alias/tests/src/Unit/AliasManagerTest.php b/core/modules/path_alias/tests/src/Unit/AliasManagerTest.php index 0a2326fbe906..8a852787f569 100644 --- a/core/modules/path_alias/tests/src/Unit/AliasManagerTest.php +++ b/core/modules/path_alias/tests/src/Unit/AliasManagerTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\path_alias\Unit; +use Drupal\Component\Datetime\Time; use Drupal\Core\Language\Language; use Drupal\Core\Language\LanguageInterface; use Drupal\path_alias\AliasRepositoryInterface; @@ -76,7 +77,7 @@ protected function setUp(): void { $this->languageManager = $this->createMock('Drupal\Core\Language\LanguageManagerInterface'); $this->cache = $this->createMock('Drupal\Core\Cache\CacheBackendInterface'); - $this->aliasManager = new AliasManager($this->aliasRepository, $this->aliasWhitelist, $this->languageManager, $this->cache); + $this->aliasManager = new AliasManager($this->aliasRepository, $this->aliasWhitelist, $this->languageManager, $this->cache, new Time()); } diff --git a/core/modules/search/search.services.yml b/core/modules/search/search.services.yml index bda507af4f04..85360e5f8a8e 100644 --- a/core/modules/search/search.services.yml +++ b/core/modules/search/search.services.yml @@ -10,7 +10,7 @@ services: search.index: class: Drupal\search\SearchIndex - arguments: ['@config.factory', '@database','@database.replica', '@cache_tags.invalidator', '@search.text_processor'] + arguments: ['@config.factory', '@database','@database.replica', '@cache_tags.invalidator', '@search.text_processor', '@datetime.time'] tags: - { name: backend_overridable } Drupal\search\SearchIndexInterface: '@search.index' diff --git a/core/modules/search/src/SearchIndex.php b/core/modules/search/src/SearchIndex.php index 97f57abe129a..2e11edca6253 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; @@ -60,13 +61,26 @@ class SearchIndex implements SearchIndexInterface { * The cache tags invalidator. * @param \Drupal\search\SearchTextProcessorInterface $text_processor * The text processor. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service */ - public function __construct(ConfigFactoryInterface $config_factory, Connection $connection, Connection $replica, CacheTagsInvalidatorInterface $cache_tags_invalidator, SearchTextProcessorInterface $text_processor) { + public function __construct( + ConfigFactoryInterface $config_factory, + Connection $connection, + Connection $replica, + CacheTagsInvalidatorInterface $cache_tags_invalidator, + SearchTextProcessorInterface $text_processor, + protected ?TimeInterface $time = NULL, + ) { $this->configFactory = $config_factory; $this->connection = $connection; $this->replica = $replica; $this->cacheTagsInvalidator = $cache_tags_invalidator; $this->textProcessor = $text_processor; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -265,7 +279,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/system/system.services.yml b/core/modules/system/system.services.yml index 7754d1437285..1685ae552013 100644 --- a/core/modules/system/system.services.yml +++ b/core/modules/system/system.services.yml @@ -82,6 +82,7 @@ services: arguments: ['@menu.link_tree', '@system.module_admin_links_memory_cache'] system.module_admin_links_memory_cache: class: Drupal\Core\Cache\MemoryCache\MemoryCache + arguments: ['@datetime.time'] system.access_route_alter_subscriber: class: Drupal\system\EventSubscriber\AccessRouteAlterSubscriber tags: diff --git a/core/modules/system/tests/src/Kernel/System/FloodTest.php b/core/modules/system/tests/src/Kernel/System/FloodTest.php index 3b682a8cd755..49f98ea283f3 100644 --- a/core/modules/system/tests/src/Kernel/System/FloodTest.php +++ b/core/modules/system/tests/src/Kernel/System/FloodTest.php @@ -2,6 +2,7 @@ namespace Drupal\Tests\system\Kernel\System; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Flood\DatabaseBackend; use Drupal\Core\Flood\MemoryBackend; use Drupal\KernelTests\KernelTestBase; @@ -56,7 +57,8 @@ public function testDatabaseBackend() { $connection = \Drupal::service('database'); $request_stack = \Drupal::service('request_stack'); - $flood = new DatabaseBackend($connection, $request_stack); + $time = \Drupal::service(TimeInterface::class); + $flood = new DatabaseBackend($connection, $request_stack, $time); $this->assertTrue($flood->isAllowed($name, $threshold)); // Register expired event. $flood->register($name, $window_expired); @@ -81,10 +83,11 @@ public function testDatabaseBackend() { public function floodBackendProvider() :array { $request_stack = \Drupal::service('request_stack'); $connection = \Drupal::service('database'); + $time = \Drupal::service(TimeInterface::class); return [ new MemoryBackend($request_stack), - new DatabaseBackend($connection, $request_stack), + new DatabaseBackend($connection, $request_stack, $time), ]; } diff --git a/core/modules/update/src/UpdateProcessor.php b/core/modules/update/src/UpdateProcessor.php index a07a47c8f51b..71eb1d8ef0dd 100644 --- a/core/modules/update/src/UpdateProcessor.php +++ b/core/modules/update/src/UpdateProcessor.php @@ -2,6 +2,7 @@ namespace Drupal\update; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\Utility\Crypt; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\KeyValueStore\KeyValueFactoryInterface; @@ -100,8 +101,19 @@ class UpdateProcessor implements UpdateProcessorInterface { * The key/value factory. * @param \Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface $key_value_expirable_factory * The expirable key/value factory. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(ConfigFactoryInterface $config_factory, QueueFactory $queue_factory, UpdateFetcherInterface $update_fetcher, StateInterface $state_store, PrivateKey $private_key, KeyValueFactoryInterface $key_value_factory, KeyValueExpirableFactoryInterface $key_value_expirable_factory) { + public function __construct( + ConfigFactoryInterface $config_factory, + QueueFactory $queue_factory, + UpdateFetcherInterface $update_fetcher, + StateInterface $state_store, + PrivateKey $private_key, + KeyValueFactoryInterface $key_value_factory, + KeyValueExpirableFactoryInterface $key_value_expirable_factory, + protected ?TimeInterface $time = NULL, + ) { $this->updateFetcher = $update_fetcher; $this->updateSettings = $config_factory->get('update.settings'); $this->fetchQueue = $queue_factory->get('update_fetch_tasks'); @@ -110,6 +122,10 @@ public function __construct(ConfigFactoryInterface $config_factory, QueueFactory $this->availableReleasesTempStore = $key_value_expirable_factory->get('update_available_releases'); $this->stateStore = $state_store; $this->privateKey = $private_key; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } $this->fetchTasks = []; $this->failed = []; } diff --git a/core/modules/update/update.services.yml b/core/modules/update/update.services.yml index 0c19e7a010f0..56ff7c1cee93 100644 --- a/core/modules/update/update.services.yml +++ b/core/modules/update/update.services.yml @@ -10,7 +10,7 @@ services: Drupal\update\UpdateManagerInterface: '@update.manager' update.processor: class: Drupal\update\UpdateProcessor - arguments: ['@config.factory', '@queue', '@update.fetcher', '@state', '@private_key', '@keyvalue', '@keyvalue.expirable'] + arguments: ['@config.factory', '@queue', '@update.fetcher', '@state', '@private_key', '@keyvalue', '@keyvalue.expirable', '@datetime.time'] Drupal\update\UpdateProcessorInterface: '@update.processor' update.fetcher: class: Drupal\update\UpdateFetcher diff --git a/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php b/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php index 31eff42f7be8..e5d8edc67e71 100644 --- a/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php +++ b/core/modules/user/src/EventSubscriber/UserRequestSubscriber.php @@ -2,6 +2,7 @@ namespace Drupal\user\EventSubscriber; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\Site\Settings; @@ -35,10 +36,16 @@ class UserRequestSubscriber implements EventSubscriberInterface { * The current user. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager * The entity type manager service. + * @param \Drupal\Component\Datetime\TimeInterface|null $time + * The time service. */ - public function __construct(AccountInterface $account, EntityTypeManagerInterface $entity_type_manager) { + public function __construct(AccountInterface $account, EntityTypeManagerInterface $entity_type_manager, protected ?TimeInterface $time = NULL) { $this->account = $account; $this->entityTypeManager = $entity_type_manager; + if (!$time) { + @trigger_error('Calling ' . __METHOD__ . '() without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3387233', E_USER_DEPRECATED); + $this->time = \Drupal::service(TimeInterface::class); + } } /** @@ -48,11 +55,11 @@ public function __construct(AccountInterface $account, EntityTypeManagerInterfac * The event to process. */ public function onKernelTerminate(TerminateEvent $event) { - if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) { + if ($this->account->isAuthenticated() && $this->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, $this->time->getRequestTime()); } } diff --git a/core/modules/user/user.services.yml b/core/modules/user/user.services.yml index f9e0b718961a..5579d0da6744 100644 --- a/core/modules/user/user.services.yml +++ b/core/modules/user/user.services.yml @@ -39,7 +39,7 @@ services: - { name: event_subscriber } user_last_access_subscriber: class: Drupal\user\EventSubscriber\UserRequestSubscriber - arguments: ['@current_user', '@entity_type.manager'] + arguments: ['@current_user', '@entity_type.manager', '@datetime.time'] tags: - { name: event_subscriber } theme.negotiator.admin_theme: diff --git a/core/phpstan-baseline.neon b/core/phpstan-baseline.neon index 96046d07f6cf..e727def905d1 100644 --- a/core/phpstan-baseline.neon +++ b/core/phpstan-baseline.neon @@ -227,11 +227,6 @@ parameters: count: 2 path: lib/Drupal/Core/Asset/JsCollectionGrouper.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 1 - path: lib/Drupal/Core/Asset/JsCollectionRenderer.php - - message: "#^Call to method getDefinitions\\(\\) on an unknown class Drupal\\\\Core\\\\Plugin\\\\CategorizingPluginManagerTrait\\.$#" count: 1 @@ -242,11 +237,6 @@ parameters: count: 1 path: lib/Drupal/Core/Block/BlockManager.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 3 - path: lib/Drupal/Core/Cache/ApcuBackend.php - - message: """ #^Class Drupal\\\\Core\\\\Cache\\\\CacheFactory implements deprecated interface Symfony\\\\Component\\\\DependencyInjection\\\\ContainerAwareInterface\\: @@ -271,26 +261,11 @@ parameters: count: 1 path: lib/Drupal/Core/Cache/ChainedFastBackendFactory.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 4 - path: lib/Drupal/Core/Cache/DatabaseBackend.php - - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 1 - path: lib/Drupal/Core/Cache/MemoryBackend.php - - message: "#^Constructor of class Drupal\\\\Core\\\\Cache\\\\NullBackend has an unused parameter \\$bin\\.$#" count: 1 path: lib/Drupal/Core/Cache/NullBackend.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 2 - path: lib/Drupal/Core/Cache/PhpBackend.php - - message: "#^Call to method getDefinitions\\(\\) on an unknown class Drupal\\\\Core\\\\Plugin\\\\CategorizingPluginManagerTrait\\.$#" count: 1 @@ -613,11 +588,6 @@ parameters: count: 1 path: lib/Drupal/Core/Entity/Sql/SqlContentEntityStorageSchema.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 2 - path: lib/Drupal/Core/EventSubscriber/FinishResponseSubscriber.php - - message: """ #^Call to deprecated method getFromDriverName\\(\\) of class Drupal\\\\Core\\\\Extension\\\\DatabaseDriverList\\: @@ -712,11 +682,6 @@ parameters: count: 9 path: lib/Drupal/Core/FileTransfer/SSH.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 4 - path: lib/Drupal/Core/Flood/DatabaseBackend.php - - message: "#^Method Drupal\\\\Core\\\\Form\\\\FormBuilder\\:\\:setInvalidTokenError\\(\\) should return \\$this\\(Drupal\\\\Core\\\\Form\\\\FormBuilder\\) but return statement is missing\\.$#" count: 1 @@ -757,11 +722,6 @@ parameters: count: 4 path: lib/Drupal/Core/KeyValueStore/DatabaseStorageExpirable.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 1 - path: lib/Drupal/Core/KeyValueStore/KeyValueDatabaseExpirableFactory.php - - message: "#^Method Drupal\\\\Core\\\\KeyValueStore\\\\NullStorageExpirable\\:\\:setIfNotExists\\(\\) should return bool but return statement is missing\\.$#" count: 1 @@ -878,16 +838,6 @@ parameters: count: 1 path: lib/Drupal/Core/Routing/MatcherDumper.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 2 - path: lib/Drupal/Core/Session/SessionHandler.php - - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 1 - path: lib/Drupal/Core/Session/SessionManager.php - - message: "#^Variable \\$current might not be defined\\.$#" count: 1 @@ -1083,11 +1033,6 @@ parameters: count: 1 path: modules/comment/src/CommentForm.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 2 - path: modules/comment/src/CommentStatistics.php - - message: "#^Method Drupal\\\\comment\\\\CommentTypeForm\\:\\:save\\(\\) should return int but return statement is missing\\.$#" count: 1 @@ -1984,11 +1929,6 @@ parameters: count: 1 path: modules/path/src/Plugin/Field/FieldType/PathItem.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 1 - path: modules/path_alias/src/AliasManager.php - - message: """ #^Call to deprecated method makeSequenceName\\(\\) of class Drupal\\\\Core\\\\Database\\\\Connection\\: @@ -2052,11 +1992,6 @@ parameters: count: 1 path: modules/search/src/Form/SearchPageFormBase.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 1 - path: modules/search/src/SearchIndex.php - - message: "#^Method Drupal\\\\search\\\\SearchPageRepository\\:\\:setDefaultSearchPage\\(\\) should return static\\(Drupal\\\\search\\\\SearchPageRepository\\) but return statement is missing\\.$#" count: 1 @@ -2312,11 +2247,6 @@ parameters: count: 1 path: modules/user/src/Controller/UserAuthenticationController.php - - - message: "#^Call to deprecated constant REQUEST_TIME\\: Deprecated in drupal\\:8\\.3\\.0 and is removed from drupal\\:11\\.0\\.0\\. Use \\\\Drupal\\:\\:time\\(\\)\\-\\>getRequestTime\\(\\); $#" - count: 2 - path: modules/user/src/EventSubscriber/UserRequestSubscriber.php - - message: "#^Variable \\$route_object might not be defined\\.$#" count: 1 diff --git a/core/tests/Drupal/KernelTests/Core/Cache/ApcuBackendTest.php b/core/tests/Drupal/KernelTests/Core/Cache/ApcuBackendTest.php index 7983cc7b2bb2..01689adbbc52 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/ApcuBackendTest.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/ApcuBackendTest.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\ApcuBackend; /** @@ -16,7 +17,7 @@ class ApcuBackendTest extends GenericCacheBackendUnitTestBase { * {@inheritdoc} */ protected function createCacheBackend($bin) { - return new ApcuBackend($bin, $this->databasePrefix, \Drupal::service('cache_tags.invalidator.checksum')); + return new ApcuBackend($bin, $this->databasePrefix, \Drupal::service('cache_tags.invalidator.checksum'), \Drupal::service(TimeInterface::class)); } /** diff --git a/core/tests/Drupal/KernelTests/Core/Cache/BackendChainTest.php b/core/tests/Drupal/KernelTests/Core/Cache/BackendChainTest.php index 5cdc41334611..23d33d784beb 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/BackendChainTest.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/BackendChainTest.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\BackendChain; use Drupal\Core\Cache\MemoryBackend; @@ -16,10 +17,11 @@ protected function createCacheBackend($bin) { $chain = new BackendChain(); // We need to create some various backends in the chain. + $time = \Drupal::service(TimeInterface::class); $chain - ->appendBackend(new MemoryBackend()) - ->prependBackend(new MemoryBackend()) - ->appendBackend(new MemoryBackend()); + ->appendBackend(new MemoryBackend($time)) + ->prependBackend(new MemoryBackend($time)) + ->appendBackend(new MemoryBackend($time)); \Drupal::service('cache_tags.invalidator')->addInvalidator($chain); diff --git a/core/tests/Drupal/KernelTests/Core/Cache/ChainedFastBackendTest.php b/core/tests/Drupal/KernelTests/Core/Cache/ChainedFastBackendTest.php index 1a84ddee0809..c5c4e8609b8a 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/ChainedFastBackendTest.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/ChainedFastBackendTest.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\ChainedFastBackend; use Drupal\Core\Cache\DatabaseBackend; use Drupal\Core\Cache\PhpBackend; @@ -20,8 +21,8 @@ class ChainedFastBackendTest extends GenericCacheBackendUnitTestBase { * A new ChainedFastBackend object. */ protected function createCacheBackend($bin) { - $consistent_backend = new DatabaseBackend(\Drupal::service('database'), \Drupal::service('cache_tags.invalidator.checksum'), $bin, \Drupal::service('serialization.phpserialize'), 100); - $fast_backend = new PhpBackend($bin, \Drupal::service('cache_tags.invalidator.checksum')); + $consistent_backend = new DatabaseBackend(\Drupal::service('database'), \Drupal::service('cache_tags.invalidator.checksum'), $bin, \Drupal::service('serialization.phpserialize'), \Drupal::service(TimeInterface::class), 100); + $fast_backend = new PhpBackend($bin, \Drupal::service('cache_tags.invalidator.checksum'), \Drupal::service(TimeInterface::class)); $backend = new ChainedFastBackend($consistent_backend, $fast_backend, $bin); // Explicitly register the cache bin as it can not work through the // cache bin list in the container. diff --git a/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTest.php b/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTest.php index 8a40e909a5fb..e9fe30ed80e5 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTest.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTest.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\DatabaseBackend; /** @@ -32,7 +33,14 @@ class DatabaseBackendTest extends GenericCacheBackendUnitTestBase { * A new DatabaseBackend object. */ protected function createCacheBackend($bin) { - return new DatabaseBackend($this->container->get('database'), $this->container->get('cache_tags.invalidator.checksum'), $bin, $this->container->get('serialization.phpserialize'), static::$maxRows); + return new DatabaseBackend( + $this->container->get('database'), + $this->container->get('cache_tags.invalidator.checksum'), + $bin, + $this->container->get('serialization.phpserialize'), + \Drupal::service(TimeInterface::class), + static::$maxRows, + ); } /** diff --git a/core/tests/Drupal/KernelTests/Core/Cache/EndOfTransactionQueriesTest.php b/core/tests/Drupal/KernelTests/Core/Cache/EndOfTransactionQueriesTest.php index 63ecff81f2e0..a50b2827f51f 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/EndOfTransactionQueriesTest.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/EndOfTransactionQueriesTest.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\Cache; use Drupal\Core\Cache\DatabaseBackendFactory; use Drupal\Core\Database\Database; @@ -54,7 +55,8 @@ public function register(ContainerBuilder $container) { ->addArgument(new Reference('database')) ->addArgument(new Reference('cache_tags.invalidator.checksum')) ->addArgument(new Reference('settings')) - ->addArgument(new Reference('serializer')); + ->addArgument(new Reference('serializer')) + ->addArgument(new Reference(TimeInterface::class)); } /** diff --git a/core/tests/Drupal/KernelTests/Core/Cache/MemoryBackendTest.php b/core/tests/Drupal/KernelTests/Core/Cache/MemoryBackendTest.php index ad6da493024a..9051840e7b19 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/MemoryBackendTest.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/MemoryBackendTest.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\MemoryBackend; /** @@ -18,7 +19,7 @@ class MemoryBackendTest extends GenericCacheBackendUnitTestBase { * A new MemoryBackend object. */ protected function createCacheBackend($bin) { - $backend = new MemoryBackend(); + $backend = new MemoryBackend(\Drupal::service(TimeInterface::class)); \Drupal::service('cache_tags.invalidator')->addInvalidator($backend); return $backend; } diff --git a/core/tests/Drupal/KernelTests/Core/Cache/PhpBackendTest.php b/core/tests/Drupal/KernelTests/Core/Cache/PhpBackendTest.php index b35a3b94f035..176d9b8fe1da 100644 --- a/core/tests/Drupal/KernelTests/Core/Cache/PhpBackendTest.php +++ b/core/tests/Drupal/KernelTests/Core/Cache/PhpBackendTest.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\PhpBackend; /** @@ -18,8 +19,7 @@ class PhpBackendTest extends GenericCacheBackendUnitTestBase { * A new PhpBackend object. */ protected function createCacheBackend($bin) { - $backend = new PhpBackend($bin, \Drupal::service('cache_tags.invalidator.checksum')); - return $backend; + return new PhpBackend($bin, \Drupal::service('cache_tags.invalidator.checksum'), \Drupal::service(TimeInterface::class)); } } diff --git a/core/tests/Drupal/KernelTests/Core/DrupalKernel/DrupalKernelSiteTest.php b/core/tests/Drupal/KernelTests/Core/DrupalKernel/DrupalKernelSiteTest.php index e8bdd9041921..5d3c9b5fe352 100644 --- a/core/tests/Drupal/KernelTests/Core/DrupalKernel/DrupalKernelSiteTest.php +++ b/core/tests/Drupal/KernelTests/Core/DrupalKernel/DrupalKernelSiteTest.php @@ -28,6 +28,11 @@ public function testServicesYml() { $class = __CLASS__; $doc = <<<EOD services: + _defaults: + autowire: true + Symfony\Component\HttpFoundation\RequestStack: ~ + Drupal\Component\Datetime\TimeInterface: + class: Drupal\Component\Datetime\Time # Add a new service. site.service.yml: class: $class diff --git a/core/tests/Drupal/KernelTests/Core/Plugin/PluginTestBase.php b/core/tests/Drupal/KernelTests/Core/Plugin/PluginTestBase.php index b1b48d0db883..2b29ecd2a6f1 100644 --- a/core/tests/Drupal/KernelTests/Core/Plugin/PluginTestBase.php +++ b/core/tests/Drupal/KernelTests/Core/Plugin/PluginTestBase.php @@ -2,6 +2,7 @@ namespace Drupal\KernelTests\Core\Plugin; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Plugin\Context\EntityContextDefinition; use Drupal\KernelTests\KernelTestBase; use Drupal\plugin_test\Plugin\TestPluginManager; @@ -45,7 +46,7 @@ protected function setUp(): void { // as derivatives and ReflectionFactory. $this->testPluginManager = new TestPluginManager(); $this->mockBlockManager = new MockBlockManager(); - $module_handler = new ModuleHandler($this->root, [], new MemoryBackend()); + $module_handler = new ModuleHandler($this->root, [], new MemoryBackend(\Drupal::service(TimeInterface::class))); $this->defaultsTestPluginManager = new DefaultsTestPluginManager($module_handler); // The expected plugin definitions within each manager. Several tests assert diff --git a/core/tests/Drupal/KernelTests/Core/Routing/RouteProviderTest.php b/core/tests/Drupal/KernelTests/Core/Routing/RouteProviderTest.php index 6df9a249fe22..03c04c3c982a 100644 --- a/core/tests/Drupal/KernelTests/Core/Routing/RouteProviderTest.php +++ b/core/tests/Drupal/KernelTests/Core/Routing/RouteProviderTest.php @@ -3,6 +3,7 @@ namespace Drupal\KernelTests\Core\Routing; use ColinODell\PsrTestLogger\TestLogger; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\MemoryBackend; use Drupal\Core\Database\Database; use Drupal\Core\KeyValueStore\KeyValueMemoryFactory; @@ -97,7 +98,7 @@ protected function setUp(): void { $this->fixtures = new RoutingFixtures(); $this->state = new State(new KeyValueMemoryFactory()); $this->currentPath = new CurrentPathStack(new RequestStack()); - $this->cache = new MemoryBackend(); + $this->cache = new MemoryBackend(\Drupal::service(TimeInterface::class)); $this->pathProcessor = \Drupal::service('path_processor_manager'); $this->cacheTagsInvalidator = \Drupal::service('cache_tags.invalidator'); $this->installEntitySchema('path_alias'); diff --git a/core/tests/Drupal/KernelTests/KernelTestBase.php b/core/tests/Drupal/KernelTests/KernelTestBase.php index ce3d4318c89c..2e449e8c7d1d 100644 --- a/core/tests/Drupal/KernelTests/KernelTestBase.php +++ b/core/tests/Drupal/KernelTests/KernelTestBase.php @@ -561,13 +561,16 @@ public function register(ContainerBuilder $container) { // Keep the container object around for tests. $this->container = $container; + $container + ->register('datetime.time', 'Drupal\Component\Datetime\Time'); $container ->register('flood', 'Drupal\Core\Flood\MemoryBackend') ->addArgument(new Reference('request_stack')); $container ->register('lock', 'Drupal\Core\Lock\NullLockBackend'); $container - ->register('cache_factory', 'Drupal\Core\Cache\MemoryBackendFactory'); + ->register('cache_factory', 'Drupal\Core\Cache\MemoryBackendFactory') + ->addArgument(new Reference('datetime.time')); // Use memory for key value storages to avoid database queries. Store the // key value factory on the test object so that key value storages persist diff --git a/core/tests/Drupal/Tests/Core/Asset/AssetResolverTest.php b/core/tests/Drupal/Tests/Core/Asset/AssetResolverTest.php index 07db8514ed3d..41c53115e997 100644 --- a/core/tests/Drupal/Tests/Core/Asset/AssetResolverTest.php +++ b/core/tests/Drupal/Tests/Core/Asset/AssetResolverTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Asset; +use Drupal\Component\Datetime\Time; use Drupal\Core\Asset\AssetResolver; use Drupal\Core\Asset\AttachedAssets; use Drupal\Core\Asset\AttachedAssetsInterface; @@ -116,7 +117,7 @@ protected function setUp(): void { $this->languageManager->expects($this->any()) ->method('getCurrentLanguage') ->will($this->onConsecutiveCalls($english, $english, $japanese, $japanese)); - $this->cache = new TestMemoryBackend(); + $this->cache = new TestMemoryBackend(new Time()); $this->assetResolver = new AssetResolver($this->libraryDiscovery, $this->libraryDependencyResolver, $this->moduleHandler, $this->themeManager, $this->languageManager, $this->cache); } diff --git a/core/tests/Drupal/Tests/Core/Cache/BackendChainImplementationUnitTest.php b/core/tests/Drupal/Tests/Core/Cache/BackendChainImplementationUnitTest.php index 6dba9c583293..43e94f18d935 100644 --- a/core/tests/Drupal/Tests/Core/Cache/BackendChainImplementationUnitTest.php +++ b/core/tests/Drupal/Tests/Core/Cache/BackendChainImplementationUnitTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Cache; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\BackendChain; use Drupal\Core\Cache\Cache; use Drupal\Core\Cache\MemoryBackend; @@ -52,9 +53,10 @@ protected function setUp(): void { parent::setUp(); // Set up three memory backends to be used in the chain. - $this->firstBackend = new MemoryBackend(); - $this->secondBackend = new MemoryBackend(); - $this->thirdBackend = new MemoryBackend(); + $time = new Time(); + $this->firstBackend = new MemoryBackend($time); + $this->secondBackend = new MemoryBackend($time); + $this->thirdBackend = new MemoryBackend($time); // Set an initial fixed dataset for all testing. The next three data // collections will test two edge cases (last backend has the data, and diff --git a/core/tests/Drupal/Tests/Core/Cache/ChainedFastBackendTest.php b/core/tests/Drupal/Tests/Core/Cache/ChainedFastBackendTest.php index 560a1a7d97e6..47a495e9d993 100644 --- a/core/tests/Drupal/Tests/Core/Cache/ChainedFastBackendTest.php +++ b/core/tests/Drupal/Tests/Core/Cache/ChainedFastBackendTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Cache; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\ChainedFastBackend; use Drupal\Core\Cache\MemoryBackend; use Drupal\Tests\UnitTestCase; @@ -49,7 +50,7 @@ public function testGetDoesNotHitConsistentBackend() { $consistent_cache->expects($this->never()) ->method('getMultiple'); - $fast_cache = new MemoryBackend(); + $fast_cache = new MemoryBackend(new Time()); $fast_cache->set('foo', 'baz'); $chained_fast_backend = new ChainedFastBackend( diff --git a/core/tests/Drupal/Tests/Core/Cache/DatabaseBackendFactoryTest.php b/core/tests/Drupal/Tests/Core/Cache/DatabaseBackendFactoryTest.php index a0ea25e7823a..d2c3ad1dd545 100644 --- a/core/tests/Drupal/Tests/Core/Cache/DatabaseBackendFactoryTest.php +++ b/core/tests/Drupal/Tests/Core/Cache/DatabaseBackendFactoryTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Cache; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Component\Serialization\PhpSerialize; use Drupal\Core\Cache\CacheTagsChecksumInterface; use Drupal\Core\Cache\DatabaseBackend; @@ -28,7 +29,8 @@ public function testGet(array $settings, $expected_max_rows_foo, $expected_max_r $this->prophesize(Connection::class)->reveal(), $this->prophesize(CacheTagsChecksumInterface::class)->reveal(), new Settings($settings), - new PhpSerialize() + new PhpSerialize(), + $this->prophesize(TimeInterface::class)->reveal(), ); $this->assertSame($expected_max_rows_foo, $database_backend_factory->get('foo')->getMaxRows()); diff --git a/core/tests/Drupal/Tests/Core/Cache/VariationCacheTest.php b/core/tests/Drupal/Tests/Core/Cache/VariationCacheTest.php index a63a73637851..b53040970b29 100644 --- a/core/tests/Drupal/Tests/Core/Cache/VariationCacheTest.php +++ b/core/tests/Drupal/Tests/Core/Cache/VariationCacheTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Cache; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Cache\CacheRedirect; use Drupal\Core\Cache\Context\CacheContextsManager; @@ -125,7 +126,7 @@ class VariationCacheTest extends UnitTestCase { protected function setUp(): void { parent::setUp(); $this->requestStack = $this->prophesize(RequestStack::class); - $this->memoryBackend = new MemoryBackend(); + $this->memoryBackend = new MemoryBackend(new Time()); $this->cacheContextsManager = $this->prophesize(CacheContextsManager::class); $housing_type = &$this->housingType; diff --git a/core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php b/core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php index 77ab459be41b..291eefba8dd8 100644 --- a/core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php +++ b/core/tests/Drupal/Tests/Core/Config/Entity/ConfigEntityStorageTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Config\Entity; +use Drupal\Component\Datetime\Time; use Drupal\Component\Uuid\UuidInterface; use Drupal\Core\Cache\Cache; use Drupal\Core\Cache\CacheTagsInvalidatorInterface; @@ -139,7 +140,7 @@ protected function setUp(): void { $entity_query_factory = $this->prophesize(QueryFactoryInterface::class); $entity_query_factory->get($entity_type, 'AND')->willReturn($this->entityQuery->reveal()); - $this->entityStorage = new ConfigEntityStorage($entity_type, $this->configFactory->reveal(), $this->uuidService->reveal(), $this->languageManager->reveal(), new MemoryCache()); + $this->entityStorage = new ConfigEntityStorage($entity_type, $this->configFactory->reveal(), $this->uuidService->reveal(), $this->languageManager->reveal(), new MemoryCache(new Time())); $this->entityStorage->setModuleHandler($this->moduleHandler->reveal()); $entity_type_manager = $this->prophesize(EntityTypeManagerInterface::class); diff --git a/core/tests/Drupal/Tests/Core/Entity/KeyValueStore/KeyValueEntityStorageTest.php b/core/tests/Drupal/Tests/Core/Entity/KeyValueStore/KeyValueEntityStorageTest.php index 613bbddb43bd..17e6056c2978 100644 --- a/core/tests/Drupal/Tests/Core/Entity/KeyValueStore/KeyValueEntityStorageTest.php +++ b/core/tests/Drupal/Tests/Core/Entity/KeyValueStore/KeyValueEntityStorageTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Entity\KeyValueStore; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\MemoryCache\MemoryCache; use Drupal\Core\Config\Entity\ConfigEntityInterface; use Drupal\Core\DependencyInjection\ContainerBuilder; @@ -137,7 +138,7 @@ protected function setUpKeyValueEntityStorage($uuid_key = 'uuid') { ->method('getCurrentLanguage') ->willReturn($language); - $this->entityStorage = new KeyValueEntityStorage($this->entityType, $this->keyValueStore, $this->uuidService, $this->languageManager, new MemoryCache()); + $this->entityStorage = new KeyValueEntityStorage($this->entityType, $this->keyValueStore, $this->uuidService, $this->languageManager, new MemoryCache(new Time())); $this->entityStorage->setModuleHandler($this->moduleHandler); $container = new ContainerBuilder(); diff --git a/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageTest.php b/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageTest.php index f414fa399399..3031589477b2 100644 --- a/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageTest.php +++ b/core/tests/Drupal/Tests/Core/Entity/Sql/SqlContentEntityStorageTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Entity\Sql; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\MemoryCache\MemoryCache; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\Entity\EntityFieldManager; @@ -426,7 +427,7 @@ public function testOnEntityTypeCreate() { ->willReturn($schema_handler); $storage = $this->getMockBuilder('Drupal\Core\Entity\Sql\SqlContentEntityStorage') - ->setConstructorArgs([$this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()]) + ->setConstructorArgs([$this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(new Time()), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()]) ->onlyMethods(['getStorageSchema']) ->getMock(); @@ -1175,7 +1176,7 @@ protected function setUpEntityStorage() { ->getActiveFieldStorageDefinitions($this->entityType->id()) ->willReturn($this->fieldDefinitions); - $this->entityStorage = new SqlContentEntityStorage($this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()); + $this->entityStorage = new SqlContentEntityStorage($this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(new Time()), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()); $this->entityStorage->setModuleHandler($this->moduleHandler); } @@ -1249,7 +1250,7 @@ public function testLoadMultipleNoPersistentCache() { ->willReturn($this->entityType); $entity_storage = $this->getMockBuilder('Drupal\Core\Entity\Sql\SqlContentEntityStorage') - ->setConstructorArgs([$this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()]) + ->setConstructorArgs([$this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(new Time()), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()]) ->onlyMethods(['getFromStorage', 'invokeStorageLoadHook', 'initTableLayout']) ->getMock(); $entity_storage->method('invokeStorageLoadHook') @@ -1309,7 +1310,7 @@ public function testLoadMultiplePersistentCacheMiss() { ->willReturn($this->entityType); $entity_storage = $this->getMockBuilder('Drupal\Core\Entity\Sql\SqlContentEntityStorage') - ->setConstructorArgs([$this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()]) + ->setConstructorArgs([$this->entityType, $this->connection, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(new Time()), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()]) ->onlyMethods(['getFromStorage', 'invokeStorageLoadHook', 'initTableLayout']) ->getMock(); $entity_storage->method('invokeStorageLoadHook') @@ -1370,7 +1371,7 @@ public function testHasData() { ->getActiveFieldStorageDefinitions($this->entityType->id()) ->willReturn($this->fieldDefinitions); - $this->entityStorage = new SqlContentEntityStorage($this->entityType, $database, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()); + $this->entityStorage = new SqlContentEntityStorage($this->entityType, $database, $this->entityFieldManager->reveal(), $this->cache, $this->languageManager, new MemoryCache(new Time()), $this->entityTypeBundleInfo, $this->entityTypeManager->reveal()); $result = $this->entityStorage->hasData(); diff --git a/core/tests/Drupal/Tests/Core/EventSubscriber/FinishResponseSubscriberTest.php b/core/tests/Drupal/Tests/Core/EventSubscriber/FinishResponseSubscriberTest.php index 4a5033e939a4..bcab1e7c65e9 100644 --- a/core/tests/Drupal/Tests/Core/EventSubscriber/FinishResponseSubscriberTest.php +++ b/core/tests/Drupal/Tests/Core/EventSubscriber/FinishResponseSubscriberTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\EventSubscriber; +use Drupal\Component\Datetime\TimeInterface; use Drupal\Core\Cache\Context\CacheContextsManager; use Drupal\Core\EventSubscriber\FinishResponseSubscriber; use Drupal\Core\Language\Language; @@ -58,6 +59,13 @@ class FinishResponseSubscriberTest extends UnitTestCase { */ protected $cacheContextsManager; + /** + * The mock time service. + * + * @var \Drupal\Component\Datetime\TimeInterface|\PHPUnit\Framework\MockObject\MockObject + */ + protected $time; + protected function setUp(): void { parent::setUp(); @@ -66,6 +74,7 @@ protected function setUp(): void { $this->requestPolicy = $this->createMock(RequestPolicyInterface::class); $this->responsePolicy = $this->createMock(ResponsePolicyInterface::class); $this->cacheContextsManager = $this->createMock(CacheContextsManager::class); + $this->time = $this->createMock(TimeInterface::class); } /** @@ -80,6 +89,7 @@ public function testDefaultHeaders() { $this->requestPolicy, $this->responsePolicy, $this->cacheContextsManager, + $this->time, FALSE ); @@ -110,6 +120,7 @@ public function testExistingHeaders() { $this->requestPolicy, $this->responsePolicy, $this->cacheContextsManager, + $this->time, FALSE ); diff --git a/core/tests/Drupal/Tests/Core/Render/RendererBubblingTest.php b/core/tests/Drupal/Tests/Core/Render/RendererBubblingTest.php index b1ef2e2f7f04..fb6a43c9fb0b 100644 --- a/core/tests/Drupal/Tests/Core/Render/RendererBubblingTest.php +++ b/core/tests/Drupal/Tests/Core/Render/RendererBubblingTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Render; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Cache\MemoryBackend; use Drupal\Core\Cache\VariationCache; @@ -80,8 +81,8 @@ public function testContextBubblingCustomCacheBin() { $bin = $this->randomMachineName(); $this->setUpRequest(); - $this->memoryCache = new VariationCache($this->requestStack, new MemoryBackend(), $this->cacheContextsManager); - $custom_cache = new VariationCache($this->requestStack, new MemoryBackend(), $this->cacheContextsManager); + $this->memoryCache = new VariationCache($this->requestStack, new MemoryBackend(new Time($this->requestStack)), $this->cacheContextsManager); + $custom_cache = new VariationCache($this->requestStack, new MemoryBackend(new Time($this->requestStack)), $this->cacheContextsManager); $this->cacheFactory->expects($this->atLeastOnce()) ->method('get') diff --git a/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php b/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php index abc05d1cba4c..59a66b53bd87 100644 --- a/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php +++ b/core/tests/Drupal/Tests/Core/Render/RendererTestBase.php @@ -4,6 +4,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; @@ -222,7 +223,7 @@ protected function setUpUnusedCache() { * Sets up a memory-based render cache back-end. */ protected function setupMemoryCache() { - $this->memoryCache = $this->memoryCache ?: new VariationCache($this->requestStack, new MemoryBackend(), $this->cacheContextsManager); + $this->memoryCache = $this->memoryCache ?: new VariationCache($this->requestStack, new MemoryBackend(new Time($this->requestStack)), $this->cacheContextsManager); $this->cacheFactory->expects($this->atLeastOnce()) ->method('get') diff --git a/core/tests/Drupal/Tests/Core/Session/UserSessionTest.php b/core/tests/Drupal/Tests/Core/Session/UserSessionTest.php index bc8965dc5905..fdf72aea1083 100644 --- a/core/tests/Drupal/Tests/Core/Session/UserSessionTest.php +++ b/core/tests/Drupal/Tests/Core/Session/UserSessionTest.php @@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Session; +use Drupal\Component\Datetime\Time; use Drupal\Core\Cache\MemoryCache\MemoryCache; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Core\Session\PermissionChecker; @@ -98,7 +99,7 @@ protected function setUp(): void { ]); $role_storage = $this->getMockBuilder('Drupal\user\RoleStorage') - ->setConstructorArgs(['role', new MemoryCache()]) + ->setConstructorArgs(['role', new MemoryCache(new Time())]) ->disableOriginalConstructor() ->onlyMethods(['loadMultiple']) ->getMock(); -- GitLab