You are here

public function ContextDefinition::isSatisfiedBy in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Plugin/Context/ContextDefinition.php \Drupal\Core\Plugin\Context\ContextDefinition::isSatisfiedBy()

Determines if this definition is satisfied by a context object.

Parameters

\Drupal\Core\Plugin\Context\ContextInterface $context: The context object.

Return value

bool TRUE if this definition is satisfiable by the context object, FALSE otherwise.

Overrides ContextDefinitionInterface::isSatisfiedBy

File

core/lib/Drupal/Core/Plugin/Context/ContextDefinition.php, line 345

Class

ContextDefinition
Defines a class for context definitions.

Namespace

Drupal\Core\Plugin\Context

Code

public function isSatisfiedBy(ContextInterface $context) {
  $definition = $context
    ->getContextDefinition();
  if (!$this
    ->dataTypeMatches($context)) {
    return FALSE;
  }

  // Get the value for this context, either directly if possible or by
  // introspecting the definition.
  if ($context
    ->hasContextValue()) {
    $values = [
      $context
        ->getContextData(),
    ];
  }
  elseif ($definition instanceof self) {
    $this
      ->initializeEntityContextDefinition();
    if ($this->entityContextDefinition) {
      $values = $this->entityContextDefinition
        ->getSampleValues();
    }
    else {
      $values = $definition
        ->getSampleValues();
    }
  }
  else {
    $values = [];
  }
  $validator = $this
    ->getTypedDataManager()
    ->getValidator();
  foreach ($values as $value) {
    $constraints = array_values($this
      ->getConstraintObjects());
    $violations = $validator
      ->validate($value, $constraints);
    foreach ($violations as $delta => $violation) {

      // Remove any violation that does not correspond to the constraints.
      if (!in_array($violation
        ->getConstraint(), $constraints)) {
        $violations
          ->remove($delta);
      }
    }

    // If a value has no violations then the requirement is satisfied.
    if (!$violations
      ->count()) {
      return TRUE;
    }
  }
  return FALSE;
}