Version 1
[yaffs-website] / web / core / lib / Drupal / Core / DependencyInjection / YamlFileLoader.php
1 <?php
2 // @codingStandardsIgnoreFile
3
4 namespace Drupal\Core\DependencyInjection;
5
6 use Drupal\Component\FileCache\FileCacheFactory;
7 use Drupal\Core\Serialization\Yaml;
8 use Symfony\Component\DependencyInjection\Alias;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Symfony\Component\DependencyInjection\Definition;
11 use Symfony\Component\DependencyInjection\DefinitionDecorator;
12 use Symfony\Component\DependencyInjection\Reference;
13 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
14
15 /**
16  * YamlFileLoader loads YAML files service definitions.
17  *
18  * Drupal does not use Symfony's Config component, and Symfony's dependency on
19  * it cannot be removed easily. Therefore, this is a partial but mostly literal
20  * copy of upstream, which does not depend on the Config component.
21  *
22  * @see \Symfony\Component\DependencyInjection\Loader\YamlFileLoader
23  * @see https://github.com/symfony/symfony/pull/10920
24  *
25  * NOTE: 98% of this code is a literal copy of Symfony's YamlFileLoader.
26  *
27  * This file does NOT follow Drupal coding standards, so as to simplify future
28  * synchronizations.
29  */
30 class YamlFileLoader
31 {
32
33     /**
34      * @var \Drupal\Core\DependencyInjection\ContainerBuilder $container
35      */
36     protected $container;
37
38     /**
39      * File cache object.
40      *
41      * @var \Drupal\Component\FileCache\FileCacheInterface
42      */
43     protected $fileCache;
44
45
46     public function __construct(ContainerBuilder $container)
47     {
48         $this->container = $container;
49         $this->fileCache = FileCacheFactory::get('container_yaml_loader');
50     }
51
52     /**
53      * Loads a Yaml file.
54      *
55      * @param mixed $file
56      *   The resource
57      */
58     public function load($file)
59     {
60         // Load from the file cache, fall back to loading the file.
61         $content = $this->fileCache->get($file);
62         if (!$content) {
63             $content = $this->loadFile($file);
64             $this->fileCache->set($file, $content);
65         }
66
67         // Not supported.
68         //$this->container->addResource(new FileResource($path));
69
70         // empty file
71         if (null === $content) {
72             return;
73         }
74
75         // imports
76         // Not supported.
77         //$this->parseImports($content, $file);
78
79         // parameters
80         if (isset($content['parameters'])) {
81             if (!is_array($content['parameters'])) {
82                 throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your YAML syntax.', $file));
83             }
84
85             foreach ($content['parameters'] as $key => $value) {
86                 $this->container->setParameter($key, $this->resolveServices($value));
87             }
88         }
89
90         // extensions
91         // Not supported.
92         //$this->loadFromExtensions($content);
93
94         // services
95         $this->parseDefinitions($content, $file);
96     }
97
98     /**
99      * Parses definitions
100      *
101      * @param array $content
102      * @param string $file
103      */
104     private function parseDefinitions($content, $file)
105     {
106         if (!isset($content['services'])) {
107             return;
108         }
109
110         if (!is_array($content['services'])) {
111             throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $file));
112         }
113
114         // Some extensions split up their dependencies into multiple files.
115         if (isset($content['_provider'])) {
116             $provider = $content['_provider'];
117         }
118         else {
119             $basename = basename($file);
120             list($provider, ) = explode('.', $basename, 2);
121         }
122         foreach ($content['services'] as $id => $service) {
123             $service['tags'][] = ['name' => '_provider', 'provider' => $provider];
124             $this->parseDefinition($id, $service, $file);
125         }
126     }
127
128     /**
129      * Parses a definition.
130      *
131      * @param string $id
132      * @param array $service
133      * @param string $file
134      *
135      * @throws InvalidArgumentException
136      *   When tags are invalid.
137      */
138     private function parseDefinition($id, $service, $file)
139     {
140         if (is_string($service) && 0 === strpos($service, '@')) {
141             $this->container->setAlias($id, substr($service, 1));
142
143             return;
144         }
145
146         if (!is_array($service)) {
147             throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but %s found for service "%s" in %s. Check your YAML syntax.', gettype($service), $id, $file));
148         }
149
150         if (isset($service['alias'])) {
151             $public = !array_key_exists('public', $service) || (bool) $service['public'];
152             $this->container->setAlias($id, new Alias($service['alias'], $public));
153
154             return;
155         }
156
157         if (isset($service['parent'])) {
158             $definition = new DefinitionDecorator($service['parent']);
159         } else {
160             $definition = new Definition();
161         }
162
163         if (isset($service['class'])) {
164             $definition->setClass($service['class']);
165         }
166
167         if (isset($service['shared'])) {
168             $definition->setShared($service['shared']);
169         }
170
171         if (isset($service['scope'])) {
172             if ('request' !== $id) {
173                 @trigger_error(sprintf('The "scope" key of service "%s" in file "%s" is deprecated since version 2.8 and will be removed in 3.0.', $id, $file), E_USER_DEPRECATED);
174             }
175             $definition->setScope($service['scope'], false);
176         }
177
178         if (isset($service['synthetic'])) {
179             $definition->setSynthetic($service['synthetic']);
180         }
181
182         if (isset($service['synchronized'])) {
183             $definition->setSynchronized($service['synchronized'], 'request' !== $id);
184         }
185
186         if (isset($service['lazy'])) {
187             $definition->setLazy($service['lazy']);
188         }
189
190         if (isset($service['public'])) {
191             $definition->setPublic($service['public']);
192         }
193
194         if (isset($service['abstract'])) {
195             $definition->setAbstract($service['abstract']);
196         }
197
198         if (array_key_exists('deprecated', $service)) {
199             $definition->setDeprecated(true, $service['deprecated']);
200         }
201
202         if (isset($service['factory'])) {
203             if (is_string($service['factory'])) {
204                 if (strpos($service['factory'], ':') !== false && strpos($service['factory'], '::') === false) {
205                     $parts = explode(':', $service['factory']);
206                     $definition->setFactory(array($this->resolveServices('@'.$parts[0]), $parts[1]));
207                 } else {
208                     $definition->setFactory($service['factory']);
209                 }
210             } else {
211                 $definition->setFactory(array($this->resolveServices($service['factory'][0]), $service['factory'][1]));
212             }
213         }
214
215         if (isset($service['factory_class'])) {
216             $definition->setFactoryClass($service['factory_class']);
217         }
218
219         if (isset($service['factory_method'])) {
220             $definition->setFactoryMethod($service['factory_method']);
221         }
222
223         if (isset($service['factory_service'])) {
224             $definition->setFactoryService($service['factory_service']);
225         }
226
227         if (isset($service['file'])) {
228             $definition->setFile($service['file']);
229         }
230
231         if (isset($service['arguments'])) {
232             $definition->setArguments($this->resolveServices($service['arguments']));
233         }
234
235         if (isset($service['properties'])) {
236             $definition->setProperties($this->resolveServices($service['properties']));
237         }
238
239         if (isset($service['configurator'])) {
240             if (is_string($service['configurator'])) {
241                 $definition->setConfigurator($service['configurator']);
242             } else {
243                 $definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1]));
244             }
245         }
246
247         if (isset($service['calls'])) {
248             if (!is_array($service['calls'])) {
249                 throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
250             }
251
252             foreach ($service['calls'] as $call) {
253                 if (isset($call['method'])) {
254                     $method = $call['method'];
255                     $args = isset($call['arguments']) ? $this->resolveServices($call['arguments']) : array();
256                 } else {
257                     $method = $call[0];
258                     $args = isset($call[1]) ? $this->resolveServices($call[1]) : array();
259                 }
260
261                 $definition->addMethodCall($method, $args);
262             }
263         }
264
265         if (isset($service['tags'])) {
266             if (!is_array($service['tags'])) {
267                 throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
268             }
269
270             foreach ($service['tags'] as $tag) {
271                 if (!is_array($tag)) {
272                     throw new InvalidArgumentException(sprintf('A "tags" entry must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
273                 }
274
275                 if (!isset($tag['name'])) {
276                     throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file));
277                 }
278
279                 $name = $tag['name'];
280                 unset($tag['name']);
281
282                 foreach ($tag as $attribute => $value) {
283                     if (!is_scalar($value) && null !== $value) {
284                         throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in %s. Check your YAML syntax.', $id, $name, $attribute, $file));
285                     }
286                 }
287
288                 $definition->addTag($name, $tag);
289             }
290         }
291
292         if (isset($service['decorates'])) {
293             $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
294             $priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0;
295             $definition->setDecoratedService($service['decorates'], $renameId, $priority);
296         }
297
298         if (isset($service['autowire'])) {
299             $definition->setAutowired($service['autowire']);
300         }
301
302         if (isset($service['autowiring_types'])) {
303             if (is_string($service['autowiring_types'])) {
304                 $definition->addAutowiringType($service['autowiring_types']);
305             } else {
306                 if (!is_array($service['autowiring_types'])) {
307                     throw new InvalidArgumentException(sprintf('Parameter "autowiring_types" must be a string or an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
308                 }
309
310                 foreach ($service['autowiring_types'] as $autowiringType) {
311                     if (!is_string($autowiringType)) {
312                         throw new InvalidArgumentException(sprintf('A "autowiring_types" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
313                     }
314
315                     $definition->addAutowiringType($autowiringType);
316                 }
317             }
318         }
319
320         $this->container->setDefinition($id, $definition);
321     }
322
323     /**
324      * Loads a YAML file.
325      *
326      * @param string $file
327      *
328      * @return array The file content
329      *
330      * @throws InvalidArgumentException
331      *   When the given file is not a local file or when it does not exist.
332      */
333     protected function loadFile($file)
334     {
335         if (!stream_is_local($file)) {
336             throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
337         }
338
339         if (!file_exists($file)) {
340             throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file));
341         }
342
343         return $this->validate(Yaml::decode(file_get_contents($file)), $file);
344     }
345
346     /**
347      * Validates a YAML file.
348      *
349      * @param mixed $content
350      * @param string $file
351      *
352      * @return array
353      *
354      * @throws InvalidArgumentException
355      *   When service file is not valid.
356      */
357     private function validate($content, $file)
358     {
359         if (null === $content) {
360             return $content;
361         }
362
363         if (!is_array($content)) {
364             throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
365         }
366
367         if ($invalid_keys = array_diff_key($content, array('parameters' => 1, 'services' => 1))) {
368             throw new InvalidArgumentException(sprintf('The service file "%s" is not valid: it contains invalid keys %s. Services have to be added under "services" and Parameters under "parameters".', $file, $invalid_keys));
369         }
370
371         return $content;
372     }
373
374     /**
375      * Resolves services.
376      *
377      * @param string|array $value
378      *
379      * @return array|string|Reference
380      */
381     private function resolveServices($value)
382     {
383         if (is_array($value)) {
384             $value = array_map(array($this, 'resolveServices'), $value);
385         } elseif (is_string($value) &&  0 === strpos($value, '@=')) {
386             // Not supported.
387             //return new Expression(substr($value, 2));
388             throw new InvalidArgumentException(sprintf("'%s' is an Expression, but expressions are not supported.", $value));
389         } elseif (is_string($value) &&  0 === strpos($value, '@')) {
390             if (0 === strpos($value, '@@')) {
391                 $value = substr($value, 1);
392                 $invalidBehavior = null;
393             } elseif (0 === strpos($value, '@?')) {
394                 $value = substr($value, 2);
395                 $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
396             } else {
397                 $value = substr($value, 1);
398                 $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
399             }
400
401             if ('=' === substr($value, -1)) {
402                 $value = substr($value, 0, -1);
403                 $strict = false;
404             } else {
405                 $strict = true;
406             }
407
408             if (null !== $invalidBehavior) {
409                 $value = new Reference($value, $invalidBehavior, $strict);
410             }
411         }
412
413         return $value;
414     }
415
416 }