Lines: 100.00%
| Line | Hits | Source |
|---|---|---|
| 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() { | |
| 28 | 6 | return str_replace('***table***', $this->tableAlias, $this->formula); |
| 29 | } | |
| 30 | ||
| 31 | /** | |
| 32 | * {@inheritdoc} | |
| 33 | */ | |
| 34 | public function query() { | |
| 35 | 5 | $this->ensureMyTable(); |
| 36 | ||
| 37 | // Get the formula and add it as a field. | |
| 38 | 5 | $formula = $this->getFormula(); |
| 39 | ||
| 40 | // Add the field with aggregation support. | |
| 41 | 5 | $params = []; |
| 42 | ||
| 43 | // Always set a function for aggregation when grouping is enabled. | |
| 44 | 5 | if ($this->view->display_handler->useGroupBy()) { |
| 45 | 3 | $params['function'] = !empty($this->options['group_type']) && $this->options['group_type'] != 'group' |
| 46 | 2 | ? $this->options['group_type'] |
| 47 | 2 | : 'sum'; |
| 48 | ||
| 49 | 3 | $params['orderby'] = FALSE; |
| 50 | 3 | $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. | |
| 56 | 5 | $this->field_alias = $this->query->addField(NULL, $formula, $this->tableAlias . '__bounce', $params); |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * {@inheritdoc} | |
| 61 | */ | |
| 62 | public function usesGroupBy() { | |
| 63 | 1 | return FALSE; |
| 64 | } | |
| 65 | ||
| 66 | } |