You are here

public function ContextDefinition::__construct in Drupal 9

Same name in this branch
  1. 9 core/lib/Drupal/Core/Annotation/ContextDefinition.php \Drupal\Core\Annotation\ContextDefinition::__construct()
  2. 9 core/lib/Drupal/Core/Plugin/Context/ContextDefinition.php \Drupal\Core\Plugin\Context\ContextDefinition::__construct()
Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Annotation/ContextDefinition.php \Drupal\Core\Annotation\ContextDefinition::__construct()

Constructs a new context definition object.

Parameters

array $values: An associative array with the following keys:

  • value: The required data type.
  • label: (optional) The UI label of this context definition.
  • required: (optional) Whether the context definition is required.
  • multiple: (optional) Whether the context definition is multivalue.
  • description: (optional) The UI description of this context definition.
  • default_value: (optional) The default value in case the underlying value is not set.
  • class: (optional) A custom ContextDefinitionInterface class.

Throws

\Exception Thrown when the class key is specified with a non ContextDefinitionInterface implementing class.

Overrides Plugin::__construct

File

core/lib/Drupal/Core/Annotation/ContextDefinition.php, line 98

Class

ContextDefinition
Defines a context definition annotation object.

Namespace

Drupal\Core\Annotation

Code

public function __construct(array $values) {
  $values += [
    'required' => TRUE,
    'multiple' => FALSE,
    'default_value' => NULL,
  ];

  // Annotation classes extract data from passed annotation classes directly
  // used in the classes they pass to.
  foreach ([
    'label',
    'description',
  ] as $key) {

    // @todo Remove this workaround in https://www.drupal.org/node/2362727.
    if (isset($values[$key]) && $values[$key] instanceof Translation) {
      $values[$key] = (string) $values[$key]
        ->get();
    }
    else {
      $values[$key] = NULL;
    }
  }
  if (isset($values['class']) && !in_array('Drupal\\Core\\Plugin\\Context\\ContextDefinitionInterface', class_implements($values['class']))) {
    throw new \Exception('ContextDefinition class must implement \\Drupal\\Core\\Plugin\\Context\\ContextDefinitionInterface.');
  }
  $class = $this
    ->getDefinitionClass($values);
  $this->definition = new $class($values['value'], $values['label'], $values['required'], $values['multiple'], $values['description'], $values['default_value']);
  if (isset($values['constraints'])) {
    foreach ($values['constraints'] as $constraint_name => $options) {
      $this->definition
        ->addConstraint($constraint_name, $options);
    }
  }
}