summaryrefslogtreecommitdiffstats
path: root/core/modules/user/src/Plugin/views/filter/Roles.php
blob: 47adafb8b6986cba33ba2610fdf95e95235755e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

namespace Drupal\user\Plugin\views\filter;

use Drupal\user\RoleInterface;
use Drupal\user\RoleStorageInterface;
use Drupal\views\Plugin\views\filter\ManyToOne;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Filter handler for user roles.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("user_roles")
 */
class Roles extends ManyToOne {

  /**
   * The role storage.
   *
   * @var \Drupal\user\RoleStorageInterface
   */
  protected $roleStorage;

  /**
   * Constructs a Roles object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\user\RoleStorageInterface $role_storage
   *   The role storage.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RoleStorageInterface $role_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->roleStorage = $role_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.manager')->getStorage('user_role')
    );
  }

  public function getValueOptions() {
    $this->valueOptions = user_role_names(TRUE);
    unset($this->valueOptions[RoleInterface::AUTHENTICATED_ID]);
    return $this->valueOptions;

  }

  /**
   * Override empty and not empty operator labels to be clearer for user roles.
   */
  public function operators() {
    $operators = parent::operators();
    $operators['empty']['title'] = $this->t("Only has the 'authenticated user' role");
    $operators['not empty']['title'] = $this->t("Has roles in addition to 'authenticated user'");
    return $operators;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = [];
    if (in_array($this->operator, ['empty', 'not empty'])) {
      return $dependencies;
    }
    foreach ($this->value as $role_id) {
      $role = $this->roleStorage->load($role_id);
      $dependencies[$role->getConfigDependencyKey()][] = $role->getConfigDependencyName();
    }
    return $dependencies;
  }

}