Permission.php in Drupal 8
File
core/modules/user/src/Plugin/views/access/Permission.php
View source
<?php
namespace Drupal\user\Plugin\views\access;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\PermissionHandlerInterface;
use Drupal\views\Plugin\views\access\AccessPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
class Permission extends AccessPluginBase implements CacheableDependencyInterface {
protected $usesOptions = TRUE;
protected $permissionHandler;
protected $moduleHandler;
public function __construct(array $configuration, $plugin_id, $plugin_definition, PermissionHandlerInterface $permission_handler, ModuleHandlerInterface $module_handler) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->permissionHandler = $permission_handler;
$this->moduleHandler = $module_handler;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('user.permissions'), $container
->get('module_handler'));
}
public function access(AccountInterface $account) {
return $account
->hasPermission($this->options['perm']);
}
public function alterRouteDefinition(Route $route) {
$route
->setRequirement('_permission', $this->options['perm']);
}
public function summaryTitle() {
$permissions = $this->permissionHandler
->getPermissions();
if (isset($permissions[$this->options['perm']])) {
return $permissions[$this->options['perm']]['title'];
}
return $this
->t($this->options['perm']);
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['perm'] = [
'default' => 'access content',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$perms = [];
$permissions = $this->permissionHandler
->getPermissions();
foreach ($permissions as $perm => $perm_item) {
$provider = $perm_item['provider'];
$display_name = $this->moduleHandler
->getName($provider);
$perms[$display_name][$perm] = strip_tags($perm_item['title']);
}
$form['perm'] = [
'#type' => 'select',
'#options' => $perms,
'#title' => $this
->t('Permission'),
'#default_value' => $this->options['perm'],
'#description' => $this
->t('Only users with the selected permission flag will be able to access this display.'),
];
}
public function getCacheMaxAge() {
return Cache::PERMANENT;
}
public function getCacheContexts() {
return [
'user.permissions',
];
}
public function getCacheTags() {
return [];
}
}
Classes
Name |
Description |
Permission |
Access plugin that provides permission-based access control. |