You are here

public function PasswordPolicyValidator::buildPasswordPolicyConstraintsTableRows in Password Policy 8.3

Builds the password policy constraints table rows.

Parameters

string $password: The new password.

\Drupal\user\UserInterface $user: The current user object.

array $edited_user_roles: An optional array containing the edited user roles.

Return value

array An array containing the constraints table rows.

Overrides PasswordPolicyValidatorInterface::buildPasswordPolicyConstraintsTableRows

File

src/PasswordPolicyValidator.php, line 95

Class

PasswordPolicyValidator

Namespace

Drupal\password_policy

Code

public function buildPasswordPolicyConstraintsTableRows(string $password, UserInterface $user, array $edited_user_roles = []) : array {
  if (empty($edited_user_roles)) {
    $edited_user_roles = $user
      ->getRoles();
    $edited_user_roles = array_combine($edited_user_roles, $edited_user_roles);
  }

  // Run validation.
  $applicable_policies = $this
    ->getApplicablePolicies($edited_user_roles);
  $original_roles = $user
    ->getRoles();
  $original_roles = array_combine($original_roles, $original_roles);
  $force_failure = FALSE;
  if ($edited_user_roles !== $original_roles && $password === '' && !empty($applicable_policies)) {

    // New role has been added and applicable policies are available.
    $force_failure = TRUE;
  }
  $policies_table_rows = [];

  /** @var \Drupal\password_policy\Entity\PasswordPolicy $policy */
  foreach ($applicable_policies as $policy) {
    $policy_constraints = $policy
      ->getConstraints();
    foreach ($policy_constraints as $constraint) {

      /** @var \Drupal\password_policy\PasswordConstraintInterface $plugin_object */
      $plugin_object = $this->passwordConstraintPluginManager
        ->createInstance($constraint['id'], $constraint);

      // Execute validation.
      $validation = $plugin_object
        ->validate($password, $user);
      if (!$force_failure && $validation
        ->isValid()) {
        $status = t('Pass');
      }
      else {
        $message = $validation
          ->getErrorMessage();
        if (empty($message)) {
          $message = t('New role was added or existing password policy changed. Please update your password.');
        }
        $status = t('Fail - @message', [
          '@message' => $message,
        ]);
      }
      $status_class = 'password-policy-constraint-' . ($validation
        ->isValid() ? 'passed' : 'failed');
      $table_row = [
        'data' => [
          'policy' => $policy
            ->label(),
          'status' => $status,
          'constraint' => $plugin_object
            ->getSummary(),
        ],
        'class' => [
          $status_class,
        ],
      ];
      $policies_table_rows[] = $table_row;
    }
  }
  return $policies_table_rows;
}