You are here

class Role in Commerce License 8.2

Provides a license type which grants one or more roles.

Plugin annotation


@CommerceLicenseType(
  id = "role",
  label = @Translation("Role"),
)

Hierarchy

Expanded class hierarchy of Role

File

src/Plugin/Commerce/LicenseType/Role.php, line 23

Namespace

Drupal\commerce_license\Plugin\Commerce\LicenseType
View source
class Role extends LicenseTypeBase implements ExistingRightsFromConfigurationCheckingInterface, GrantedEntityLockingInterface {

  /**
   * {@inheritdoc}
   */
  public function buildLabel(LicenseInterface $license) {
    $args = [
      '@role' => $license->license_role->entity
        ->label(),
    ];
    return $this
      ->t('@role role license', $args);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'license_role' => '',
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function grantLicense(LicenseInterface $license) {

    // Get the role ID that this license grants.
    $role_id = $license->license_role->target_id;

    // Get the owner of the license and grant them the role.
    $owner = $license
      ->getOwner();
    if (!$owner
      ->isAnonymous()) {
      $owner
        ->addRole($role_id);
      $owner
        ->save();
    }

    // TODO: Log this, as it's something admins should see?
  }

  /**
   * {@inheritdoc}
   */
  public function revokeLicense(LicenseInterface $license) {

    // Get the role ID that this license grants.
    $role_id = $license->license_role
      ->first()->target_id;

    // Get the owner of the license and remove that role.
    $owner = $license
      ->getOwner();
    if (!$owner
      ->isAnonymous()) {
      $owner
        ->removeRole($role_id);
      $owner
        ->save();
    }

    // TODO: Log this, as it's something admins should see?
  }

  /**
   * {@inheritdoc}
   */
  public function checkUserHasExistingRights(UserInterface $user) {
    $role_id = $this->configuration['license_role'];
    $role = \Drupal::service('entity_type.manager')
      ->getStorage('user_role')
      ->load($role_id);
    return ExistingRightsResult::rightsExistIf($user
      ->hasRole($role_id), $this
      ->t("You already have the @role-label role.", [
      '@role-label' => $role
        ->label(),
    ]), $this
      ->t("User @user already has the @role-label role.", [
      '@user' => $user
        ->getDisplayName(),
      '@role-label' => $role
        ->label(),
    ]));
  }

  /**
   * {@inheritdoc}
   */
  public function alterEntityOwnerForm(array &$form, FormStateInterface $form_state, $form_id, LicenseInterface $license, EntityInterface $form_entity) {
    if ($form_entity
      ->getEntityTypeId() != 'user') {

      // Only act on a user form.
      return;
    }
    $licensed_role_id = $license->license_role->target_id;
    $form['account']['roles'][$licensed_role_id]['#disabled'] = TRUE;
    $form['account']['roles'][$licensed_role_id]['#default_value'] = TRUE;
    $form['account']['roles'][$licensed_role_id]['#description'] = t("This role is granted by a license. It cannot be removed manually.");
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $roles = UserRole::loadMultiple();

    // Skip the built-in roles.
    unset($roles[RoleInterface::ANONYMOUS_ID]);
    unset($roles[RoleInterface::AUTHENTICATED_ID]);

    // Remove the admin role if it exists.
    // TODO: consider removing any role that has is_admin set.
    unset($roles['administrator']);

    // If no licensable roles exist, display an error message.
    // A radios element without options will result in an
    // "Illegal choice detected" error.
    if (!$roles) {
      $form['error'] = [
        '#markup' => $this
          ->t('No licensable roles can be configured, please review your configuration.'),
      ];
      return $form;
    }
    $options = EntityHelper::extractLabels($roles);
    $form['license_role'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Licensed role'),
      '#options' => EntityHelper::extractLabels($roles),
      '#default_value' => isset($options[$this->configuration['license_role']]) ? $this->configuration['license_role'] : key($options),
      '#required' => TRUE,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValue($form['#parents']);
    if (!empty($values['license_role'])) {
      $this->configuration['license_role'] = $values['license_role'];
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildFieldDefinitions() {
    $fields = parent::buildFieldDefinitions();
    $fields['license_role'] = BundleFieldDefinition::create('entity_reference')
      ->setLabel(t('Role'))
      ->setDescription(t('The role this product grants access to.'))
      ->setCardinality(1)
      ->setRequired(TRUE)
      ->setSetting('target_type', 'user_role')
      ->setDisplayOptions('form', [
      'type' => 'options_select',
    ])
      ->setDisplayOptions('view', [
      'label' => 'inline',
      'type' => 'entity_reference_label',
      'weight' => 1,
      'settings' => [
        'link' => TRUE,
      ],
    ]);
    return $fields;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
LicenseTypeBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
LicenseTypeBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
LicenseTypeBase::getLabel public function Gets the license type label. Overrides LicenseTypeInterface::getLabel
LicenseTypeBase::getWorkflowId public function Gets the workflow ID this this license type should use. Overrides LicenseTypeInterface::getWorkflowId
LicenseTypeBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
LicenseTypeBase::setConfigurationValuesOnLicense public function Copy configuration values to a license entity. Overrides LicenseTypeInterface::setConfigurationValuesOnLicense
LicenseTypeBase::__construct public function Constructs a new plugin instance. Overrides PluginBase::__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.
Role::alterEntityOwnerForm public function Alter a form for an entity owned by the license owner. Overrides GrantedEntityLockingInterface::alterEntityOwnerForm
Role::buildConfigurationForm public function Form constructor. Overrides LicenseTypeBase::buildConfigurationForm
Role::buildFieldDefinitions public function Builds the field definitions for entities of this bundle. Overrides LicenseTypeBase::buildFieldDefinitions
Role::buildLabel public function Builds a label for the given license. Overrides LicenseTypeInterface::buildLabel
Role::checkUserHasExistingRights public function Checks whether the user already has the rights this license grants. Overrides ExistingRightsFromConfigurationCheckingInterface::checkUserHasExistingRights
Role::defaultConfiguration public function Gets default configuration for this plugin. Overrides LicenseTypeBase::defaultConfiguration
Role::grantLicense public function Reacts to the license being activated. Overrides LicenseTypeInterface::grantLicense
Role::revokeLicense public function Reacts to the license being revoked. Overrides LicenseTypeInterface::revokeLicense
Role::submitConfigurationForm public function Form submission handler. Overrides LicenseTypeBase::submitConfigurationForm
Role::validateConfigurationForm public function Form validation handler. Overrides LicenseTypeBase::validateConfigurationForm
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.