Coverage index

src/Plugin/views/field/VisitorsLanguage.php

Lines: 100.00%

LineHitsSource
1
<?php
2
3
namespace Drupal\visitors\Plugin\views\field;
4
5
use Drupal\Core\Form\FormStateInterface;
6
use Drupal\views\Attribute\ViewsField;
7
use Drupal\views\Plugin\views\field\FieldPluginBase;
8
use Drupal\views\ResultRow;
9
use Drupal\visitors\VisitorsLanguageInterface;
10
use Symfony\Component\DependencyInjection\ContainerInterface;
11
12
/**
13
 * Field handler to display the language of the visitors.
14
 *
15
 * @ingroup views_field_handlers
16
 */
17
#[ViewsField("visitors_language")]
18
final class VisitorsLanguage extends FieldPluginBase {
19
20
  /**
21
   * The language service.
22
   *
23
   * @var \Drupal\visitors\VisitorsLanguageInterface
24
   */
25
  protected $language;
26
27
  /**
28
   * Continent field.
29
   *
30
   * @param array $configuration
31
   *   The plugin configuration.
32
   * @param string $plugin_id
33
   *   The plugin ID.
34
   * @param mixed $plugin_definition
35
   *   The plugin definition.
36
   * @param \Drupal\visitors\VisitorsLanguageInterface $language
37
   *   The location service.
38
   */
39
  public function __construct(array $configuration, $plugin_id, $plugin_definition, VisitorsLanguageInterface $language) {
4011
    parent::__construct($configuration, $plugin_id, $plugin_definition);
41
4211
    $this->language = $language;
43
  }
44
45
  /**
46
   * {@inheritdoc}
47
   */
48
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
4911
    return new self(
5011
      $configuration,
5111
      $plugin_id,
5211
      $plugin_definition,
5311
      $container->get('visitors.language'),
5411
    );
55
  }
56
57
  /**
58
   * Define the available options.
59
   *
60
   * @return array
61
   *   The available options.
62
   */
63
  protected function defineOptions() {
6411
    $options = parent::defineOptions();
6511
    $options['code'] = ['default' => FALSE];
66
6711
    return $options;
68
  }
69
70
  /**
71
   * Provide the options form.
72
   */
73
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
74
751
    $form['code'] = [
761
      '#title' => $this->t('Show language code'),
771
      '#type' => 'checkbox',
781
      '#default_value' => $this->options['code'],
791
    ];
80
811
    parent::buildOptionsForm($form, $form_state);
82
  }
83
84
  /**
85
   * {@inheritdoc}
86
   */
87
  public function render(ResultRow $values) {
88
892
    $language_code = $this->getValue($values);
90
912
    $language = $this->language->getLanguageLabel($language_code);
92
932
    if ($this->options['code']) {
941
      $language = $language . ' (' . $language_code . ')';
95
    }
96
972
    return $language;
98
  }
99
100
}