You are here

public function Security::hasPermissions in Bamboo Twig 8.5

Same name and namespace in other branches
  1. 8.4 bamboo_twig_security/src/TwigExtension/Security.php \Drupal\bamboo_twig_security\TwigExtension\Security::hasPermissions()

Does the current|given user has the given permissions collection ?

Parameters

string[] $permissions: Drupal permissions string.

string $conjunction: (Optional) The conjunction to use againts user permissions. Allowing 'AND' or 'OR' values. Default to 'AND'.

int $user: (Optional) user id to check permission. Otherwise current user is used.

Return value

bool True if the current|given user has all the given permissions. Otherwise FALSE.

File

bamboo_twig_security/src/TwigExtension/Security.php, line 72

Class

Security
Provides a 'Security' Twig Extensions.

Namespace

Drupal\bamboo_twig_security\TwigExtension

Code

public function hasPermissions(array $permissions, $conjunction = 'AND', $user = NULL) {

  // Get the current user when $user is not provided.
  if (!$user) {
    $user = $this
      ->getCurrentUser()
      ->id();
  }
  $account = $this
    ->getUserStorage()
    ->load($user);

  // If given user do not exists or is anonymous - don't go further.
  if (!$account || $account
    ->isAnonymous()) {
    return NULL;
  }

  // Sanitize the conjunction to AND / OR values.
  if (!in_array($conjunction, [
    'AND',
    'OR',
  ])) {
    throw new \InvalidArgumentException(sprintf('Invalid conjunction type "%s".', $conjunction));
  }
  foreach ($permissions as $permission) {

    // When OR is requested, return TRUE on any match.
    if ($conjunction == 'OR' and $account
      ->hasPermission($permission)) {
      return TRUE;
    }

    // When AND is requested, return FALSE on any unmatch.
    if ($conjunction == 'AND' and !$account
      ->hasPermission($permission)) {
      return FALSE;
    }
  }

  // The previous loop may not return when:
  // - The conjunction is AND & the user has all roles.
  // - The conjunction is OR & the user has not any roles.
  return $conjunction == 'AND' ? TRUE : FALSE;
}