Roles.php 2.53 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\user\Plugin\views\field\Roles.
6 7
 */

8
namespace Drupal\user\Plugin\views\field;
9

10
use Drupal\Component\Annotation\PluginID;
11
use Drupal\views\Plugin\views\display\DisplayPluginBase;
12
use Drupal\views\ViewExecutable;
13
use Drupal\views\Plugin\views\field\PrerenderList;
14 15 16 17 18

/**
 * Field handler to provide a list of roles.
 *
 * @ingroup views_field_handlers
19
 *
20
 * @PluginID("user_roles")
21 22
 */
class Roles extends PrerenderList {
23

24
  /**
25
   * Overrides Drupal\views\Plugin\views\field\FieldPluginBase::init().
26
   */
27 28
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
29

30 31 32
    $this->additional_fields['uid'] = array('table' => 'users', 'field' => 'uid');
  }

33
  public function query() {
34
    $this->addAdditionalFields();
35 36 37 38 39 40 41 42
    $this->field_alias = $this->aliases['uid'];
  }

  function pre_render(&$values) {
    $uids = array();
    $this->items = array();

    foreach ($values as $result) {
43
      $uids[] = $this->get_value($result);
44 45 46
    }

    if ($uids) {
47 48
      $roles = user_roles();
      $query = db_select('users_roles', 'u');
49
      $query->fields('u', array('uid', 'rid'));
50
      $query->condition('u.rid', array_keys($roles));
51
      $query->condition('u.uid', $uids);
52

53
      $result = $query->execute();
54
      foreach ($result as $role) {
55
        $this->items[$role->uid][$role->rid]['role'] = check_plain($roles[$role->rid]->label());
56 57
        $this->items[$role->uid][$role->rid]['rid'] = $role->rid;
      }
58 59 60 61 62 63 64 65 66
      // Sort the roles for each user by role weight.
      $ordered_roles = array_flip(array_keys($roles));
      foreach ($this->items as &$user_roles) {
        // Create an array of rids that the user has in the role weight order.
        $sorted_keys  = array_intersect_key($ordered_roles, $user_roles);
        // Merge with the unsorted array of role information which has the
        // effect of sorting it.
        $user_roles = array_merge($sorted_keys, $user_roles);
      }
67 68 69 70 71 72 73 74 75 76 77 78
    }
  }

  function render_item($count, $item) {
    return $item['role'];
  }

  function document_self_tokens(&$tokens) {
    $tokens['[' . $this->options['id'] . '-role' . ']'] = t('The name of the role.');
    $tokens['[' . $this->options['id'] . '-rid' . ']'] = t('The role machine-name of the role.');
  }

79
  protected function addSelfTokens(&$tokens, $item) {
80 81 82 83 84
    if (!empty($item['role'])) {
      $tokens['[' . $this->options['id'] . '-role' . ']'] = $item['role'];
      $tokens['[' . $this->options['id'] . '-rid' . ']'] = $item['rid'];
    }
  }
85

86
}