entity_agree-2.0.x-dev/src/Plugin/entity_agree/AgreementHandler/RoleApplies.php
src/Plugin/entity_agree/AgreementHandler/RoleApplies.php
<?php namespace Drupal\entity_agree\Plugin\entity_agree\AgreementHandler; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\entity_agree\AgreementHandlerAppliesInterface; use Drupal\entity_agree\AgreementHandlerPluginBase; use Drupal\user\RoleInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Plugin to determine if agreement applies to roles. * * @AgreementHandler( * id = "entity_agree_roles_apply", * label = @Translation("Roles"), * category = @Translation("Applies"), * ) */ class RoleApplies extends AgreementHandlerPluginBase implements AgreementHandlerAppliesInterface, ContainerFactoryPluginInterface { /** * The current user. * * @var \Drupal\Core\Session\AccountInterface */ protected $currentUser; /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { $plugin = new static($configuration, $plugin_id, $plugin_definition); $plugin->currentUser = $container->get('current_user'); return $plugin; } /** * {@inheritdoc} */ public function defaultConfiguration() { return parent::defaultConfiguration() + [ 'roles' => [], 'negate' => [], 'conjunction' => 'and', ]; } /** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form = parent::buildConfigurationForm($form, $form_state); $form['roles'] = [ '#type' => 'checkboxes', '#title' => $this->t('Roles'), '#options' => array_map(function (RoleInterface $role) { return $role->label(); }, user_roles(TRUE)), '#default_value' => $this->configuration['roles'] ?? [], ]; $form['negate'] = [ '#type' => 'checkbox', '#title' => $this->t('Negate'), '#default_value' => $this->configuration['negate'], ]; $form['conjunction'] = [ '#type' => 'select', '#title' => $this->t('Conjunction'), '#options' => [ 'all' => $this->t('All'), 'any' => $this->t('Any'), ], '#default_value' => $this->configuration['conjunction'], ]; return $form; } /** * {@inheritdoc} */ public function applies() { if ($this->configuration['conjunction'] == 'any') { $result = !empty(array_intersect($this->configuration['roles'], $this->currentUser->getRoles())); } else { $result = !empty(array_diff($this->configuration['roles'], $this->currentUser->getRoles())); } return $result xor $this->configuration['negate']; } }