Coverage index

src/Plugin/views/field/BounceRate.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Plugin\views\field;
6
7
use Drupal\views\Attribute\ViewsField;
8
use Drupal\views\Plugin\views\field\FieldPluginBase;
9
10
/**
11
 * Field handler to display bounce rate percentage.
12
 */
13
#[ViewsField("visitors_bounce_rate")]
14
class BounceRate extends FieldPluginBase {
15
16
  /**
17
   * {@inheritdoc}
18
   */
19
  public function query() {
203
    $this->ensureMyTable();
21
223
    $bounce_rate_alias = $this->tableAlias . '__bounce_rate';
23
24
    // Check if already added.
253
    foreach ($this->query->fields as $field_info) {
263
      if (!empty($field_info['alias']) && $field_info['alias'] === $bounce_rate_alias) {
271
        $this->field_alias = $bounce_rate_alias;
281
        return;
29
      }
30
    }
31
323
    $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.
353
    $params = [
363
      'alias' => $bounce_rate_alias,
373
      'aggregate' => TRUE,
383
      'function' => 'sum',
393
    ];
40
413
    $this->field_alias = $this->query->addField(NULL, $expression, $bounce_rate_alias, $params);
42
  }
43
44
  /**
45
   * {@inheritdoc}
46
   */
47
  public function render($values) {
488
    $value = $this->getValue($values);
49
508
    if ($value === NULL || $value === '') {
512
      return '';
52
    }
53
54
    // Format as percentage with 2 decimal places.
556
    return number_format((float) $value * 100, 0) . '%';
56
  }
57
58
  /**
59
   * {@inheritdoc}
60
   */
61
  public function usesGroupBy() {
621
    return FALSE;
63
  }
64
65
}