Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
BounceRate
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
3 / 3
8
100.00% covered (success)
100.00%
1 / 1
 query
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 render
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 usesGroupBy
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Drupal\visitors\Plugin\views\field;
6
7use Drupal\views\Attribute\ViewsField;
8use Drupal\views\Plugin\views\field\FieldPluginBase;
9
10/**
11 * Field handler to display bounce rate percentage.
12 */
13#[ViewsField("visitors_bounce_rate")]
14class BounceRate extends FieldPluginBase {
15
16  /**
17   * {@inheritdoc}
18   */
19  public function query() {
20    $this->ensureMyTable();
21
22    $bounce_rate_alias = $this->tableAlias . '__bounce_rate';
23
24    // Check if already added.
25    foreach ($this->query->fields as $field_info) {
26      if (!empty($field_info['alias']) && $field_info['alias'] === $bounce_rate_alias) {
27        $this->field_alias = $bounce_rate_alias;
28        return;
29      }
30    }
31
32    $expression = "CASE WHEN {$this->tableAlias}.total_events = 1 THEN 1 ELSE 0 END) / COUNT(DISTINCT {$this->tableAlias}.id";
33
34    // Add as a raw expression, telling Views NOT to aggregate or group it.
35    $params = [
36      'alias' => $bounce_rate_alias,
37      'aggregate' => TRUE,
38      'function' => 'sum',
39    ];
40
41    $this->field_alias = $this->query->addField(NULL, $expression, $bounce_rate_alias, $params);
42  }
43
44  /**
45   * {@inheritdoc}
46   */
47  public function render($values) {
48    $value = $this->getValue($values);
49
50    if ($value === NULL || $value === '') {
51      return '';
52    }
53
54    // Format as percentage with 2 decimal places.
55    return number_format((float) $value * 100, 0) . '%';
56  }
57
58  /**
59   * {@inheritdoc}
60   */
61  public function usesGroupBy() {
62    return FALSE;
63  }
64
65}