You are here

class Dates in Bamboo Twig 8

Provides a 'Dates' Twig Extensions.

Hierarchy

  • class \Drupal\bamboo_twig\TwigExtension\Dates extends \Drupal\bamboo_twig\TwigExtension\Twig_Extension

Expanded class hierarchy of Dates

1 string reference to 'Dates'
bamboo_twig.services.yml in ./bamboo_twig.services.yml
bamboo_twig.services.yml
1 service uses Dates
bamboo_twig.twig.dates in ./bamboo_twig.services.yml
Drupal\bamboo_twig\TwigExtension\Dates

File

src/TwigExtension/Dates.php, line 10

Namespace

Drupal\bamboo_twig\TwigExtension
View source
class Dates extends \Twig_Extension {

  /**
   * Formats a date, using a date type or a custom date format string.
   *
   * @var Drupal\Core\Datetime\DateFormatter
   */
  private $dateFormatter;

  /**
   * TwigExtension constructor.
   */
  public function __construct(DateFormatter $dateFormatter) {
    $this->dateFormatter = $dateFormatter;
  }

  /**
   * List of all Twig functions.
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('format_date_i18n', [
        $this,
        'dateFormati18n',
      ]),
    ];
  }

  /**
   * Unique identifier for this Twig extension.
   */
  public function getName() {
    return 'bamboo_twig.twig.dates';
  }

  /**
   * Render a custom date format with Twig.
   *
   * Use the internal helper "format_date" to render the date
   * using the current language for texts.
   *
   * @param mixed $date
   *   A valide DrupalDateTime or DateTime object,
   *   a Y-m-d string or an integer timestamp.
   * @param string $format
   *   A format string.
   *
   * @return string|null
   *   Formatted given date corresponding of given format date.
   */
  public function dateFormati18n($date, $format = 'Y-m-d') {
    if (is_a($date, 'Drupal\\Core\\Datetime\\DrupalDateTime') || is_a($date, 'DateTime')) {
      $timestmap = $date
        ->getTimestamp();
    }
    elseif (\DateTime::createFromFormat('Y-m-d', $date)) {
      $timestmap = strtotime($date);
    }
    else {
      $timestmap = $date;
    }

    // Check the $date is a valid timestmap.
    try {
      $date_format = new \DateTime('@' . $timestmap);
      $timestmap = $date_format
        ->getTimestamp();
    } catch (\Exception $e) {
      return NULL;
    }
    return $this->dateFormatter
      ->format($timestmap, "custom", $format);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Dates::$dateFormatter private property Formats a date, using a date type or a custom date format string.
Dates::dateFormati18n public function Render a custom date format with Twig.
Dates::getFilters public function List of all Twig functions.
Dates::getName public function Unique identifier for this Twig extension.
Dates::__construct public function TwigExtension constructor.