Coverage index

src/Plugin/views/field/NumberRange.php

Lines: 78.19%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Plugin\views\field;
4
5
use Drupal\Core\Form\FormStateInterface;
6
use Drupal\views\Attribute\ViewsField;
7
use Drupal\views\Plugin\views\field\FieldPluginBase;
8
use Drupal\views\ResultRow;
9
10
/**
11
 * Field handler to display numeric values grouped into configured ranges.
12
 */
13
#[ViewsField("visitors_number_range")]
14
class NumberRange extends FieldPluginBase {
15
16
  /**
17
   * {@inheritdoc}
18
   */
19
  public function query() {
203
    $this->ensureMyTable();
21
    $suffix = '__range';
223
    $field = "$this->tableAlias.$this->realField";
23
243
    $ranges_text = $this->options['ranges'];
253
    $ranges = preg_split('/\r\n|\r|\n/', $ranges_text);
263
    $ranges = array_map('trim', $ranges);
273
    $ranges = array_filter($ranges, function ($range) {
283
      return trim($range) !== '';
293
    });
30
313
    if (empty($ranges)) {
322
      return parent::query();
33
    }
34
351
    $case_sql = [];
361
    foreach ($ranges as $i => $range) {
37
381
      $value = $i;
391
      $parsed_range = $this->parseTimeRange($range);
40
41
      // "X-Y" with or without time units.
421
      if (preg_match('/^(\d+(?:\.\d+)?)\-(\d+(?:\.\d+)?)$/', $range, $m)) {
431
        $start_seconds = $this->convertToSeconds($m[1], $parsed_range['start_unit']);
441
        $end_seconds = $this->convertToSeconds($m[2], $parsed_range['end_unit']);
451
        $case_sql[] = "WHEN $field BETWEEN $start_seconds AND $end_seconds THEN $value";
46
      }
47
      // "-X" format (0 to X).
481
      elseif (preg_match('/^\-(\d+(?:\.\d+)?)([mdwy]?)$/', $range, $m)) {
490
        $end_seconds = $this->convertToSeconds($m[1], $m[2] ?: NULL);
500
        $case_sql[] = "WHEN $field BETWEEN 0 AND $end_seconds THEN $value";
51
      }
52
      // "X+" with or without time units.
531
      elseif (preg_match('/^(\d+(?:\.\d+)?)\+$/', $range, $m)) {
541
        $seconds = $this->convertToSeconds($m[1], $parsed_range['start_unit']);
551
        $case_sql[] = "WHEN $field >= $seconds THEN $value";
56
      }
57
      // Exact number with or without time units.
581
      elseif (preg_match('/^(\d+(?:\.\d+)?)$/', $range, $m)) {
591
        $seconds = $this->convertToSeconds($m[1], $parsed_range['start_unit']);
601
        $case_sql[] = "WHEN $field = $seconds THEN $value";
61
      }
62
63
    }
641
    $max_value = count($ranges) + 1;
651
    $case_expression = "CASE " . implode(' ', $case_sql) . " ELSE $max_value END";
66
67
    // Tell Views to use this CASE expression as the field value.
681
    $this->field_alias = $this->query->addField(NULL, $case_expression, $this->tableAlias . '_' . $this->realField . $suffix);
69
  }
70
71
  /**
72
   * {@inheritdoc}
73
   */
74
  public function render(ResultRow $values) {
7514
    $label = $this->getValue($values);
76
77
    // Get display name.
7814
    $display_name = $this->options;
79
80
    // Always replace the index value with the range label.
8114
    $label = $this->getRangeLabel($label);
82
83
    // If time format is enabled, convert the range to time format.
8414
    if ($this->options['time_format']) {
857
      $time_unit = $this->options['time_unit'] ?? 'auto';
867
      if ($time_unit === 'auto') {
877
        $label = $this->formatTimeRange($label);
88
      }
89
      else {
900
        $label = $this->formatTimeRangeInUnit($label, $time_unit);
91
      }
92
    }
937
    elseif ($this->options['pluralize']) {
94
      // Example: pluralize with the word "item".
952
      return $this->formatPlural(
962
        $label,
972
        $this->options['singular_label'],
982
        $this->options['plural_label'],
992
      );
100
    }
101
10212
    return $label;
103
  }
104
105
  /**
106
   * Formats a range value as time when the range represents seconds.
107
   *
108
   * @param string $range
109
   *   The range value (e.g., "60", "3600", "86400").
110
   *
111
   * @return string
112
   *   The formatted time range (e.g., "1m", "1h", "1d").
113
   */
114
  protected function formatTimeRange(string $range): string {
115
    // Handle ranges like "60-120" or "3600+".
1167
    if (strpos($range, '-') !== FALSE) {
1174
      $parts = explode('-', $range);
1184
      $unit = NULL;
1194
      $start = $this->formatSeconds((int) $parts[0], $unit);
1204
      $end = $this->formatSeconds((int) $parts[1], $unit);
121
      // If start and end are less than 1 unit apart, return the integer with
122
      // the unit. Example: "1 day".
1234
      if (is_numeric($start) && is_numeric($end)
1244
          && abs($end - $start) < 1) {
1250
        $integer = is_int($end) ? $end : (is_int($start) ? $start : $end);
126
        // Only return "0" without units if both start and end are exactly 0.
1270
        if ($integer == 0 && $start == 0 && $end == 0) {
1280
          return '0';
129
        }
1300
        return $this->makePluralWith($integer, $unit);
131
      }
1324
      if ($start == 0 && $end == 1) {
1332
        return $this->makeSingle("$end", $unit);
134
      }
1353
      elseif ($start == 0) {
1360
        return $this->makeSingle("$start-$end", $unit);
137
      }
138
1393
      return $this->makePlural(floor($start) . "-$end", $unit);
140
    }
141
1423
    if (strpos($range, '+') !== FALSE) {
1431
      $seconds = (int) rtrim($range, '+');
1441
      $unit = NULL;
1451
      $time = $this->formatSeconds($seconds, $unit);
1461
      return $this->makePluralWith(floor($time), $unit ?? 'second', '+');
147
    }
148
149
    // Single value.
1502
    $seconds = (int) $range;
1512
    $unit = NULL;
1522
    $time = $this->formatSeconds($seconds, $unit);
1532
    return $this->makePluralWith($time, $unit ?? 'second');
154
  }
155
156
  /**
157
   * Formats a range value as time using a specific unit.
158
   *
159
   * @param string $range
160
   *   The range value (e.g., "60", "3600", "86400").
161
   * @param string $unit
162
   *   The time unit to use (second, minute, hour, day, week, year).
163
   *
164
   * @return string
165
   *   The formatted time range in the specified unit.
166
   */
167
  protected function formatTimeRangeInUnit(string $range, string $unit): string {
168
    // Handle "-X" format (0 to X).
1690
    if (preg_match('/^\-(\d+)$/', $range, $m)) {
1700
      $end = $this->formatSecondsInUnit((int) $m[1], $unit);
1710
      if ($end == 0) {
1720
        return '0';
173
      }
1740
      return $this->makePluralWith($end, $unit);
175
    }
176
177
    // Handle ranges like "60-120" or "3600+".
1780
    if (strpos($range, '-') !== FALSE) {
1790
      $parts = explode('-', $range);
1800
      $start = $this->formatSecondsInUnit((int) $parts[0], $unit);
1810
      $end = $this->formatSecondsInUnit((int) $parts[1], $unit);
182
183
      // If both start and end are 0, return just "0".
1840
      if ($start == 0 && $end == 0) {
1850
        return '0';
186
      }
187
188
      // If start and end are less than 1 unit apart, return the integer with
189
      // the unit. Example: "1 day".
1900
      if (is_numeric($start) && is_numeric($end)
1910
          && abs($end - $start) < 1) {
1920
        $integer = floor($start);
193
        // Only return "0" without units if both start and end are exactly 0.
1940
        if ($integer == 0 && $start == 0 && $end == 0) {
1950
          return '0';
196
        }
1970
        return $this->makePluralWith($integer, $unit);
198
      }
1990
      if ($start == 0 && $end == 1) {
2000
        return $this->makeSingle("$end", $unit);
201
      }
2020
      elseif ($start == 0) {
2030
        return $this->makePlural($end, $unit);
204
      }
205
2060
      return $this->makePlural(floor($start) . "-" . floor($end), $unit);
207
    }
208
2090
    if (strpos($range, '+') !== FALSE) {
2100
      $seconds = (int) rtrim($range, '+');
2110
      $time = $this->formatSecondsInUnit($seconds, $unit);
2120
      if ($time == 0) {
2130
        return '0+';
214
      }
2150
      return $this->makePluralWith(floor($time), $unit, '+');
216
    }
217
218
    // Single value.
2190
    $seconds = (int) $range;
2200
    $time = $this->formatSecondsInUnit($seconds, $unit);
2210
    if ($time == 0) {
2220
      return '0';
223
    }
2240
    return $this->makePluralWith($time, $unit);
225
  }
226
227
  /**
228
   * Formats seconds into a specific time unit.
229
   *
230
   * @param int $seconds
231
   *   The number of seconds.
232
   * @param string $unit
233
   *   The unit of time to format the seconds into.
234
   *
235
   * @return float
236
   *   The formatted time value as a float.
237
   */
238
  protected function formatSecondsInUnit(int $seconds, string $unit): float {
239
    switch ($unit) {
2400
      case 'second':
2410
        return (float) $seconds;
242
2430
      case 'minute':
2440
        return $seconds / 60;
245
2460
      case 'hour':
2470
        return $seconds / 3600;
248
2490
      case 'day':
2500
        return $seconds / 86400;
251
2520
      case 'week':
2530
        return $seconds / 604800;
254
2550
      case 'year':
2560
        return $seconds / 31536000;
257
258
      default:
2590
        return (float) $seconds;
260
    }
261
  }
262
263
  /**
264
   * Creates plural or singular form based on the time value.
265
   *
266
   * @param mixed $time
267
   *   The time value to format.
268
   * @param string $unit
269
   *   The time unit (second, minute, hour, etc.).
270
   * @param string $suffix
271
   *   Optional suffix to append to the time value.
272
   *
273
   * @return string
274
   *   The formatted time string with proper pluralization.
275
   */
276
  protected function makePluralWith($time, string $unit, $suffix = ''): string {
2773
    if ($time == 1) {
2783
      return $this->makeSingle($time, $unit, $suffix);
279
    }
2802
    return $this->makePlural($time, $unit, $suffix);
281
  }
282
283
  /**
284
   * Creates plural form of time units.
285
   *
286
   * @param mixed $time
287
   *   The time value to format.
288
   * @param string $unit
289
   *   The time unit (second, minute, hour, etc.).
290
   * @param string $suffix
291
   *   Optional suffix to append to the time value.
292
   *
293
   * @return string
294
   *   The formatted time string in plural form.
295
   */
296
  protected function makePlural($time, string $unit, $suffix = ''): string {
2975
    $plural = $this->t('Unknown unit');
298
    switch ($unit) {
2995
      case 'second':
3001
        $plural = $this->t('@time seconds', ['@time' => $time . $suffix]);
3011
        break;
302
3035
      case 'minute':
3045
        $plural = $this->t('@time minutes', ['@time' => $time . $suffix]);
3055
        break;
306
3073
      case 'hour':
3083
        $plural = $this->t('@time hours', ['@time' => $time . $suffix]);
3093
        break;
310
3113
      case 'day':
3123
        $plural = $this->t('@time days', ['@time' => $time . $suffix]);
3133
        break;
314
3151
      case 'week':
3161
        $plural = $this->t('@time weeks', ['@time' => $time . $suffix]);
3171
        break;
318
3191
      case 'month':
3201
        $plural = $this->t('@time months', ['@time' => $time . $suffix]);
3211
        break;
322
3231
      case 'year':
3241
        $plural = $this->t('@time years', ['@time' => $time . $suffix]);
325
        break;
326
    }
327
3285
    return $plural;
329
  }
330
331
  /**
332
   * Creates singular form of time units.
333
   *
334
   * @param mixed $time
335
   *   The time value to format.
336
   * @param string $unit
337
   *   The time unit (second, minute, hour, etc.).
338
   * @param string $suffix
339
   *   Optional suffix to append to the time value.
340
   *
341
   * @return string
342
   *   The formatted time string in singular form.
343
   */
344
  protected function makeSingle($time, string $unit, $suffix = ''): string {
3455
    $single = $this->t('Unknown unit');
346
    switch ($unit) {
3475
      case 'second':
3481
        $single = $this->t('@time second', ['@time' => $time . $suffix]);
3491
        break;
350
3515
      case 'minute':
3524
        $single = $this->t('@time minute', ['@time' => $time . $suffix]);
3534
        break;
354
3554
      case 'hour':
3564
        $single = $this->t('@time hour', ['@time' => $time . $suffix]);
3574
        break;
358
3593
      case 'day':
3603
        $single = $this->t('@time day', ['@time' => $time . $suffix]);
3613
        break;
362
3631
      case 'week':
3641
        $single = $this->t('@time week', ['@time' => $time . $suffix]);
3651
        break;
366
3671
      case 'month':
3681
        $single = $this->t('@time month', ['@time' => $time . $suffix]);
3691
        break;
370
3711
      case 'year':
3721
        $single = $this->t('@time year', ['@time' => $time . $suffix]);
373
        break;
374
    }
3755
    return $single;
376
  }
377
378
  /**
379
   * Formats seconds into human-readable time units.
380
   *
381
   * @param int $seconds
382
   *   The number of seconds.
383
   * @param string|null $unit
384
   *   The unit of time used to format the seconds.
385
   *
386
   * @return float
387
   *   The formatted time value as a float.
388
   */
389
  protected function formatSeconds(int $seconds, &$unit = NULL): float {
39013
    if ($seconds === 0) {
3915
      return (float) $seconds;
392
    }
393
394
    // If unit is already specified and not empty, format seconds as that unit.
39513
    if ($unit !== NULL && $unit !== '') {
396
      switch ($unit) {
3976
        case 'second':
3981
          return (float) $seconds;
399
4006
        case 'minute':
4015
          return $seconds / 60;
402
4035
        case 'hour':
4044
          return $seconds / 3600;
405
4065
        case 'day':
4074
          return $seconds / 86400;
408
4093
        case 'week':
4102
          return $seconds / 604800;
411
4123
        case 'month':
4132
          return $seconds / 2592000;
414
4153
        case 'year':
4162
          return $seconds / 31536000;
417
418
        default:
419
          // If unit is not recognized, fall through to automatic detection.
420
          break;
421
      }
422
    }
423
424
    // Automatic unit detection (existing logic)
42511
    if ($seconds < 60) {
4263
      $unit = 'second';
4273
      return (float) $seconds;
428
    }
429
43011
    if ($seconds < 3600) {
4319
      $unit = 'minute';
4329
      return $seconds / 60;
433
    }
434
4359
    if ($seconds < 86400) {
4368
      $unit = 'hour';
4378
      return $seconds / 3600;
438
    }
439
4408
    if ($seconds < 604800) {
4417
      $unit = 'day';
4427
      return $seconds / 86400;
443
    }
444
4454
    if ($seconds < 2592000) {
4463
      $unit = 'week';
4473
      return $seconds / 604800;
448
    }
449
4504
    if ($seconds < 31536000) {
4513
      $unit = 'month';
4523
      return $seconds / 2592000;
453
    }
454
4554
    $unit = 'year';
4564
    return $seconds / 31536000;
457
  }
458
459
  /**
460
   * Gets the range label for a given index value.
461
   *
462
   * @param string|int $index
463
   *   The index value (e.g., 1, 2, 3, 4, etc.).
464
   *
465
   * @return string
466
   *   The range label for the index.
467
   */
468
  protected function getRangeLabel($index): string {
46914
    $ranges_text = $this->options['ranges'];
47014
    $ranges = preg_split('/\r\n|\r|\n/', $ranges_text);
471
47214
    $i = 0;
47314
    foreach ($ranges as $range) {
47414
      $range = trim($range);
47514
      if ($range === '') {
476
        continue;
477
      }
478
47912
      if ($i === (int) $index) {
4808
        return $range;
481
      }
482
48312
      $i += 1;
484
    }
485
486
    // If no match found, return the original index value.
4877
    return (string) $index;
488
  }
489
490
  /**
491
   * Parses a time range string to extract time units.
492
   *
493
   * @param string $range
494
   *   The range string (e.g., "1m-2m", "5d+", "1w", "-60").
495
   *
496
   * @return array
497
   *   An array with 'start_unit' and 'end_unit' keys containing the time units.
498
   */
499
  protected function parseTimeRange(string $range): array {
5001
    $result = ['start_unit' => NULL, 'end_unit' => NULL];
501
502
    // Handle range format "X-Y" with units.
5031
    if (preg_match('/^(\d+(?:\.\d+)?)([mdwy]?)\-(\d+(?:\.\d+)?)([mdwy]?)$/', $range, $m)) {
5041
      $result['start_unit'] = $m[2] ?: NULL;
5051
      $result['end_unit'] = $m[4] ?: NULL;
506
    }
507
    // Handle "-X" format (0 to X) with units.
5081
    elseif (preg_match('/^\-(\d+(?:\.\d+)?)([mdwy]?)$/', $range, $m)) {
5090
      $result['start_unit'] = NULL;
5100
      $result['end_unit'] = $m[2] ?: NULL;
511
    }
512
    // Handle single value or "X+" format with units.
5131
    elseif (preg_match('/^(\d+(?:\.\d+)?)([mdwy]?)(\+?)$/', $range, $m)) {
5141
      $result['start_unit'] = $m[2] ?: NULL;
5151
      $result['end_unit'] = $m[2] ?: NULL;
516
    }
517
5181
    return $result;
519
  }
520
521
  /**
522
   * Converts a number with time unit to seconds.
523
   *
524
   * @param string $value
525
   *   The numeric value.
526
   * @param string|null $unit
527
   *   The time unit (m, d, w, y) or NULL for no unit.
528
   *
529
   * @return int
530
   *   The value converted to seconds.
531
   */
532
  protected function convertToSeconds(string $value, ?string $unit): int {
5331
    $num_value = (float) $value;
534
5351
    if ($unit === NULL) {
5361
      return (int) $num_value;
537
    }
538
539
    switch ($unit) {
540
      // Minutes.
5410
      case 'm':
5420
        return (int) ($num_value * 60);
543
544
      // Days.
5450
      case 'd':
5460
        return (int) ($num_value * 86400);
547
548
      // Weeks.
5490
      case 'w':
5500
        return (int) ($num_value * 604800);
551
552
      // Years.
5530
      case 'y':
5540
        return (int) ($num_value * 31536000);
555
556
      default:
5570
        return (int) $num_value;
558
    }
559
  }
560
561
  /**
562
   * {@inheritdoc}
563
   */
564
  protected function defineOptions() {
56511
    $options = parent::defineOptions();
56611
    $options['pluralize'] = ['default' => FALSE];
56711
    $options['singular_label'] = ['default' => '1 item'];
56811
    $options['plural_label'] = ['default' => '@count items'];
56911
    $options['ranges'] = ['default' => "0\n1\n2\n3\n4\n5\n6-7\n8-10\n11-14\n15-20\n21+"];
57011
    $options['time_format'] = ['default' => FALSE];
57111
    $options['time_unit'] = ['default' => 'auto'];
57211
    return $options;
573
  }
574
575
  /**
576
   * {@inheritdoc}
577
   */
578
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
5793
    parent::buildOptionsForm($form, $form_state);
580
5813
    $form['pluralize'] = [
5823
      '#type' => 'checkbox',
5833
      '#title' => $this->t('Enable pluralization'),
5843
      '#default_value' => $this->options['pluralize'],
5853
    ];
586
5873
    $form['singular_label'] = [
5883
      '#type' => 'textfield',
5893
      '#title' => $this->t('Singular label'),
5903
      '#default_value' => $this->options['singular_label'],
5913
      '#states' => [
5923
        'visible' => [
5933
          ':input[name="options[pluralize]"]' => ['checked' => TRUE],
5943
        ],
5953
      ],
5963
    ];
597
5983
    $form['plural_label'] = [
5993
      '#type' => 'textfield',
6003
      '#title' => $this->t('Plural label'),
6013
      '#default_value' => $this->options['plural_label'],
6023
      '#states' => [
6033
        'visible' => [
6043
          ':input[name="options[pluralize]"]' => ['checked' => TRUE],
6053
        ],
6063
      ],
6073
    ];
608
6093
    $form['ranges'] = [
6103
      '#type' => 'textarea',
6113
      '#title' => $this->t('Number ranges'),
6123
      '#description' => $this->t("Enter one range per line. Examples: <code>0</code>, <code>6-7</code>, <code>21+</code>."),
6133
      '#default_value' => $this->options['ranges'],
6143
    ];
615
6163
    $form['time_format'] = [
6173
      '#type' => 'checkbox',
6183
      '#title' => $this->t('Format ranges as time (e.g., 60s, 1h, 1d)'),
6193
      '#default_value' => $this->options['time_format'],
6203
    ];
621
6223
    $form['time_unit'] = [
6233
      '#type' => 'select',
6243
      '#title' => $this->t('Time unit'),
6253
      '#description' => $this->t('Choose the time unit for displaying all ranges. Auto will use the most appropriate unit for each range.'),
6263
      '#default_value' => $this->options['time_unit'] ?? 'auto',
6273
      '#options' => [
6283
        'auto' => $this->t('Auto'),
6293
        'second' => $this->t('Seconds'),
6303
        'minute' => $this->t('Minutes'),
6313
        'hour' => $this->t('Hours'),
6323
        'day' => $this->t('Days'),
6333
        'week' => $this->t('Weeks'),
6343
        'year' => $this->t('Years'),
6353
      ],
6363
      '#states' => [
6373
        'visible' => [
6383
          ':input[name="options[time_format]"]' => ['checked' => TRUE],
6393
        ],
6403
      ],
6413
    ];
642
  }
643
644
}