Coverage index

src/Plugin/views/field/MediaRate.php

Lines: 82.14%

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
 * 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() {
2511
    $options = parent::defineOptions();
2611
    $options['numerator'] = ['default' => 'play_count'];
2711
    $options['denominator'] = ['default' => 'id'];
2811
    $options['denominator_function'] = ['default' => 'count'];
2911
    return $options;
30
  }
31
32
  /**
33
   * {@inheritdoc}
34
   */
35
  public function query() {
362
    $this->ensureMyTable();
372
    $numerator = (string) $this->options['numerator'];
382
    $denominator = (string) $this->options['denominator'];
392
    if (!in_array($numerator, self::COLUMNS, TRUE) || !in_array($denominator, self::COLUMNS, TRUE)) {
400
      return;
41
    }
42
432
    $alias = $this->tableAlias . '__' . $numerator . '_' . $denominator;
442
    foreach ($this->query->fields as $field_info) {
452
      if (!empty($field_info['alias']) && $field_info['alias'] === $alias) {
460
        $this->field_alias = $alias;
470
        return;
48
      }
49
    }
50
512
    $function = $this->options['denominator_function'] === 'sum' ? 'SUM' : 'COUNT';
522
    $table = $this->tableAlias;
53
    // Views wraps the expression in SUM(). The wrapper's closing
54
    // parenthesis closes NULLIF().
552
    $expression = "{$table}.{$numerator}) / NULLIF({$function}({$table}.{$denominator}), 0";
562
    $this->field_alias = $this->query->addField(NULL, $expression, $alias, [
572
      'alias' => $alias,
582
      'aggregate' => TRUE,
592
      'function' => 'sum',
602
    ]);
61
  }
62
63
  /**
64
   * {@inheritdoc}
65
   */
66
  public function render($values) {
671
    $value = $this->getValue($values);
681
    if ($value === NULL || $value === '') {
690
      return '';
70
    }
711
    return number_format((float) $value * 100, 0) . '%';
72
  }
73
74
  /**
75
   * {@inheritdoc}
76
   */
77
  public function usesGroupBy() {
780
    return FALSE;
79
  }
80
81
}