Coverage index

src/Plugin/views/field/Exits.php

Lines: 69.70%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Plugin\views\field;
6
7
use Drupal\Core\Form\FormStateInterface;
8
use Drupal\views\Attribute\ViewsField;
9
use Drupal\views\Plugin\views\field\FieldPluginBase;
10
11
/**
12
 * Counts visits whose last page view is this one.
13
 *
14
 * Matomo's exits metric is one per visit that ended on the page.
15
 */
16
#[ViewsField("visitors_exit")]
17
class Exits extends FieldPluginBase {
18
19
  /**
20
   * {@inheritdoc}
21
   */
22
  protected function defineOptions() {
2311
    $options = parent::defineOptions();
2411
    $options['hide_zero'] = ['default' => FALSE];
2511
    return $options;
26
  }
27
28
  /**
29
   * {@inheritdoc}
30
   */
31
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
320
    parent::buildOptionsForm($form, $form_state);
330
    $form['hide_zero'] = [
340
      '#type' => 'checkbox',
350
      '#title' => $this->t('Hide groups with no exits'),
360
      '#description' => $this->t(
370
        'Omit rows that were never the last page in a visit.'
380
      ),
390
      '#default_value' => !empty($this->options['hide_zero']),
400
    ];
41
  }
42
43
  /**
44
   * {@inheritdoc}
45
   */
46
  public function query() {
473
    $this->ensureMyTable();
483
    $formula = $this->exitCase();
493
    $params = [];
50
51
    // Sum the 0/1 flag when the display groups rows.
523
    if ($this->view->display_handler->useGroupBy()) {
531
      $params['function'] = !empty($this->options['group_type']) && $this->options['group_type'] != 'group'
541
        ? $this->options['group_type']
551
        : 'sum';
561
      $params['orderby'] = FALSE;
571
      $params['no_group'] = TRUE;
58
    }
59
603
    $alias = $this->tableAlias . '__exit';
613
    $this->field_alias = $this->query->addField(NULL, $formula, $alias, $params);
62
633
    if (!empty($this->options['hide_zero'])) {
641
      $this->query->addHavingExpression(0, 'SUM(' . $formula . ') > 0');
65
    }
66
  }
67
68
  /**
69
   * {@inheritdoc}
70
   */
71
  public function usesGroupBy() {
721
    return FALSE;
73
  }
74
75
  /**
76
   * SQL that is 1 when this page view is the visit exit.
77
   */
78
  protected function exitCase(): string {
793
    $event = $this->tableAlias;
803
    $visit = $this->visitAlias();
813
    return "CASE WHEN {$event}.id = {$visit}.exit THEN 1 ELSE 0 END";
82
  }
83
84
  /**
85
   * Alias of the visit table, which stores the exit event id.
86
   */
87
  protected function visitAlias(): string {
883
    $storage = $this->view->storage ?? NULL;
893
    if ($storage) {
903
      return (string) $storage->get('base_table');
91
    }
920
    return 'visitors_visit';
93
  }
94
95
}