diff --git a/core/lib/Drupal/Core/Datetime/FormattedDateDiff.php b/core/lib/Drupal/Core/Datetime/FormattedDateDiff.php index 07bb83638b1549f4aac6dd3d9c8c6b4be9a1eac0..266022be83ed0149958d5761bf95c0f6eed86a80 100644 --- a/core/lib/Drupal/Core/Datetime/FormattedDateDiff.php +++ b/core/lib/Drupal/Core/Datetime/FormattedDateDiff.php @@ -51,10 +51,23 @@ public function getString() { } /** + * {@inheritdoc} + */ + public function getCacheMaxAge() { + return $this->maxAge; + } + + /** + * The maximum age for which this object may be cached. + * * @return int + * The maximum time in seconds that this object may be cached. + * + * @deprecated in Drupal 8.1.9 and will be removed before Drupal 9.0.0. Use + * \Drupal\Core\Datetime\FormattedDateDiff::getCacheMaxAge() instead. */ public function getMaxAge() { - return $this->maxAge; + return $this->getCacheMaxAge(); } /** diff --git a/core/tests/Drupal/Tests/Core/Datetime/DateTest.php b/core/tests/Drupal/Tests/Core/Datetime/DateTest.php index 238b5c88e3e8d44e806211374242d20c4a452daa..edf6d714e798c5ac8f4c3b270874481db1b29765 100644 --- a/core/tests/Drupal/Tests/Core/Datetime/DateTest.php +++ b/core/tests/Drupal/Tests/Core/Datetime/DateTest.php @@ -2,6 +2,7 @@ namespace Drupal\Tests\Core\Datetime; +use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Datetime\DateFormatter; use Drupal\Core\Datetime\FormattedDateDiff; use Drupal\Core\DependencyInjection\ContainerBuilder; @@ -392,6 +393,38 @@ public function providerTestFormatDiff() { return $data; } + /** + * Tests FormattedDateDiff. + * + * @covers \Drupal\Core\Datetime\FormattedDateDiff::toRenderable + * @covers \Drupal\Core\Datetime\FormattedDateDiff::getString + * @covers \Drupal\Core\Datetime\FormattedDateDiff::getCacheMaxAge + */ + public function testFormattedDateDiff() { + $string = '10 minutes'; + $max_age = 60; + $object = new FormattedDateDiff($string, $max_age); + + // Test conversion to a render array. + $expected = [ + '#markup' => $string, + '#cache' => [ + 'max-age' => $max_age, + ], + ]; + $this->assertArrayEquals($expected, $object->toRenderable()); + + // Test retrieving the formatted time difference string. + $this->assertEquals($string, $object->getString()); + + // Test applying cacheability data to an existing build. + $build = []; + CacheableMetadata::createFromObject($object)->applyTo($build); + $this->assertEquals($max_age, $build['#cache']['max-age']); + // Test the BC layer. + $this->assertSame($object->getCacheMaxAge(), $object->getMaxAge()); + } + /** * Creates a UNIX timestamp given a date and time string in the format * year-month-day hour:minute:seconds (e.g. 2013-12-11 10:09:08).