You are here

public function AddRoleToUser::execute in Business Rules 8

Same name and namespace in other branches
  1. 2.x src/Plugin/BusinessRulesAction/AddRoleToUser.php \Drupal\business_rules\Plugin\BusinessRulesAction\AddRoleToUser::execute()

Execute the action.

Parameters

\Drupal\business_rules\ActionInterface $action: The configured action.

\Drupal\business_rules\Events\BusinessRulesEvent $event: The event that has triggered the action.

Return value

array The render array to be showed on debug block.

Overrides BusinessRulesActionPlugin::execute

File

src/Plugin/BusinessRulesAction/AddRoleToUser.php, line 126

Class

AddRoleToUser
Class AddRoleToUser.

Namespace

Drupal\business_rules\Plugin\BusinessRulesAction

Code

public function execute(ActionInterface $action, BusinessRulesEvent $event) {

  /** @var \Drupal\business_rules\VariablesSet $event_variables */
  $event_variables = $event
    ->getArgument('variables');
  $user_container = $action
    ->getSettings('user_container');
  $uid = $action
    ->getSettings('uid');
  $uid = $this
    ->processVariables($uid, $event_variables);
  $variable = $action
    ->getSettings('variable');
  $roles = $action
    ->getSettings('roles');
  switch ($user_container) {
    case 'current':

      /** @var \Drupal\Core\Session\AccountProxyInterface $account */

      /** @var \Drupal\user\Entity\User $user */
      $account = $this->util->container
        ->get('current_user');
      $user = User::load($account
        ->id());
      break;
    case 'by_id':
      $user = User::load($uid);
      break;
    case 'variable':
      $user = $event_variables
        ->getVariable($variable);
      break;
  }
  foreach ($roles as $role) {
    $user
      ->addRole($role);
  }
  $user
    ->save();
  $result = [
    '#type' => 'markup',
    '#markup' => t('User: %user<br>Roles added: %roles', [
      '%user' => $user
        ->getAccountName(),
      '%roles' => implode(', ', $roles),
    ]),
  ];
  return $result;
}