Coverage index

src/Plugin/views/field/ExitRate.php

Lines: 96.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
 * Exit rate: visits that ended on this page, divided by visits to it.
12
 */
13
#[ViewsField("visitors_exit_rate")]
14
class ExitRate extends FieldPluginBase {
15
16
  /**
17
   * {@inheritdoc}
18
   */
19
  public function query() {
204
    $this->ensureMyTable();
21
224
    $alias = $this->tableAlias . '__exit_rate';
234
    foreach ($this->query->fields as $field_info) {
244
      if (!empty($field_info['alias']) && $field_info['alias'] === $alias) {
251
        $this->field_alias = $alias;
261
        return;
27
      }
28
    }
29
30
    // Views wraps this expression in SUM(), which closes on the CASE.
314
    $expression = $this->exitCase() . ") / COUNT(DISTINCT " . $this->visitAlias() . ".id";
324
    $params = [
334
      'alias' => $alias,
344
      'aggregate' => TRUE,
354
      'function' => 'sum',
364
    ];
374
    $this->field_alias = $this->query->addField(NULL, $expression, $alias, $params);
38
  }
39
40
  /**
41
   * {@inheritdoc}
42
   */
43
  public function render($values) {
443
    $value = $this->getValue($values);
453
    if ($value === NULL || $value === '') {
461
      return '';
47
    }
483
    return number_format((float) $value * 100, 0) . '%';
49
  }
50
51
  /**
52
   * {@inheritdoc}
53
   */
54
  public function usesGroupBy() {
551
    return FALSE;
56
  }
57
58
  /**
59
   * SQL that is 1 when this page view is the visit exit.
60
   */
61
  protected function exitCase(): string {
624
    $event = $this->tableAlias;
634
    $visit = $this->visitAlias();
644
    return "CASE WHEN {$event}.id = {$visit}.exit THEN 1 ELSE 0 END";
65
  }
66
67
  /**
68
   * Alias of the visit table, which stores the exit event id.
69
   */
70
  protected function visitAlias(): string {
714
    $storage = $this->view->storage ?? NULL;
724
    if ($storage) {
734
      return (string) $storage->get('base_table');
74
    }
750
    return 'visitors_visit';
76
  }
77
78
}