ConditionAccessResolverTrait.php 1.36 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Condition;

5
use Drupal\Component\Plugin\Exception\ContextException;
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

/**
 * Resolves a set of conditions.
 */
trait ConditionAccessResolverTrait {

  /**
   * Resolves the given conditions based on the condition logic ('and'/'or').
   *
   * @param \Drupal\Core\Condition\ConditionInterface[] $conditions
   *   A set of conditions.
   * @param string $condition_logic
   *   The logic used to compute access, either 'and' or 'or'.
   *
   * @return bool
   *   Whether these conditions grant or deny access.
   */
  protected function resolveConditions($conditions, $condition_logic) {
    foreach ($conditions as $condition) {
      try {
        $pass = $condition->execute();
      }
28
      catch (ContextException $e) {
29 30 31
        // If a condition is missing context and is not negated, consider that a
        // fail.
        $pass = $condition->isNegated();
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
      }

      // If a condition fails and all conditions were needed, deny access.
      if (!$pass && $condition_logic == 'and') {
        return FALSE;
      }
      // If a condition passes and only one condition was needed, grant access.
      elseif ($pass && $condition_logic == 'or') {
        return TRUE;
      }
    }

    // Return TRUE if logic was 'and', meaning all rules passed.
    // Return FALSE if logic was 'or', meaning no rule passed.
    return $condition_logic == 'and';
  }

}