You are here

class Role in Mass Contact 8

Select users by their role.

Plugin annotation


@GroupingMethod(
  id = "role",
  title = @Translation("Role"),
  description = @Translation("Select recipients by role")
)

Hierarchy

Expanded class hierarchy of Role

File

src/Plugin/MassContact/GroupingMethod/Role.php, line 21

Namespace

Drupal\mass_contact\Plugin\MassContact\GroupingMethod
View source
class Role extends GroupingBase implements ContainerFactoryPluginInterface {

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs the role grouping plugin.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->configuration += $this
      ->defaultConfiguration();
    assert(in_array($this->configuration['conjunction'], [
      'AND',
      'OR',
    ]));
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $configurations = [];
    foreach ($this->configuration['categories'] as $role_id) {
      $configurations[] = 'user.role.' . $role_id;
    }
    return [
      'config' => $configurations,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function displayCategories(array $categories) {

    /** @var \Drupal\user\RoleInterface[] $roles */
    $roles = $this->entityTypeManager
      ->getStorage('user_role')
      ->loadMultiple($categories);
    $labels = [];
    foreach ($roles as $role) {
      $labels[] = $role
        ->label();
    }
    if (!empty($labels)) {
      return new FormattableMarkup($this
        ->t('Roles: %roles', [
        '%roles' => implode(', ', $labels),
      ]), []);
    }
    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function getRecipients(array $categories) {
    if ($this->configuration['conjunction'] === 'OR') {
      $query = $this->entityTypeManager
        ->getStorage('user')
        ->getQuery();
      $query
        ->condition('status', 1);

      // If the authenticated role is not included, add the appropriate filters.
      // Otherwise, return all active users.
      if (!in_array(RoleInterface::AUTHENTICATED_ID, $categories)) {
        $query
          ->condition('roles', $categories, 'IN');
      }
      return $query
        ->execute();
    }
    else {

      // Must have all the roles if conjunction is set to AND.
      // Note that entity query doesn't appear to be able to handle multiple
      // conditions against the same field.
      $results = [];
      foreach ($categories as $id) {
        $query = $this->entityTypeManager
          ->getStorage('user')
          ->getQuery();
        $query
          ->condition('status', 1);
        if ($id !== RoleInterface::AUTHENTICATED_ID) {
          $query
            ->condition('roles', $id);
        }
        $results[$id] = $query
          ->execute();
      }
      return count($results) > 1 ? call_user_func_array('array_intersect', $results) : reset($results);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function adminForm(array &$form, FormStateInterface $form_state) {
    $roles = $this->entityTypeManager
      ->getStorage('user_role')
      ->loadMultiple();
    unset($roles[RoleInterface::ANONYMOUS_ID]);
    $options = array_map(function (RoleInterface $role) {
      return $role
        ->label();
    }, $roles);

    // Create a set of checkboxes, including each role.
    $form['categories'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('User roles to include'),
      '#options' => $options,
      '#default_value' => $this->configuration['categories'],
      '#description' => t('These roles will be added to the mailing list. Note: if you check "authenticated user", other roles will not be added, as they will receive the email anyway.'),
    ];
    $form['conjunction'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Selection criteria'),
      '#options' => [
        'OR' => $this
          ->t('Any'),
        'AND' => $this
          ->t('All'),
      ],
      '#description' => $this
        ->t('Choose <em>any</em> to return recipients with any of the roles, choose <em>all</em> to return recipients with all of the roles.'),
      '#default_value' => $this->configuration['conjunction'],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
GroupingBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurablePluginInterface::defaultConfiguration
GroupingBase::getCategories public function Retrieves a list of category IDs. Overrides GroupingInterface::getCategories
GroupingBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurablePluginInterface::getConfiguration
GroupingBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurablePluginInterface::setConfiguration
GroupingBase::submitConfigurationForm public function
GroupingBase::validateConfigurationForm public function
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
Role::$entityTypeManager protected property The entity type manager service.
Role::adminForm public function Builds the form for selecting categories for a mass contact. Overrides GroupingInterface::adminForm
Role::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
Role::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
Role::displayCategories public function Display list of categories. Overrides GroupingInterface::displayCategories
Role::getRecipients public function Retrieve the list of users by category. Overrides GroupingInterface::getRecipients
Role::__construct public function Constructs the role grouping plugin. Overrides PluginBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.