Version 1
[yaffs-website] / web / core / lib / Drupal / Core / TypedData / TypedDataManager.php
1 <?php
2
3 namespace Drupal\Core\TypedData;
4
5 use Drupal\Component\Plugin\Exception\PluginException;
6 use Drupal\Core\Cache\CacheBackendInterface;
7 use Drupal\Core\DependencyInjection\ClassResolverInterface;
8 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
9 use Drupal\Core\Extension\ModuleHandlerInterface;
10 use Drupal\Core\Plugin\DefaultPluginManager;
11 use Drupal\Core\TypedData\Validation\ExecutionContextFactory;
12 use Drupal\Core\TypedData\Validation\RecursiveValidator;
13 use Drupal\Core\Validation\ConstraintManager;
14 use Drupal\Core\Validation\ConstraintValidatorFactory;
15 use Drupal\Core\Validation\DrupalTranslator;
16 use Symfony\Component\Validator\Validator\ValidatorInterface;
17
18 /**
19  * Manages data type plugins.
20  */
21 class TypedDataManager extends DefaultPluginManager implements TypedDataManagerInterface {
22   use DependencySerializationTrait;
23
24   /**
25    * The validator used for validating typed data.
26    *
27    * @var \Symfony\Component\Validator\Validator\ValidatorInterface
28    */
29   protected $validator;
30
31   /**
32    * The validation constraint manager to use for instantiating constraints.
33    *
34    * @var \Drupal\Core\Validation\ConstraintManager
35    */
36   protected $constraintManager;
37
38   /**
39    * An array of typed data property prototypes.
40    *
41    * @var array
42    */
43   protected $prototypes = [];
44
45   /**
46    * The class resolver.
47    *
48    * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
49    */
50   protected $classResolver;
51
52   /**
53    * Constructs a new TypedDataManager.
54    *
55    * @param \Traversable $namespaces
56    *   An object that implements \Traversable which contains the root paths
57    *   keyed by the corresponding namespace to look for plugin implementations.
58    * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
59    *   Cache backend instance to use.
60    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
61    *   The module handler.
62    * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
63    *   The class resolver.
64    */
65   public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ClassResolverInterface $class_resolver) {
66     $this->alterInfo('data_type_info');
67     $this->setCacheBackend($cache_backend, 'typed_data_types_plugins');
68     $this->classResolver = $class_resolver;
69
70     parent::__construct('Plugin/DataType', $namespaces, $module_handler, NULL, 'Drupal\Core\TypedData\Annotation\DataType');
71   }
72
73   /**
74    * {@inheritdoc}
75    */
76   public function createInstance($data_type, array $configuration = []) {
77     $data_definition = $configuration['data_definition'];
78     $type_definition = $this->getDefinition($data_type);
79
80     if (!isset($type_definition)) {
81       throw new \InvalidArgumentException("Invalid data type '$data_type' has been given");
82     }
83
84     // Allow per-data definition overrides of the used classes, i.e. take over
85     // classes specified in the type definition.
86     $class = $data_definition->getClass();
87
88     if (!isset($class)) {
89       throw new PluginException(sprintf('The plugin (%s) did not specify an instance class.', $data_type));
90     }
91     $typed_data = $class::createInstance($data_definition, $configuration['name'], $configuration['parent']);
92     $typed_data->setTypedDataManager($this);
93     return $typed_data;
94   }
95
96   /**
97    * {@inheritdoc}
98    */
99   public function create(DataDefinitionInterface $definition, $value = NULL, $name = NULL, $parent = NULL) {
100     $typed_data = $this->createInstance($definition->getDataType(), [
101       'data_definition' => $definition,
102       'name' => $name,
103       'parent' => $parent,
104     ]);
105     if (isset($value)) {
106       $typed_data->setValue($value, FALSE);
107     }
108     return $typed_data;
109   }
110
111   /**
112    * {@inheritdoc}
113    */
114   public function createDataDefinition($data_type) {
115     $type_definition = $this->getDefinition($data_type);
116     if (!isset($type_definition)) {
117       throw new \InvalidArgumentException("Invalid data type '$data_type' has been given");
118     }
119     $class = $type_definition['definition_class'];
120     return $class::createFromDataType($data_type);
121   }
122
123   /**
124    * {@inheritdoc}
125    */
126   public function createListDataDefinition($item_type) {
127     $type_definition = $this->getDefinition($item_type);
128     if (!isset($type_definition)) {
129       throw new \InvalidArgumentException("Invalid data type '$item_type' has been given");
130     }
131     $class = $type_definition['list_definition_class'];
132     return $class::createFromItemType($item_type);
133   }
134
135   /**
136    * {@inheritdoc}
137    */
138   public function getInstance(array $options) {
139     return $this->getPropertyInstance($options['object'], $options['property'], $options['value']);
140   }
141
142   /**
143    * {@inheritdoc}
144    */
145   public function getPropertyInstance(TypedDataInterface $object, $property_name, $value = NULL) {
146     // For performance, try to reuse existing prototypes instead of
147     // constructing new objects when possible. A prototype is reused when
148     // creating a data object:
149     // - for a similar root object (same data type and settings),
150     // - at the same property path under that root object.
151     $root_definition = $object->getRoot()->getDataDefinition();
152     // If the root object is a list, we want to look at the data type and the
153     // settings of its item definition.
154     if ($root_definition instanceof ListDataDefinition) {
155       $root_definition = $root_definition->getItemDefinition();
156     }
157
158     // Root data type and settings.
159     $parts[] = $root_definition->getDataType();
160     if ($settings = $root_definition->getSettings()) {
161       // Include the settings serialized as JSON as part of the key. The JSON is
162       // a shorter string than the serialized form, so array access is faster.
163       $parts[] = json_encode($settings);
164     }
165     // Property path for the requested data object. When creating a list item,
166     // use 0 in the key as all items look the same.
167     $parts[] = $object->getPropertyPath() . '.' . (is_numeric($property_name) ? 0 : $property_name);
168     $key = implode(':', $parts);
169
170     // Create the prototype if needed.
171     if (!isset($this->prototypes[$key])) {
172       // Fetch the data definition for the child object from the parent.
173       if ($object instanceof ComplexDataInterface) {
174         $definition = $object->getDataDefinition()->getPropertyDefinition($property_name);
175       }
176       elseif ($object instanceof ListInterface) {
177         $definition = $object->getItemDefinition();
178       }
179       else {
180         throw new \InvalidArgumentException("The passed object has to either implement the ComplexDataInterface or the ListInterface.");
181       }
182       if (!$definition) {
183         throw new \InvalidArgumentException("Property $property_name is unknown.");
184       }
185       // Create the prototype without any value, but with initial parenting
186       // so that constructors can set up the objects correclty.
187       $this->prototypes[$key] = $this->create($definition, NULL, $property_name, $object);
188     }
189
190     // Clone the prototype, update its parenting information, and assign the
191     // value.
192     $property = clone $this->prototypes[$key];
193     $property->setContext($property_name, $object);
194     if (isset($value)) {
195       $property->setValue($value, FALSE);
196     }
197     return $property;
198   }
199
200   /**
201    * Sets the validator for validating typed data.
202    *
203    * @param \Symfony\Component\Validator\Validator\ValidatorInterface $validator
204    *   The validator object to set.
205    */
206   public function setValidator(ValidatorInterface $validator) {
207     $this->validator = $validator;
208   }
209
210   /**
211    * {@inheritdoc}
212    */
213   public function getValidator() {
214     if (!isset($this->validator)) {
215       $this->validator = new RecursiveValidator(
216         new ExecutionContextFactory(new DrupalTranslator()),
217         new ConstraintValidatorFactory($this->classResolver),
218         $this
219       );
220     }
221     return $this->validator;
222   }
223
224   /**
225    * {@inheritdoc}
226    */
227   public function setValidationConstraintManager(ConstraintManager $constraintManager) {
228     $this->constraintManager = $constraintManager;
229   }
230
231   /**
232    * {@inheritdoc}
233    */
234   public function getValidationConstraintManager() {
235     return $this->constraintManager;
236   }
237
238   /**
239    * {@inheritdoc}
240    */
241   public function getDefaultConstraints(DataDefinitionInterface $definition) {
242     $constraints = [];
243     $type_definition = $this->getDefinition($definition->getDataType());
244     // Auto-generate a constraint for data types implementing a primitive
245     // interface.
246     if (is_subclass_of($type_definition['class'], '\Drupal\Core\TypedData\PrimitiveInterface')) {
247       $constraints['PrimitiveType'] = [];
248     }
249     // Add in constraints specified by the data type.
250     if (isset($type_definition['constraints'])) {
251       $constraints += $type_definition['constraints'];
252     }
253     // Add the NotNull constraint for required data.
254     if ($definition->isRequired()) {
255       $constraints['NotNull'] = [];
256     }
257     // Check if the class provides allowed values.
258     if (is_subclass_of($definition->getClass(), 'Drupal\Core\TypedData\OptionsProviderInterface')) {
259       $constraints['AllowedValues'] = [];
260     }
261     return $constraints;
262   }
263
264   /**
265    * {@inheritdoc}
266    */
267   public function clearCachedDefinitions() {
268     parent::clearCachedDefinitions();
269     $this->prototypes = [];
270   }
271
272   /**
273    * {@inheritdoc}
274    */
275   public function getCanonicalRepresentation(TypedDataInterface $data) {
276     $data_definition = $data->getDataDefinition();
277     // In case a list is passed, respect the 'wrapped' key of its data type.
278     if ($data_definition instanceof ListDataDefinitionInterface) {
279       $data_definition = $data_definition->getItemDefinition();
280     }
281     // Get the plugin definition of the used data type.
282     $type_definition = $this->getDefinition($data_definition->getDataType());
283     if (!empty($type_definition['unwrap_for_canonical_representation'])) {
284       return $data->getValue();
285     }
286     return $data;
287   }
288
289 }