Lines: 83.87%
| Line | Hits | Source |
|---|---|---|
| 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 an event dimension to its drill-down report. | |
| 15 | * | |
| 16 | * View arguments listed in argument_parameters are added to the route. | |
| 17 | * A missing argument renders the value as plain text. | |
| 18 | */ | |
| 19 | #[ViewsField('visitors_event_dimension_link')] | |
| 20 | final class EventDimensionLink extends FieldPluginBase { | |
| 21 | ||
| 22 | /** | |
| 23 | * {@inheritdoc} | |
| 24 | */ | |
| 25 | protected function defineOptions() { | |
| 26 | 11 | $options = parent::defineOptions(); |
| 27 | 11 | $options['route'] = ['default' => '']; |
| 28 | 11 | $options['parameter'] = ['default' => '']; |
| 29 | 11 | $options['argument_parameters'] = ['default' => []]; |
| 30 | 11 | return $options; |
| 31 | } | |
| 32 | ||
| 33 | /** | |
| 34 | * {@inheritdoc} | |
| 35 | */ | |
| 36 | public function render(ResultRow $values) { | |
| 37 | 1 | $raw = $this->getValue($values); |
| 38 | 1 | $value = is_scalar($raw) ? trim((string) $raw) : ''; |
| 39 | 1 | if ($value === '') { |
| 40 | 0 | return ''; |
| 41 | } | |
| 42 | ||
| 43 | 1 | $route = (string) ($this->options['route'] ?? ''); |
| 44 | 1 | $parameter = (string) ($this->options['parameter'] ?? ''); |
| 45 | 1 | if ($route === '' || $parameter === '') { |
| 46 | 0 | return $value; |
| 47 | } | |
| 48 | ||
| 49 | 1 | $params = [$parameter => $value]; |
| 50 | 1 | $maps = $this->options['argument_parameters'] ?? []; |
| 51 | 1 | if (!is_array($maps)) { |
| 52 | 0 | return $value; |
| 53 | } | |
| 54 | 1 | foreach ($maps as $map) { |
| 55 | 1 | if (!is_array($map)) { |
| 56 | 0 | return $value; |
| 57 | } | |
| 58 | 1 | $argument_id = (string) ($map['argument'] ?? ''); |
| 59 | 1 | $route_parameter = (string) ($map['parameter'] ?? ''); |
| 60 | 1 | if ($argument_id === '' || $route_parameter === '') { |
| 61 | 0 | return $value; |
| 62 | } | |
| 63 | 1 | $argument = $this->view->argument[$argument_id] ?? NULL; |
| 64 | 1 | $arg_value = $argument ? $argument->getValue() : NULL; |
| 65 | 1 | if (!is_scalar($arg_value) || trim((string) $arg_value) === '') { |
| 66 | 1 | return $value; |
| 67 | } | |
| 68 | 1 | $params[$route_parameter] = trim((string) $arg_value); |
| 69 | } | |
| 70 | ||
| 71 | 1 | $url = Url::fromRoute($route, $params); |
| 72 | 1 | return Link::fromTextAndUrl($value, $url)->toString(); |
| 73 | } | |
| 74 | ||
| 75 | } |