You are here

class DrupalRolesConsumer in Authorization 8

Provides a consumer for Drupal roles.

Plugin annotation


@AuthorizationConsumer(
  id = "authorization_drupal_roles",
  label = @Translation("Drupal Roles")
)

Hierarchy

Expanded class hierarchy of DrupalRolesConsumer

File

authorization_drupal_roles/src/Plugin/authorization/Consumer/DrupalRolesConsumer.php, line 23

Namespace

Drupal\authorization_drupal_roles\Plugin\authorization\Consumer
View source
class DrupalRolesConsumer extends ConsumerPluginBase {

  /**
   * Allow consumer target creation.
   *
   * @var bool
   */
  protected $allowConsumerTargetCreation = TRUE;

  /**
   * Wildcard.
   *
   * @var string
   */
  protected $wildcard = 'source';

  /**
   * Transliteration.
   *
   * @var \Drupal\Component\Transliteration\TransliterationInterface
   */
  protected $transliteration;

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

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, TransliterationInterface $transliteration, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->transliteration = $transliteration;
    $this->entityTypeManager = $entity_type_manager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) : array {
    $form['description'] = [
      '#type' => 'markup',
      '#markup' => $this
        ->t('There are no settings for Drupal roles.'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function buildRowForm(array $form, FormStateInterface $form_state, $index = 0) : array {
    $row = [];
    $mappings = $this->configuration['profile']
      ->getConsumerMappings();
    $roleOptions = [
      'none' => $this
        ->t('- N/A -'),
    ];
    $roles = user_roles(TRUE);
    foreach ($roles as $key => $role) {
      if ($key !== 'authenticated') {
        $roleOptions[$key] = $role
          ->label();
      }
    }
    $roleOptions['source'] = $this
      ->t('Source (Any group)');
    $row['role'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Role'),
      '#options' => $roleOptions,
      '#default_value' => isset($mappings[$index]) ? $mappings[$index]['role'] : NULL,
      '#description' => $this
        ->t("Choosing 'Source' maps any input directly to Drupal, use with caution."),
    ];
    return $row;
  }

  /**
   * {@inheritdoc}
   */
  public function grantSingleAuthorization(UserInterface $user, $mapping) : void {
    $mapping = $this
      ->sanitizeRoleId($mapping);
    $previousRoles = [];
    $savedRoles = $user
      ->get('authorization_drupal_roles_roles')
      ->getValue();
    foreach ($savedRoles as $savedRole) {
      $previousRoles[] = $savedRole['value'];
    }
    if (!in_array($mapping, $previousRoles, TRUE)) {
      $previousRoles[] = $mapping;
    }
    $user
      ->set('authorization_drupal_roles_roles', $previousRoles);
    $user
      ->addRole($mapping);
  }

  /**
   * {@inheritdoc}
   */
  public function revokeGrants(UserInterface $user, array $context) : void {
    foreach ($context as $key => $mapping) {
      $context[$key] = $this
        ->sanitizeRoleId($mapping);
    }
    $previousRoles = [];
    $savedRoles = $user
      ->get('authorization_drupal_roles_roles')
      ->getValue();
    foreach ($savedRoles as $savedRole) {
      $previousRoles[] = $savedRole['value'];
    }
    foreach ($previousRoles as $key => $value) {
      if (!in_array($value, $context, TRUE)) {
        $user
          ->removeRole($value);
        unset($previousRoles[$key]);
      }
    }
    $user
      ->set('authorization_drupal_roles_roles', $previousRoles);
  }

  /**
   * {@inheritdoc}
   */
  public function createConsumerTarget(string $mapping) : void {
    $sanitizedId = $this
      ->sanitizeRoleId($mapping);
    $storage = $this->entityTypeManager
      ->getStorage('user_role');
    if (!$storage
      ->load($sanitizedId)) {
      $role = $storage
        ->create([
        'id' => $sanitizedId,
        'label' => $mapping,
      ]);
      $role
        ->save();
    }
  }

  /**
   * Return the wildcard in use.
   *
   * We use this to allow for direct mapping within the filter proposals.
   *
   * @return string
   *   Wildcard.
   */
  private function getWildcard() : string {
    return $this->wildcard;
  }

  /**
   * {@inheritdoc}
   */
  public function filterProposals(array $proposals, array $mapping) : array {
    if ($mapping['role'] === $this
      ->getWildcard()) {
      return $proposals;
    }

    // Filters out valid providers with invalid assignments.
    if ($mapping['role'] === 'none') {
      return [];
    }
    if (!empty($proposals)) {

      // The match from the provider already ensured that the consumer mapping
      // is correct, thus we can safely map the value directly.
      return [
        $mapping['role'] => $mapping['role'],
      ];
    }
    return [];
  }

  /**
   * Take a proposed mapping and provide a safe value for Drupal roles.
   *
   * @param string $consumer
   *   A valid proposal for this consumer.
   *
   * @return string
   *   A valid string for Drupal roles.
   */
  private function sanitizeRoleId(string $consumer) : string {
    $sanitizedId = $this->transliteration
      ->transliterate($consumer, 'en', '');
    $sanitizedId = mb_strtolower($sanitizedId);
    return preg_replace('@[^a-z0-9_.]+@', '_', $sanitizedId);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigurableAuthorizationPluginBase::buildRowDescription public function Builds the authorization row description. Overrides ConfigurableAuthorizationPluginInterface::buildRowDescription
ConfigurableAuthorizationPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ConfigurableAuthorizationPluginBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration
ConfigurableAuthorizationPluginBase::getConfiguration public function Unused, configuration is saved in the profile, required by base class. Overrides ConfigurableInterface::getConfiguration
ConfigurableAuthorizationPluginBase::getDescription public function Returns the plugin's description. Overrides ConfigurableAuthorizationPluginInterface::getDescription
ConfigurableAuthorizationPluginBase::getTokens public function Tokens for the relevant plugin. Overrides ConfigurableAuthorizationPluginInterface::getTokens
ConfigurableAuthorizationPluginBase::getType public function
ConfigurableAuthorizationPluginBase::label public function Returns the label for use on the administration pages. Overrides ConfigurableAuthorizationPluginInterface::label
ConfigurableAuthorizationPluginBase::setConfiguration public function Unused, configuration is saved in the profile, required by base class. Overrides ConfigurableInterface::setConfiguration
ConfigurableAuthorizationPluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
ConfigurableAuthorizationPluginBase::submitRowForm public function Submits the authorization form row. Overrides ConfigurableAuthorizationPluginInterface::submitRowForm
ConfigurableAuthorizationPluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
ConfigurableAuthorizationPluginBase::validateRowForm public function Validates the authorization form row. Overrides ConfigurableAuthorizationPluginInterface::validateRowForm
ConsumerPluginBase::$type protected property Defines the type, for example used by getToken(). Overrides ConfigurableAuthorizationPluginBase::$type
ConsumerPluginBase::consumerTargetCreationAllowed public function Are we allowed to create things. Overrides ConsumerInterface::consumerTargetCreationAllowed
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
DrupalRolesConsumer::$allowConsumerTargetCreation protected property Allow consumer target creation. Overrides ConsumerPluginBase::$allowConsumerTargetCreation
DrupalRolesConsumer::$entityTypeManager protected property Entity type manager.
DrupalRolesConsumer::$transliteration protected property Transliteration.
DrupalRolesConsumer::$wildcard protected property Wildcard.
DrupalRolesConsumer::buildConfigurationForm public function Form constructor. Overrides ConfigurableAuthorizationPluginBase::buildConfigurationForm
DrupalRolesConsumer::buildRowForm public function Builds the authorization form row. Overrides ConfigurableAuthorizationPluginBase::buildRowForm
DrupalRolesConsumer::create public static function Creates an instance of the plugin. Overrides ConfigurableAuthorizationPluginBase::create
DrupalRolesConsumer::createConsumerTarget public function Create authorization consumer targets. Overrides ConsumerInterface::createConsumerTarget
DrupalRolesConsumer::filterProposals public function Consumer-side filtering. Overrides ConsumerPluginBase::filterProposals
DrupalRolesConsumer::getWildcard private function Return the wildcard in use.
DrupalRolesConsumer::grantSingleAuthorization public function Grant one individual proposal. Overrides ConsumerInterface::grantSingleAuthorization
DrupalRolesConsumer::revokeGrants public function Revoke all previously applied and no longer valid grants. Overrides ConsumerInterface::revokeGrants
DrupalRolesConsumer::sanitizeRoleId private function Take a proposed mapping and provide a safe value for Drupal roles.
DrupalRolesConsumer::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides ConfigurableAuthorizationPluginBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
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.
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.