Issue #1479454 by Hugo Wetterberg, galooph, dawehner, andypost, marcingy, heyrocker...
[project/drupal.git] / core / modules / user / lib / Drupal / user / Plugin / views / field / Roles.php
1 <?php
2
3 /**
4 * @file
5 * Definition of Drupal\user\Plugin\views\field\Roles.
6 */
7
8 namespace Drupal\user\Plugin\views\field;
9
10 use Drupal\Core\Annotation\Plugin;
11 use Drupal\views\Plugin\views\display\DisplayPluginBase;
12 use Drupal\views\ViewExecutable;
13 use Drupal\views\Plugin\views\field\PrerenderList;
14
15 /**
16 * Field handler to provide a list of roles.
17 *
18 * @ingroup views_field_handlers
19 *
20 * @Plugin(
21 * id = "user_roles",
22 * module = "user"
23 * )
24 */
25 class Roles extends PrerenderList {
26
27 /**
28 * Overrides Drupal\views\Plugin\views\field\FieldPluginBase::init().
29 */
30 public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
31 parent::init($view, $display, $options);
32
33 $this->additional_fields['uid'] = array('table' => 'users', 'field' => 'uid');
34 }
35
36 public function query() {
37 $this->add_additional_fields();
38 $this->field_alias = $this->aliases['uid'];
39 }
40
41 function pre_render(&$values) {
42 $uids = array();
43 $this->items = array();
44
45 foreach ($values as $result) {
46 $uids[] = $this->get_value($result);
47 }
48
49 if ($uids) {
50 $roles = user_roles();
51 $query = db_select('users_roles', 'u');
52 $query->fields('u', array('uid', 'rid'));
53 $query->condition('u.rid', array_keys($roles));
54 $query->condition('u.uid', $uids);
55
56 $result = $query->execute();
57 foreach ($result as $role) {
58 $this->items[$role->uid][$role->rid]['role'] = check_plain($roles[$role->rid]->label());
59 $this->items[$role->uid][$role->rid]['rid'] = $role->rid;
60 }
61 // Sort the roles for each user by role weight.
62 $ordered_roles = array_flip(array_keys($roles));
63 foreach ($this->items as &$user_roles) {
64 // Create an array of rids that the user has in the role weight order.
65 $sorted_keys = array_intersect_key($ordered_roles, $user_roles);
66 // Merge with the unsorted array of role information which has the
67 // effect of sorting it.
68 $user_roles = array_merge($sorted_keys, $user_roles);
69 }
70 }
71 }
72
73 function render_item($count, $item) {
74 return $item['role'];
75 }
76
77 function document_self_tokens(&$tokens) {
78 $tokens['[' . $this->options['id'] . '-role' . ']'] = t('The name of the role.');
79 $tokens['[' . $this->options['id'] . '-rid' . ']'] = t('The role machine-name of the role.');
80 }
81
82 function add_self_tokens(&$tokens, $item) {
83 if (!empty($item['role'])) {
84 $tokens['[' . $this->options['id'] . '-role' . ']'] = $item['role'];
85 $tokens['[' . $this->options['id'] . '-rid' . ']'] = $item['rid'];
86 }
87 }
88
89 }