You are here

public function Countdown::build in Countdown 8

Implements a block render.

Overrides BlockPluginInterface::build

File

src/Plugin/Block/countdown.php, line 24

Class

Countdown
Provides a 'Countdown' Block.

Namespace

Drupal\countdown\Plugin\Block

Code

public function build() {
  $config = $this
    ->getConfiguration();
  $time = time();
  $event_name = isset($config['event_name']) ? $config['event_name'] : '';
  $url = isset($config['url']) ? $config['url'] : '';
  if ($url != "") {
    if (UrlHelper::isExternal($url)) {
      $event_name = Link::fromTextAndUrl($event_name, Url::fromUri($url, []))
        ->toString();
    }
    else {
      if ($url == "<front>") {
        $url = "/";
      }
      $event_name = Link::fromTextAndUrl($event_name, Url::fromUri('internal:/' . ltrim($url, '/'), []))
        ->toString();
    }
  }
  $accuracy = isset($config['accuracy']) ? $config['accuracy'] : '';
  $countdown_timestamp = isset($config['timestamp']) ? $config['timestamp'] : $time;
  $difference = $countdown_timestamp - $time;
  if ($difference < 0) {
    $passed = 1;
    $difference = abs($difference);
  }
  else {
    $passed = 0;
  }
  if ($passed) {
    $event_name = $this
      ->t(' since @event_name.', [
      '@event_name' => $event_name,
    ]);
  }
  else {
    $event_name = $this
      ->t(' until @event_name.', [
      '@event_name' => $event_name,
    ]);
  }
  $days_left = floor($difference / 60 / 60 / 24);
  $hrs_left = floor(($difference - $days_left * 60 * 60 * 24) / 60 / 60);
  $min_left = floor(($difference - $days_left * 60 * 60 * 24 - $hrs_left * 60 * 60) / 60);
  $secs_left = floor($difference - $days_left * 60 * 60 * 24 - $hrs_left * 60 * 60 - $min_left * 60);
  $days_left = $this
    ->formatPlural($days_left, '1 day', '@count days');
  if ($accuracy == 'h' || $accuracy == 'm' || $accuracy == 's') {
    $hrs_left = $this
      ->formatPlural($hrs_left, ', 1 hour', ', @count hours');
  }
  if ($accuracy == 'm' || $accuracy == 's') {
    $min_left = $this
      ->formatPlural($min_left, ', 1 minute', ', @count minutes');
  }
  if ($accuracy == 's') {
    $secs_left = $this
      ->formatPlural($secs_left, ', 1 second', ', @count seconds');
  }
  $build = [
    '#theme' => 'countdown',
    '#cache' => [
      'max-age' => 0,
    ],
    '#accuracy' => $accuracy,
    '#countdown_url' => $url,
    '#countdown_event_name' => $event_name,
    '#days_left' => $days_left,
    '#hrs_left' => $hrs_left,
    '#min_left' => $min_left,
    '#secs_left' => $secs_left,
    '#attached' => [
      'library' => 'countdown/countdownblock',
      'drupalSettings' => [
        'countdown' => [
          'countdownblock' => [
            'accuracy' => $accuracy,
          ],
        ],
      ],
    ],
  ];
  return $build;
}