FormattedDateDiff.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 will be removed before Drupal 9.0.0. Use
  57. * \Drupal\Core\Datetime\FormattedDateDiff::getCacheMaxAge() instead.
  58. */
  59. public function getMaxAge() {
  60. return $this->getCacheMaxAge();
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function toRenderable() {
  66. return [
  67. '#markup' => $this->string,
  68. '#cache' => [
  69. 'max-age' => $this->maxAge,
  70. ],
  71. ];
  72. }
  73. }