FormattedDateDiff.php 1.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
<?php

namespace Drupal\Core\Datetime;

use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Cache\UnchangingCacheableDependencyTrait;
use Drupal\Core\Render\RenderableInterface;

/**
 * Contains a formatted time difference.
 */
class FormattedDateDiff implements RenderableInterface, CacheableDependencyInterface {

  use UnchangingCacheableDependencyTrait;

  /**
   * The actual formatted time difference.
   *
   * @var string
   */
  protected $string;

  /**
   * The maximum time in seconds that this string may be cached.
   *
   * Let's say the time difference is 1 day 1 hour. In this case, we can cache
   * it until now + 1 hour, so maxAge is 3600 seconds.
   *
   * @var int
   */
  protected $maxAge;

  /**
   * Creates a new FormattedDateDiff instance.
   *
   * @param string $string
   *   The formatted time difference.
   * @param int $max_age
   *   The maximum time in seconds that this string may be cached.
   */
  public function __construct($string, $max_age) {
    $this->string = $string;
    $this->maxAge = $max_age;
  }

  /**
   * @return string
   */
  public function getString() {
    return $this->string;
  }

  /**
54
   * @return int
55
   */
56
  public function getMaxAge() {
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    return $this->maxAge;
  }

  /**
   * {@inheritdoc}
   */
  public function toRenderable() {
    return [
      '#markup' => $this->string,
      '#cache' => [
        'max-age' => $this->maxAge,
      ],
    ];
  }

}