You are here

protected function UserRestrictionTypeBase::matchesValue in User restrictions 8

Check if the specified value matches the restriction.

Parameters

string $value: String to check against all restrictions of the type.

Return value

bool|\Drupal\user_restrictions\Entity\UserRestrictions The restriction entity if the value matches one of the restrictions, FALSE otherwise.

3 calls to UserRestrictionTypeBase::matchesValue()
ClientIp::matches in src/Plugin/UserRestrictionType/ClientIp.php
Check if the given data matches the restriction.
Email::matches in src/Plugin/UserRestrictionType/Email.php
Check if the given data matches the restriction.
Name::matches in src/Plugin/UserRestrictionType/Name.php
Check if the given data matches the restriction.

File

src/Plugin/UserRestrictionType/UserRestrictionTypeBase.php, line 64

Class

UserRestrictionTypeBase

Namespace

Drupal\user_restrictions\Plugin\UserRestrictionType

Code

protected function matchesValue($value) {

  // Load rules with exact pattern matches.
  $query = $this->entityStorage
    ->getQuery();
  $query
    ->condition('rule_type', $this
    ->getPluginId())
    ->condition('pattern', $value)
    ->condition('expiry', \Drupal::time()
    ->getRequestTime(), '>');
  $results = $query
    ->execute();
  $exact_rules = $this->entityStorage
    ->loadMultiple($results);
  if (!empty($exact_rules)) {

    // Simply take the first matching rule as we have no weight (yet).

    /** @var \Drupal\user_restrictions\Entity\UserRestrictions $rule */
    $rule = reset($exact_rules);
    return $rule
      ->getAccessType() === UserRestrictions::BLACKLIST ? $rule : FALSE;
  }

  // Load all rules of the restriction type.
  $query = $this->entityStorage
    ->getQuery();
  $query
    ->condition('rule_type', $this
    ->getPluginId())
    ->condition('expiry', \Drupal::time()
    ->getRequestTime(), '>');
  $results = $query
    ->execute();
  $rules = $this->entityStorage
    ->loadMultiple($results);
  if (empty($rules)) {
    return FALSE;
  }

  // Set the return variable to FALSE to allow by default.
  $return = FALSE;

  /** @var \Drupal\user_restrictions\Entity\UserRestrictions $rule */
  foreach ($rules as $rule) {
    if (preg_match('/' . $rule
      ->getPattern() . '/i', $value)) {

      // Exit loop after first whitelisted pattern.
      if ($rule
        ->getAccessType() === UserRestrictions::WHITELIST) {
        return FALSE;
      }
      elseif ($rule
        ->getAccessType() === UserRestrictions::BLACKLIST) {

        // If a matching pattern is blacklisted store it but don't return
        // as there may be a whitelisted pattern further in the loop.
        $return = $rule;
      }
    }
  }

  // Return either no match or the blacklisted rule.
  return $return;
}