Lines: 96.00%
| Line | Hits | Source |
|---|---|---|
| 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() { | |
| 20 | 4 | $this->ensureMyTable(); |
| 21 | ||
| 22 | 4 | $alias = $this->tableAlias . '__exit_rate'; |
| 23 | 4 | foreach ($this->query->fields as $field_info) { |
| 24 | 4 | if (!empty($field_info['alias']) && $field_info['alias'] === $alias) { |
| 25 | 1 | $this->field_alias = $alias; |
| 26 | 1 | return; |
| 27 | } | |
| 28 | } | |
| 29 | ||
| 30 | // Views wraps this expression in SUM(), which closes on the CASE. | |
| 31 | 4 | $expression = $this->exitCase() . ") / COUNT(DISTINCT " . $this->visitAlias() . ".id"; |
| 32 | 4 | $params = [ |
| 33 | 4 | 'alias' => $alias, |
| 34 | 4 | 'aggregate' => TRUE, |
| 35 | 4 | 'function' => 'sum', |
| 36 | 4 | ]; |
| 37 | 4 | $this->field_alias = $this->query->addField(NULL, $expression, $alias, $params); |
| 38 | } | |
| 39 | ||
| 40 | /** | |
| 41 | * {@inheritdoc} | |
| 42 | */ | |
| 43 | public function render($values) { | |
| 44 | 3 | $value = $this->getValue($values); |
| 45 | 3 | if ($value === NULL || $value === '') { |
| 46 | 1 | return ''; |
| 47 | } | |
| 48 | 3 | return number_format((float) $value * 100, 0) . '%'; |
| 49 | } | |
| 50 | ||
| 51 | /** | |
| 52 | * {@inheritdoc} | |
| 53 | */ | |
| 54 | public function usesGroupBy() { | |
| 55 | 1 | return FALSE; |
| 56 | } | |
| 57 | ||
| 58 | /** | |
| 59 | * SQL that is 1 when this page view is the visit exit. | |
| 60 | */ | |
| 61 | protected function exitCase(): string { | |
| 62 | 4 | $event = $this->tableAlias; |
| 63 | 4 | $visit = $this->visitAlias(); |
| 64 | 4 | 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 { | |
| 71 | 4 | $storage = $this->view->storage ?? NULL; |
| 72 | 4 | if ($storage) { |
| 73 | 4 | return (string) $storage->get('base_table'); |
| 74 | } | |
| 75 | 0 | return 'visitors_visit'; |
| 76 | } | |
| 77 | ||
| 78 | } |