diff --git a/core/lib/Drupal/Core/Datetime/DrupalDateTime.php b/core/lib/Drupal/Core/Datetime/DrupalDateTime.php index ad2a89f08cf9fb6fe00bb1bb0091003504cfbd35..172331cf5f841aa40fb6f27a7cc03a5e56de0545 100644 --- a/core/lib/Drupal/Core/Datetime/DrupalDateTime.php +++ b/core/lib/Drupal/Core/Datetime/DrupalDateTime.php @@ -3,6 +3,7 @@ namespace Drupal\Core\Datetime; use Drupal\Component\Datetime\DateTimePlus; +use Drupal\Core\DependencyInjection\DependencySerializationTrait; use Drupal\Core\StringTranslation\StringTranslationTrait; /** @@ -21,6 +22,9 @@ class DrupalDateTime extends DateTimePlus { use StringTranslationTrait; + use DependencySerializationTrait { + __sleep as defaultSleep; + } /** * Formatted strings translation cache. @@ -52,7 +56,7 @@ class DrupalDateTime extends DateTimePlus { * * @var array */ - protected $formatTranslationCache; + protected $formatTranslationCache = []; /** * Constructs a date object. @@ -166,4 +170,11 @@ public function format($format, $settings = []) { return $value; } + /** + * {@inheritdoc} + */ + public function __sleep(): array { + return array_diff($this->defaultSleep(), ['formatTranslationCache']); + } + } diff --git a/core/tests/Drupal/Tests/Core/Datetime/DrupalDateTimeTest.php b/core/tests/Drupal/Tests/Core/Datetime/DrupalDateTimeTest.php index 53467b6d7895561a12b859bfcb1260e3168307b6..b523f4e0aaf92f50e7dfad7597dd9ac462dbd245 100644 --- a/core/tests/Drupal/Tests/Core/Datetime/DrupalDateTimeTest.php +++ b/core/tests/Drupal/Tests/Core/Datetime/DrupalDateTimeTest.php @@ -271,4 +271,23 @@ public function testRfc2822DateFormat() { } } + /** + * Test to avoid serialization of formatTranslationCache. + */ + public function testSleep(): void { + $tz = new \DateTimeZone(date_default_timezone_get()); + $date = new DrupalDateTime('now', $tz, ['langcode' => 'en']); + + // Override timestamp before serialize. + $date->setTimestamp(12345678); + + $vars = $date->__sleep(); + $this->assertContains('langcode', $vars); + $this->assertContains('dateTimeObject', $vars); + $this->assertNotContains('formatTranslationCache', $vars); + + $unserialized_date = unserialize(serialize($date)); + $this->assertSame(12345678, $unserialized_date->getTimestamp()); + } + }