You are here

public function DateRangeFormatterRangeFormatter::viewElements in Date range formatter 8.3

Same name and namespace in other branches
  1. 9.0.x src/Plugin/Field/FieldFormatter/DateRangeFormatterRangeFormatter.php \Drupal\date_range_formatter\Plugin\Field\FieldFormatter\DateRangeFormatterRangeFormatter::viewElements()

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides DateTimeRangeTrait::viewElements

File

src/Plugin/Field/FieldFormatter/DateRangeFormatterRangeFormatter.php, line 46

Class

DateRangeFormatterRangeFormatter
Plugin implementation of the 'Custom' formatter for 'daterange' fields.

Namespace

Drupal\date_range_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($items as $delta => $item) {
    if (!empty($item->start_date) && !empty($item->end_date)) {

      /** @var \Drupal\Core\Datetime\DrupalDateTime $start_date */
      $start_date = $item->start_date
        ->getTimestamp();

      /** @var \Drupal\Core\Datetime\DrupalDateTime $end_date */
      $end_date = $item->end_date
        ->getTimestamp();
      if ($start_date !== $end_date) {
        $format = $this
          ->getSetting('several_years');
        if (date('Y', $start_date) === date('Y', $end_date)) {
          $format = $this
            ->getSetting('several_months');
        }
        if (date('m.Y', $start_date) === date('m.Y', $end_date)) {
          $format = $this
            ->getSetting('one_month');
        }
        if (date('d.m.Y', $start_date) === date('d.m.Y', $end_date)) {
          $format = $this
            ->getSetting('one_day');
        }
        $date_str = format_date($start_date, 'custom', preg_replace('/\\{([a-zA-Z])\\}/', '{\\\\$1}', t($format)));
        $matches = array();
        if (preg_match_all('/\\{([a-zA-Z])\\}/', $date_str, $matches)) {
          foreach ($matches[1] as $match) {
            $date_str = preg_replace('/\\{' . $match . '\\}/', format_date($end_date, 'custom', $match), $date_str);
          }
        }
        $elements[$delta] = [
          '#markup' => '<span class="date-display-range">' . $date_str . '</span>',
        ];
      }
      else {
        $elements[$delta] = [
          '#markup' => format_date($start_date, 'custom', t($this
            ->getSetting('one_day'))),
        ];
      }
    }
  }
  return $elements;
}