Lines: 82.14%
| 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 | * A media ratio: plays over impressions, or finishes over plays. | |
| 12 | */ | |
| 13 | #[ViewsField("visitors_media_rate")] | |
| 14 | class MediaRate extends FieldPluginBase { | |
| 15 | ||
| 16 | /** | |
| 17 | * Columns this handler is allowed to aggregate. | |
| 18 | */ | |
| 19 | private const COLUMNS = ['id', 'play_count', 'finish_count']; | |
| 20 | ||
| 21 | /** | |
| 22 | * {@inheritdoc} | |
| 23 | */ | |
| 24 | protected function defineOptions() { | |
| 25 | 11 | $options = parent::defineOptions(); |
| 26 | 11 | $options['numerator'] = ['default' => 'play_count']; |
| 27 | 11 | $options['denominator'] = ['default' => 'id']; |
| 28 | 11 | $options['denominator_function'] = ['default' => 'count']; |
| 29 | 11 | return $options; |
| 30 | } | |
| 31 | ||
| 32 | /** | |
| 33 | * {@inheritdoc} | |
| 34 | */ | |
| 35 | public function query() { | |
| 36 | 2 | $this->ensureMyTable(); |
| 37 | 2 | $numerator = (string) $this->options['numerator']; |
| 38 | 2 | $denominator = (string) $this->options['denominator']; |
| 39 | 2 | if (!in_array($numerator, self::COLUMNS, TRUE) || !in_array($denominator, self::COLUMNS, TRUE)) { |
| 40 | 0 | return; |
| 41 | } | |
| 42 | ||
| 43 | 2 | $alias = $this->tableAlias . '__' . $numerator . '_' . $denominator; |
| 44 | 2 | foreach ($this->query->fields as $field_info) { |
| 45 | 2 | if (!empty($field_info['alias']) && $field_info['alias'] === $alias) { |
| 46 | 0 | $this->field_alias = $alias; |
| 47 | 0 | return; |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 51 | 2 | $function = $this->options['denominator_function'] === 'sum' ? 'SUM' : 'COUNT'; |
| 52 | 2 | $table = $this->tableAlias; |
| 53 | // Views wraps the expression in SUM(). The wrapper's closing | |
| 54 | // parenthesis closes NULLIF(). | |
| 55 | 2 | $expression = "{$table}.{$numerator}) / NULLIF({$function}({$table}.{$denominator}), 0"; |
| 56 | 2 | $this->field_alias = $this->query->addField(NULL, $expression, $alias, [ |
| 57 | 2 | 'alias' => $alias, |
| 58 | 2 | 'aggregate' => TRUE, |
| 59 | 2 | 'function' => 'sum', |
| 60 | 2 | ]); |
| 61 | } | |
| 62 | ||
| 63 | /** | |
| 64 | * {@inheritdoc} | |
| 65 | */ | |
| 66 | public function render($values) { | |
| 67 | 1 | $value = $this->getValue($values); |
| 68 | 1 | if ($value === NULL || $value === '') { |
| 69 | 0 | return ''; |
| 70 | } | |
| 71 | 1 | return number_format((float) $value * 100, 0) . '%'; |
| 72 | } | |
| 73 | ||
| 74 | /** | |
| 75 | * {@inheritdoc} | |
| 76 | */ | |
| 77 | public function usesGroupBy() { | |
| 78 | 0 | return FALSE; |
| 79 | } | |
| 80 | ||
| 81 | } |