Chris@0: 'checkboxes', Chris@0: '#title' => $this->t('When the user has the following roles'), Chris@0: '#default_value' => $this->configuration['roles'], Chris@0: '#options' => array_map('\Drupal\Component\Utility\Html::escape', user_role_names()), Chris@0: '#description' => $this->t('If you select no roles, the condition will evaluate to TRUE for all users.'), Chris@0: ]; Chris@0: return parent::buildConfigurationForm($form, $form_state); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function defaultConfiguration() { Chris@0: return [ Chris@0: 'roles' => [], Chris@0: ] + parent::defaultConfiguration(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { Chris@0: $this->configuration['roles'] = array_filter($form_state->getValue('roles')); Chris@0: parent::submitConfigurationForm($form, $form_state); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function summary() { Chris@0: // Use the role labels. They will be sanitized below. Chris@0: $roles = array_intersect_key(user_role_names(), $this->configuration['roles']); Chris@0: if (count($roles) > 1) { Chris@0: $roles = implode(', ', $roles); Chris@0: } Chris@0: else { Chris@0: $roles = reset($roles); Chris@0: } Chris@0: if (!empty($this->configuration['negate'])) { Chris@0: return $this->t('The user is not a member of @roles', ['@roles' => $roles]); Chris@0: } Chris@0: else { Chris@0: return $this->t('The user is a member of @roles', ['@roles' => $roles]); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function evaluate() { Chris@0: if (empty($this->configuration['roles']) && !$this->isNegated()) { Chris@0: return TRUE; Chris@0: } Chris@0: $user = $this->getContextValue('user'); Chris@0: return (bool) array_intersect($this->configuration['roles'], $user->getRoles()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function getCacheContexts() { Chris@0: // Optimize cache context, if a user cache context is provided, only use Chris@0: // user.roles, since that's the only part this condition cares about. Chris@0: $contexts = []; Chris@0: foreach (parent::getCacheContexts() as $context) { Chris@0: $contexts[] = $context == 'user' ? 'user.roles' : $context; Chris@0: } Chris@0: return $contexts; Chris@0: } Chris@0: Chris@0: }