Coverage index

src/Plugin/views/field/VisitorsDayWeek.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Plugin\views\field;
4
5
use Drupal\Core\Cache\CacheableMetadata;
6
use Drupal\views\Attribute\ViewsField;
7
8
/**
9
 * Field handler to display the day of the week of the visit.
10
 *
11
 * @ingroup views_field_handlers
12
 */
13
#[ViewsField("visitors_day_of_week")]
14
final class VisitorsDayWeek extends VisitorsTimestamp {
15
16
  /**
17
   * {@inheritdoc}
18
   */
19
  protected $format = '%w';
20
21
  /**
22
   * {@inheritdoc}
23
   */
24
  public function render($values) {
25
    // Default to Sunday (0)
262
    $first_day = $this->configFactory->get('system.date')->get('first_day') ?? 0;
27
282
    $weekdays = [];
292
    $weekdays[((0 + 7 - $first_day) % 7)] = $this->t('Sunday');
302
    $weekdays[((1 + 7 - $first_day) % 7)] = $this->t('Monday');
312
    $weekdays[((2 + 7 - $first_day) % 7)] = $this->t('Tuesday');
322
    $weekdays[((3 + 7 - $first_day) % 7)] = $this->t('Wednesday');
332
    $weekdays[((4 + 7 - $first_day) % 7)] = $this->t('Thursday');
342
    $weekdays[((5 + 7 - $first_day) % 7)] = $this->t('Friday');
352
    $weekdays[((6 + 7 - $first_day) % 7)] = $this->t('Saturday');
36
372
    $value = (int) $this->getValue($values);
38
39
    // $output = $weekdays[$value];
402
    $output = [
412
      '#markup' => $weekdays[$value],
422
    ];
43
    // Add cache metadata.
442
    $cache_metadata = new CacheableMetadata();
452
    $cache_metadata->addCacheTags(['config:system.date']);
462
    $cache_metadata->applyTo($output);
47
482
    return $output;
49
  }
50
51
  /**
52
   * {@inheritdoc}
53
   */
54
  public function query() {
552
    $this->ensureMyTable();
56
572
    $params = $this->options['group_type'] != 'group' ? ['function' => $this->options['group_type']] : [];
58
    /** @var \Drupal\views\Plugin\views\query\Sql $query */
592
    $query = $this->query;
60
61
    // Default to Sunday (0)
622
    $system_date = $this->configFactory->get('system.date');
632
    $first_day = $system_date->get('first_day') ?? 0;
64
652
    $timezone_location = $system_date->get('timezone.default');
66
672
    $timezone = new \DateTimeZone($timezone_location);
682
    $offset = $timezone->getOffset(new \DateTime());
69
702
    $field = $query->getDateField("$this->tableAlias.$this->realField", FALSE, FALSE);
712
    $query->setFieldTimezoneOffset($field, $offset);
722
    $formula = $query->getDateFormat($field, $this->getFormat(), FALSE);
732
    $sorted_expression = $formula;
742
    if ($first_day != 0) {
751
      $sorted_expression = "(($formula + 7 - $first_day) % 7)";
76
    }
77
782
    $this->field_alias = $query->addField(NULL, $sorted_expression, $this->field, $params);
79
802
    $this->addAdditionalFields();
81
  }
82
83
}