Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / lib / Drupal / Component / Plugin / Context / Context.php
1 <?php
2
3 namespace Drupal\Component\Plugin\Context;
4
5 use Drupal\Component\Plugin\Exception\ContextException;
6 use Symfony\Component\Validator\Constraints\Type;
7 use Symfony\Component\Validator\Validation;
8
9 /**
10  * A generic context class for wrapping data a plugin needs to operate.
11  */
12 class Context implements ContextInterface {
13
14   /**
15    * The value of the context.
16    *
17    * @var mixed
18    */
19   protected $contextValue;
20
21   /**
22    * The definition to which a context must conform.
23    *
24    * @var \Drupal\Component\Plugin\Context\ContextDefinitionInterface
25    */
26   protected $contextDefinition;
27
28   /**
29    * Create a context object.
30    *
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.
35    */
36   public function __construct(ContextDefinitionInterface $context_definition, $context_value = NULL) {
37     $this->contextDefinition = $context_definition;
38     $this->contextValue = $context_value;
39   }
40
41   /**
42    * {@inheritdoc}
43    */
44   public function getContextValue() {
45     // Support optional contexts.
46     if (!isset($this->contextValue)) {
47       $definition = $this->getContextDefinition();
48       $default_value = $definition->getDefaultValue();
49
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));
53       }
54       // Keep the default value here so that subsequent calls don't have to look
55       // it up again.
56       $this->contextValue = $default_value;
57     }
58     return $this->contextValue;
59   }
60
61   /**
62    * {@inheritdoc}
63    */
64   public function hasContextValue() {
65     return (bool) $this->contextValue || (bool) $this->getContextDefinition()->getDefaultValue();
66   }
67
68   /**
69    * {@inheritdoc}
70    */
71   public function getContextDefinition() {
72     return $this->contextDefinition;
73   }
74
75   /**
76    * {@inheritdoc}
77    */
78   public function getConstraints() {
79     if (empty($this->contextDefinition['class'])) {
80       throw new ContextException("An error was encountered while trying to validate the context.");
81     }
82     return [new Type($this->contextDefinition['class'])];
83   }
84
85   /**
86    * {@inheritdoc}
87    */
88   public function validate() {
89     $validator = Validation::createValidatorBuilder()
90       ->getValidator();
91     return $validator->validateValue($this->getContextValue(), $this->getConstraints());
92   }
93
94 }