Coverage index

src/Plugin/views/sort/NumberRange.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Plugin\views\sort;
4
5
use Drupal\Core\Form\FormStateInterface;
6
use Drupal\views\Attribute\ViewsSort;
7
use Drupal\views\Plugin\views\sort\SortPluginBase;
8
use Drupal\visitors\Service\SequenceService;
9
10
/**
11
 * Sort handler that uses defined number ranges instead of raw values.
12
 */
13
#[ViewsSort("visitors_number_range")]
14
class NumberRange extends SortPluginBase {
15
16
  /**
17
   * Gets the total count of configured ranges.
18
   *
19
   * @return int
20
   *   The total number of ranges.
21
   */
22
  public function getTotalRanges(): int {
2312
    $ranges_text = $this->options['ranges'];
2412
    $ranges = preg_split('/\r\n|\r|\n/', $ranges_text);
2512
    $ranges = array_map('trim', $ranges);
2612
    $ranges = array_filter($ranges, function ($range) {
2712
      return trim($range) !== '';
2812
    });
29
3012
    return count($ranges);
31
  }
32
33
  /**
34
   * {@inheritdoc}
35
   */
36
  public function defineOptions() {
3711
    $options = parent::defineOptions();
3811
    $options['ranges'] = ['default' => "0\n1\n2\n3\n4\n5\n6-7\n8-10\n11-14\n15-20\n21+"];
3911
    return $options;
40
  }
41
42
  /**
43
   * {@inheritdoc}
44
   */
45
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
461
    parent::buildOptionsForm($form, $form_state);
47
481
    $form['ranges'] = [
491
      '#type' => 'textarea',
501
      '#title' => $this->t('Number ranges'),
511
      '#description' => $this->t("Enter one range per line. Examples: <code>0</code>, <code>6-7</code>, <code>21+</code>. The sort order will follow the order you define here."),
521
      '#default_value' => $this->options['ranges'],
531
    ];
54
  }
55
56
  /**
57
   * {@inheritdoc}
58
   */
59
  public function query() {
60
    // Add the base field to the query.
617
    $this->ensureMyTable();
62
63
    // Check if the field already exists in the query.
647
    $existing_field_alias = $this->tableAlias . '_' . $this->realField . '__range';
65
66
    // Look through the query fields to see if our target field already exists.
677
    foreach ($this->query->fields as $field_info) {
686
      if (isset($field_info['alias']) && $field_info['alias'] === $existing_field_alias) {
69
        // Field already exists, use it for sorting.
702
        $this->query->addOrderBy(NULL, NULL, $this->options['order'], $existing_field_alias);
712
        return;
72
      }
73
    }
74
75
    // Field doesn't exist, create our own CASE expression.
765
    $field = "$this->tableAlias.$this->realField";
77
785
    $ranges_text = $this->options['ranges'];
795
    $ranges = preg_split('/\r\n|\r|\n/', $ranges_text);
805
    $ranges = array_map('trim', $ranges);
815
    $ranges = array_filter($ranges, function ($range) {
825
      return trim($range) !== '';
835
    });
84
855
    $case_sql = [];
86
    $i = 0;
875
    foreach ($ranges as $range) {
88
      // Range "X-Y".
894
      if (preg_match('/^(\d+)\-(\d+)$/', $range, $m)) {
903
        $case_sql[] = "WHEN $field BETWEEN {$m[1]} AND {$m[2]} THEN $i";
91
      }
92
      // Range "X+".
934
      elseif (preg_match('/^(\d+)\+$/', $range, $m)) {
943
        $case_sql[] = "WHEN $field >= {$m[1]} THEN $i";
95
      }
96
      // Exact number.
974
      elseif (is_numeric($range)) {
984
        $case_sql[] = "WHEN $field = {$range} THEN $i";
99
      }
100
    }
101
1025
    $case_expression = "CASE " . implode(' ', $case_sql) . " ELSE 9999 END";
103
104
    // Tell Views how to sort.
1055
    $this->query->addOrderBy(NULL, $case_expression, $this->options['order'], $existing_field_alias);
106
  }
107
108
  /**
109
   * {@inheritdoc}
110
   */
111
  public function postExecute(&$values) {
11210
    $values = SequenceService::integer($values, $this->tableAlias . '_' . $this->realField . '__range', $this->getTotalRanges());
113
  }
114
115
}