3 namespace Drupal\Component\Plugin\Context;
5 use Drupal\Component\Plugin\Exception\ContextException;
6 use Symfony\Component\Validator\Constraints\Type;
7 use Symfony\Component\Validator\Validation;
10 * A generic context class for wrapping data a plugin needs to operate.
12 class Context implements ContextInterface {
15 * The value of the context.
19 protected $contextValue;
22 * The definition to which a context must conform.
24 * @var \Drupal\Component\Plugin\Context\ContextDefinitionInterface
26 protected $contextDefinition;
29 * Create a context object.
31 * @param \Drupal\Component\Plugin\Context\ContextDefinitionInterface $context_definition
32 * The context definition.
33 * @param mixed|null $context_value
34 * The value of the context.
36 public function __construct(ContextDefinitionInterface $context_definition, $context_value = NULL) {
37 $this->contextDefinition = $context_definition;
38 $this->contextValue = $context_value;
44 public function getContextValue() {
45 // Support optional contexts.
46 if (!isset($this->contextValue)) {
47 $definition = $this->getContextDefinition();
48 $default_value = $definition->getDefaultValue();
50 if (!isset($default_value) && $definition->isRequired()) {
51 $type = $definition->getDataType();
52 throw new ContextException(sprintf("The %s context is required and not present.", $type));
54 // Keep the default value here so that subsequent calls don't have to look
56 $this->contextValue = $default_value;
58 return $this->contextValue;
64 public function hasContextValue() {
65 return (bool) $this->contextValue || (bool) $this->getContextDefinition()->getDefaultValue();
71 public function getContextDefinition() {
72 return $this->contextDefinition;
78 public function getConstraints() {
79 if (empty($this->contextDefinition['class'])) {
80 throw new ContextException("An error was encountered while trying to validate the context.");
82 return [new Type($this->contextDefinition['class'])];
88 public function validate() {
89 $validator = Validation::createValidatorBuilder()
91 return $validator->validateValue($this->getContextValue(), $this->getConstraints());