You are here

public function TimeRangeFormatter::viewElements in Opigno calendar 8

Same name and namespace in other branches
  1. 3.x src/Plugin/Field/FieldFormatter/TimeRangeFormatter.php \Drupal\opigno_calendar\Plugin\Field\FieldFormatter\TimeRangeFormatter::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 DateRangeCustomFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/TimeRangeFormatter.php, line 37

Class

TimeRangeFormatter
Time range with optional date formatter.

Namespace

Drupal\opigno_calendar\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $separator = $this
    ->getSetting('separator');
  $split_format = $this
    ->getSplitFormat();
  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;

      /** @var \Drupal\Core\Datetime\DrupalDateTime $end_date */
      $end_date = $item->end_date;
      $formatted_start_date = $this->dateFormatter
        ->format($start_date
        ->getTimestamp(), 'custom', $split_format['date']);
      $formatted_end_date = $this->dateFormatter
        ->format($end_date
        ->getTimestamp(), 'custom', $split_format['date']);
      if ($formatted_start_date !== $formatted_end_date) {
        $elements[$delta] = [
          'start_date' => $this
            ->buildDate($start_date),
          'separator' => [
            '#plain_text' => ' ' . $separator . ' ',
          ],
          'end_date' => $this
            ->buildDate($end_date),
        ];
      }
      else {
        $date_format = $this
          ->getSetting('date_format');
        $this
          ->setSetting('date_format', $split_format['time']);
        $elements[$delta] = [
          'start_date' => $this
            ->buildDate($start_date),
          'separator' => [
            '#plain_text' => ' ' . $separator . ' ',
          ],
          'end_date' => $this
            ->buildDate($end_date),
        ];
        $this
          ->setSetting('date_format', $date_format);
      }
    }
  }
  return $elements;
}