UserRole.php in Drupal 10
File
core/modules/user/src/Plugin/Condition/UserRole.php
View source
<?php
namespace Drupal\user\Plugin\Condition;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
class UserRole extends ConditionPluginBase {
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['roles'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('When the user has the following roles'),
'#default_value' => $this->configuration['roles'],
'#options' => array_map('\\Drupal\\Component\\Utility\\Html::escape', user_role_names()),
'#description' => $this
->t('If you select no roles, the condition will evaluate to TRUE for all users.'),
];
return parent::buildConfigurationForm($form, $form_state);
}
public function defaultConfiguration() {
return [
'roles' => [],
] + parent::defaultConfiguration();
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['roles'] = array_filter($form_state
->getValue('roles'));
parent::submitConfigurationForm($form, $form_state);
}
public function summary() {
$roles = array_intersect_key(user_role_names(), $this->configuration['roles']);
if (count($roles) > 1) {
$roles = implode(', ', $roles);
}
else {
$roles = reset($roles);
}
if (!empty($this->configuration['negate'])) {
return $this
->t('The user is not a member of @roles', [
'@roles' => $roles,
]);
}
else {
return $this
->t('The user is a member of @roles', [
'@roles' => $roles,
]);
}
}
public function evaluate() {
if (empty($this->configuration['roles']) && !$this
->isNegated()) {
return TRUE;
}
$user = $this
->getContextValue('user');
return (bool) array_intersect($this->configuration['roles'], $user
->getRoles());
}
public function getCacheContexts() {
$contexts = [];
foreach (parent::getCacheContexts() as $context) {
$contexts[] = $context == 'user' ? 'user.roles' : $context;
}
return $contexts;
}
}