Coverage index

src/Plugin/views/field/RefererNameLink.php

Lines: 94.12%

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
 * Links a referrer name or keyword to its drill-down report.
15
 *
16
 * An empty value uses empty_label and the argument "not-defined".
17
 */
18
#[ViewsField('visitors_referer_name_link')]
19
final class RefererNameLink extends FieldPluginBase {
20
21
  /**
22
   * {@inheritdoc}
23
   */
24
  protected function defineOptions() {
2511
    $options = parent::defineOptions();
2611
    $options['route'] = ['default' => ''];
2711
    $options['parameter'] = ['default' => 'referer_name'];
2811
    $options['empty_label'] = ['default' => ''];
2911
    return $options;
30
  }
31
32
  /**
33
   * {@inheritdoc}
34
   */
35
  public function render(ResultRow $values) {
361
    $raw = $this->getValue($values);
371
    $value = is_scalar($raw) ? trim((string) $raw) : '';
381
    $label = $value;
391
    if ($value === '' && $this->options['empty_label'] !== '') {
401
      $label = $this->options['empty_label'];
411
      $value = 'not-defined';
42
    }
43
441
    $route = (string) ($this->options['route'] ?? '');
451
    if ($route === '' || $value === '') {
460
      return $label;
47
    }
48
491
    $parameter = (string) ($this->options['parameter'] ?? 'referer_name');
501
    $url = Url::fromRoute($route, [$parameter => $value]);
511
    return Link::fromTextAndUrl($label, $url)->toString();
52
  }
53
54
}