Coverage index

src/Plugin/views/field/RefererType.php

Lines: 96.97%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Plugin\views\field;
6
7
use Drupal\Core\Link;
8
use Drupal\Core\Url;
9
use Drupal\views\Attribute\ViewsField;
10
use Drupal\views\Plugin\views\field\FieldPluginBase;
11
use Drupal\views\ResultRow;
12
13
/**
14
 * Renders a visit referrer channel.
15
 *
16
 * When the link option is set, channels that have a report link to it.
17
 */
18
#[ViewsField("visitors_referer_type")]
19
final class RefererType extends FieldPluginBase {
20
21
  /**
22
   * Channel routes.
23
   *
24
   * Direct entry has no separate report.
25
   */
26
  private const ROUTES = [
27
    'search_engine' => 'visitors.search',
28
    'website' => 'visitors.websites',
29
    'social_network' => 'visitors.social',
30
    'ai_assistant' => 'visitors.ai',
31
    'campaign' => 'visitors.campaigns',
32
  ];
33
34
  /**
35
   * {@inheritdoc}
36
   */
37
  protected function defineOptions() {
3811
    $options = parent::defineOptions();
3911
    $options['link'] = ['default' => FALSE];
4011
    return $options;
41
  }
42
43
  /**
44
   * {@inheritdoc}
45
   */
46
  public function render(ResultRow $values) {
478
    $type = $this->getValue($values);
48
    switch ($type) {
498
      case 'direct':
503
        $value = $this->t('Direct Entry');
513
        break;
52
537
      case 'website':
542
        $value = $this->t('Website');
552
        break;
56
576
      case 'internal':
582
        $value = $this->t('Internal');
592
        break;
60
615
      case 'search_engine':
622
        $value = $this->t('Search Engine');
632
        break;
64
655
      case 'spam':
662
        $value = $this->t('Spam');
672
        break;
68
695
      case 'social_network':
702
        $value = $this->t('Social Network');
712
        break;
72
734
      case 'ai_assistant':
742
        $value = $this->t('AI Assistant');
752
        break;
76
774
      case 'campaign':
781
        $value = $this->t('Campaign');
791
        break;
80
81
      default:
823
        $value = $this->t('Unknown');
83
        break;
84
    }
85
868
    $route = self::ROUTES[$type] ?? NULL;
878
    if (empty($this->options['link']) || $route === NULL) {
888
      return $value;
89
    }
90
910
    return Link::fromTextAndUrl($value, Url::fromRoute($route));
92
  }
93
94
}