You are here

public function UserVariable::evaluate in Business Rules 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/BusinessRulesVariable/UserVariable.php \Drupal\business_rules\Plugin\BusinessRulesVariable\UserVariable::evaluate()

Evaluate the variable.

Parameters

\Drupal\business_rules\Entity\Variable $variable: The variable to be evaluated.

\Drupal\business_rules\Events\BusinessRulesEvent $event: The dispatched event.

Return value

\Drupal\business_rules\VariableObject|\Drupal\business_rules\VariablesSet The evaluated variables.

Overrides BusinessRulesVariablePlugin::evaluate

File

src/Plugin/BusinessRulesVariable/UserVariable.php, line 121

Class

UserVariable
A variable representing one user account.

Namespace

Drupal\business_rules\Plugin\BusinessRulesVariable

Code

public function evaluate(Variable $variable, BusinessRulesEvent $event) {
  $user = NULL;
  if ($variable
    ->getSettings('current_or_defined') == 'current') {

    // Get the current user.
    $account = $this->util->container
      ->get('current_user');
    $user = User::load($account
      ->id());
  }
  elseif ($variable
    ->getSettings('current_or_defined') == 'defined') {

    // Load user by id.
    $user_id = $variable
      ->getSettings('user_id');
    $user_id = $this
      ->processVariables($user_id, $event
      ->getArgument('variables'));
    $user = User::load($user_id);

    // Add log error if user id not found.
    if (empty($user)) {
      $this->util->logger
        ->error('User id: $id not found. Variable: %variable', [
        '%id' => $user_id,
        '%variable' => $variable
          ->id(),
      ]);
    }
  }
  $variableSet = new VariablesSet();

  // Prepare the user fields to be used as variables.
  if ($user instanceof User) {
    $variableObject = new VariableObject($variable
      ->id(), $user, $variable
      ->getType());
    $variableSet
      ->append($variableObject);
    $fields = $this->util->entityFieldManager
      ->getFieldDefinitions($variable
      ->getTargetEntityType(), $variable
      ->getTargetBundle());
    foreach ($fields as $field_name => $field_storage) {
      $variableObject = new VariableObject($variable
        ->id() . '->' . $field_name, $user
        ->get($field_name)->value, $variable
        ->getType());
      $variableSet
        ->append($variableObject);
    }
  }
  return $variableSet;
}