ConditionAccessResolverTrait.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Drupal\Core\Condition;
  3. use Drupal\Component\Plugin\Exception\ContextException;
  4. /**
  5. * Resolves a set of conditions.
  6. */
  7. trait ConditionAccessResolverTrait {
  8. /**
  9. * Resolves the given conditions based on the condition logic ('and'/'or').
  10. *
  11. * @param \Drupal\Core\Condition\ConditionInterface[] $conditions
  12. * A set of conditions.
  13. * @param string $condition_logic
  14. * The logic used to compute access, either 'and' or 'or'.
  15. *
  16. * @return bool
  17. * Whether these conditions grant or deny access.
  18. */
  19. protected function resolveConditions($conditions, $condition_logic) {
  20. foreach ($conditions as $condition) {
  21. try {
  22. $pass = $condition->execute();
  23. }
  24. catch (ContextException $e) {
  25. // If a condition is missing context and is not negated, consider that a
  26. // fail.
  27. $pass = $condition->isNegated();
  28. }
  29. // If a condition fails and all conditions were needed, deny access.
  30. if (!$pass && $condition_logic == 'and') {
  31. return FALSE;
  32. }
  33. // If a condition passes and only one condition was needed, grant access.
  34. elseif ($pass && $condition_logic == 'or') {
  35. return TRUE;
  36. }
  37. }
  38. // Return TRUE if logic was 'and', meaning all rules passed.
  39. // Return FALSE if logic was 'or', meaning no rule passed.
  40. return $condition_logic == 'and';
  41. }
  42. }