FormattedDateDiff.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Drupal\Core\Datetime;
  3. use Drupal\Core\Cache\CacheableDependencyInterface;
  4. use Drupal\Core\Cache\UnchangingCacheableDependencyTrait;
  5. use Drupal\Core\Render\RenderableInterface;
  6. /**
  7. * Contains a formatted time difference.
  8. */
  9. class FormattedDateDiff implements RenderableInterface, CacheableDependencyInterface {
  10. use UnchangingCacheableDependencyTrait;
  11. /**
  12. * The actual formatted time difference.
  13. *
  14. * @var string
  15. */
  16. protected $string;
  17. /**
  18. * The maximum time in seconds that this string may be cached.
  19. *
  20. * Let's say the time difference is 1 day 1 hour. In this case, we can cache
  21. * it until now + 1 hour, so maxAge is 3600 seconds.
  22. *
  23. * @var int
  24. */
  25. protected $maxAge;
  26. /**
  27. * Creates a new FormattedDateDiff instance.
  28. *
  29. * @param string $string
  30. * The formatted time difference.
  31. * @param int $max_age
  32. * The maximum time in seconds that this string may be cached.
  33. */
  34. public function __construct($string, $max_age) {
  35. $this->string = $string;
  36. $this->maxAge = $max_age;
  37. }
  38. /**
  39. * @return string
  40. */
  41. public function getString() {
  42. return $this->string;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function getCacheMaxAge() {
  48. return $this->maxAge;
  49. }
  50. /**
  51. * The maximum age for which this object may be cached.
  52. *
  53. * @return int
  54. * The maximum time in seconds that this object may be cached.
  55. *
  56. * @deprecated in drupal:8.1.9 and is removed from drupal:9.0.0. Use
  57. * \Drupal\Core\Datetime\FormattedDateDiff::getCacheMaxAge() instead.
  58. *
  59. * @see https://www.drupal.org/node/2783545
  60. */
  61. public function getMaxAge() {
  62. @trigger_error(__NAMESPACE__ . '\FormattedDateDiff::getMaxAge() is deprecated in drupal:8.1.9 and is removed from drupal:9.0.0. Use \Drupal\Core\Datetime\FormattedDateDiff::getCacheMaxAge() instead. See https://www.drupal.org/node/2783545', E_USER_DEPRECATED);
  63. return $this->getCacheMaxAge();
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public function toRenderable() {
  69. return [
  70. '#markup' => $this->string,
  71. '#cache' => [
  72. 'max-age' => $this->maxAge,
  73. ],
  74. ];
  75. }
  76. }