Coverage index

src/Plugin/views/field/Bounce.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Plugin\views\field;
4
5
use Drupal\views\Attribute\ViewsField;
6
use Drupal\views\Plugin\views\field\FieldPluginBase;
7
8
/**
9
 * Field handler to display bounce rate.
10
 */
11
#[ViewsField("visitors_bounce")]
12
class Bounce extends FieldPluginBase {
13
14
  /**
15
   * The formula for this handler.
16
   *
17
   * @var string|null
18
   */
19
  public $formula = "CASE WHEN ***table***.total_events = 1 THEN 1 ELSE 0 END";
20
21
  /**
22
   * Gets the prepared formula.
23
   *
24
   * @return string
25
   *   The formula with the table placeholder replaced.
26
   */
27
  public function getFormula() {
286
    return str_replace('***table***', $this->tableAlias, $this->formula);
29
  }
30
31
  /**
32
   * {@inheritdoc}
33
   */
34
  public function query() {
355
    $this->ensureMyTable();
36
37
    // Get the formula and add it as a field.
385
    $formula = $this->getFormula();
39
40
    // Add the field with aggregation support.
415
    $params = [];
42
43
    // Always set a function for aggregation when grouping is enabled.
445
    if ($this->view->display_handler->useGroupBy()) {
453
      $params['function'] = !empty($this->options['group_type']) && $this->options['group_type'] != 'group'
462
        ? $this->options['group_type']
472
        : 'sum';
48
493
      $params['orderby'] = FALSE;
503
      $params['no_group'] = TRUE;
51
    }
52
53
    // Use addField with NULL table to indicate this is an expression/formula.
54
    // This allows Views to properly apply aggregation functions to
55
    // the expression.
565
    $this->field_alias = $this->query->addField(NULL, $formula, $this->tableAlias . '__bounce', $params);
57
  }
58
59
  /**
60
   * {@inheritdoc}
61
   */
62
  public function usesGroupBy() {
631
    return FALSE;
64
  }
65
66
}