Mercurial > hg > isophonics-drupal-site
comparison vendor/symfony/dependency-injection/Loader/XmlFileLoader.php @ 0:4c8ae668cc8c
Initial import (non-working)
author | Chris Cannam |
---|---|
date | Wed, 29 Nov 2017 16:09:58 +0000 |
parents | |
children | 1fec387a4317 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:4c8ae668cc8c |
---|---|
1 <?php | |
2 | |
3 /* | |
4 * This file is part of the Symfony package. | |
5 * | |
6 * (c) Fabien Potencier <fabien@symfony.com> | |
7 * | |
8 * For the full copyright and license information, please view the LICENSE | |
9 * file that was distributed with this source code. | |
10 */ | |
11 | |
12 namespace Symfony\Component\DependencyInjection\Loader; | |
13 | |
14 use Symfony\Component\Config\Resource\FileResource; | |
15 use Symfony\Component\Config\Util\XmlUtils; | |
16 use Symfony\Component\DependencyInjection\DefinitionDecorator; | |
17 use Symfony\Component\DependencyInjection\ContainerInterface; | |
18 use Symfony\Component\DependencyInjection\Alias; | |
19 use Symfony\Component\DependencyInjection\Definition; | |
20 use Symfony\Component\DependencyInjection\Reference; | |
21 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; | |
22 use Symfony\Component\DependencyInjection\Exception\RuntimeException; | |
23 use Symfony\Component\ExpressionLanguage\Expression; | |
24 | |
25 /** | |
26 * XmlFileLoader loads XML files service definitions. | |
27 * | |
28 * @author Fabien Potencier <fabien@symfony.com> | |
29 */ | |
30 class XmlFileLoader extends FileLoader | |
31 { | |
32 const NS = 'http://symfony.com/schema/dic/services'; | |
33 | |
34 /** | |
35 * {@inheritdoc} | |
36 */ | |
37 public function load($resource, $type = null) | |
38 { | |
39 $path = $this->locator->locate($resource); | |
40 | |
41 $xml = $this->parseFileToDOM($path); | |
42 | |
43 $this->container->addResource(new FileResource($path)); | |
44 | |
45 // anonymous services | |
46 $this->processAnonymousServices($xml, $path); | |
47 | |
48 // imports | |
49 $this->parseImports($xml, $path); | |
50 | |
51 // parameters | |
52 $this->parseParameters($xml); | |
53 | |
54 // extensions | |
55 $this->loadFromExtensions($xml); | |
56 | |
57 // services | |
58 $this->parseDefinitions($xml, $path); | |
59 } | |
60 | |
61 /** | |
62 * {@inheritdoc} | |
63 */ | |
64 public function supports($resource, $type = null) | |
65 { | |
66 return is_string($resource) && 'xml' === pathinfo($resource, PATHINFO_EXTENSION); | |
67 } | |
68 | |
69 /** | |
70 * Parses parameters. | |
71 * | |
72 * @param \DOMDocument $xml | |
73 */ | |
74 private function parseParameters(\DOMDocument $xml) | |
75 { | |
76 if ($parameters = $this->getChildren($xml->documentElement, 'parameters')) { | |
77 $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter')); | |
78 } | |
79 } | |
80 | |
81 /** | |
82 * Parses imports. | |
83 * | |
84 * @param \DOMDocument $xml | |
85 * @param string $file | |
86 */ | |
87 private function parseImports(\DOMDocument $xml, $file) | |
88 { | |
89 $xpath = new \DOMXPath($xml); | |
90 $xpath->registerNamespace('container', self::NS); | |
91 | |
92 if (false === $imports = $xpath->query('//container:imports/container:import')) { | |
93 return; | |
94 } | |
95 | |
96 $defaultDirectory = dirname($file); | |
97 foreach ($imports as $import) { | |
98 $this->setCurrentDir($defaultDirectory); | |
99 $this->import($import->getAttribute('resource'), null, (bool) XmlUtils::phpize($import->getAttribute('ignore-errors')), $file); | |
100 } | |
101 } | |
102 | |
103 /** | |
104 * Parses multiple definitions. | |
105 * | |
106 * @param \DOMDocument $xml | |
107 * @param string $file | |
108 */ | |
109 private function parseDefinitions(\DOMDocument $xml, $file) | |
110 { | |
111 $xpath = new \DOMXPath($xml); | |
112 $xpath->registerNamespace('container', self::NS); | |
113 | |
114 if (false === $services = $xpath->query('//container:services/container:service')) { | |
115 return; | |
116 } | |
117 | |
118 foreach ($services as $service) { | |
119 if (null !== $definition = $this->parseDefinition($service, $file)) { | |
120 $this->container->setDefinition((string) $service->getAttribute('id'), $definition); | |
121 } | |
122 } | |
123 } | |
124 | |
125 /** | |
126 * Parses an individual Definition. | |
127 * | |
128 * @param \DOMElement $service | |
129 * @param string $file | |
130 * | |
131 * @return Definition|null | |
132 */ | |
133 private function parseDefinition(\DOMElement $service, $file) | |
134 { | |
135 if ($alias = $service->getAttribute('alias')) { | |
136 $this->validateAlias($service, $file); | |
137 | |
138 $public = true; | |
139 if ($publicAttr = $service->getAttribute('public')) { | |
140 $public = XmlUtils::phpize($publicAttr); | |
141 } | |
142 $this->container->setAlias((string) $service->getAttribute('id'), new Alias($alias, $public)); | |
143 | |
144 return; | |
145 } | |
146 | |
147 if ($parent = $service->getAttribute('parent')) { | |
148 $definition = new DefinitionDecorator($parent); | |
149 } else { | |
150 $definition = new Definition(); | |
151 } | |
152 | |
153 foreach (array('class', 'shared', 'public', 'synthetic', 'lazy', 'abstract') as $key) { | |
154 if ($value = $service->getAttribute($key)) { | |
155 $method = 'set'.$key; | |
156 $definition->$method(XmlUtils::phpize($value)); | |
157 } | |
158 } | |
159 | |
160 if ($value = $service->getAttribute('autowire')) { | |
161 $definition->setAutowired(XmlUtils::phpize($value)); | |
162 } | |
163 | |
164 if ($files = $this->getChildren($service, 'file')) { | |
165 $definition->setFile($files[0]->nodeValue); | |
166 } | |
167 | |
168 if ($deprecated = $this->getChildren($service, 'deprecated')) { | |
169 $definition->setDeprecated(true, $deprecated[0]->nodeValue ?: null); | |
170 } | |
171 | |
172 $definition->setArguments($this->getArgumentsAsPhp($service, 'argument')); | |
173 $definition->setProperties($this->getArgumentsAsPhp($service, 'property')); | |
174 | |
175 if ($factories = $this->getChildren($service, 'factory')) { | |
176 $factory = $factories[0]; | |
177 if ($function = $factory->getAttribute('function')) { | |
178 $definition->setFactory($function); | |
179 } else { | |
180 $factoryService = $this->getChildren($factory, 'service'); | |
181 | |
182 if (isset($factoryService[0])) { | |
183 $class = $this->parseDefinition($factoryService[0], $file); | |
184 } elseif ($childService = $factory->getAttribute('service')) { | |
185 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE); | |
186 } else { | |
187 $class = $factory->getAttribute('class'); | |
188 } | |
189 | |
190 $definition->setFactory(array($class, $factory->getAttribute('method'))); | |
191 } | |
192 } | |
193 | |
194 if ($configurators = $this->getChildren($service, 'configurator')) { | |
195 $configurator = $configurators[0]; | |
196 if ($function = $configurator->getAttribute('function')) { | |
197 $definition->setConfigurator($function); | |
198 } else { | |
199 $configuratorService = $this->getChildren($configurator, 'service'); | |
200 | |
201 if (isset($configuratorService[0])) { | |
202 $class = $this->parseDefinition($configuratorService[0], $file); | |
203 } elseif ($childService = $configurator->getAttribute('service')) { | |
204 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE); | |
205 } else { | |
206 $class = $configurator->getAttribute('class'); | |
207 } | |
208 | |
209 $definition->setConfigurator(array($class, $configurator->getAttribute('method'))); | |
210 } | |
211 } | |
212 | |
213 foreach ($this->getChildren($service, 'call') as $call) { | |
214 $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument')); | |
215 } | |
216 | |
217 foreach ($this->getChildren($service, 'tag') as $tag) { | |
218 $parameters = array(); | |
219 foreach ($tag->attributes as $name => $node) { | |
220 if ('name' === $name) { | |
221 continue; | |
222 } | |
223 | |
224 if (false !== strpos($name, '-') && false === strpos($name, '_') && !array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) { | |
225 $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue); | |
226 } | |
227 // keep not normalized key | |
228 $parameters[$name] = XmlUtils::phpize($node->nodeValue); | |
229 } | |
230 | |
231 if ('' === $tag->getAttribute('name')) { | |
232 throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', (string) $service->getAttribute('id'), $file)); | |
233 } | |
234 | |
235 $definition->addTag($tag->getAttribute('name'), $parameters); | |
236 } | |
237 | |
238 foreach ($this->getChildren($service, 'autowiring-type') as $type) { | |
239 $definition->addAutowiringType($type->textContent); | |
240 } | |
241 | |
242 if ($value = $service->getAttribute('decorates')) { | |
243 $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null; | |
244 $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0; | |
245 $definition->setDecoratedService($value, $renameId, $priority); | |
246 } | |
247 | |
248 return $definition; | |
249 } | |
250 | |
251 /** | |
252 * Parses a XML file to a \DOMDocument. | |
253 * | |
254 * @param string $file Path to a file | |
255 * | |
256 * @return \DOMDocument | |
257 * | |
258 * @throws InvalidArgumentException When loading of XML file returns error | |
259 */ | |
260 private function parseFileToDOM($file) | |
261 { | |
262 try { | |
263 $dom = XmlUtils::loadFile($file, array($this, 'validateSchema')); | |
264 } catch (\InvalidArgumentException $e) { | |
265 throw new InvalidArgumentException(sprintf('Unable to parse file "%s".', $file), $e->getCode(), $e); | |
266 } | |
267 | |
268 $this->validateExtensions($dom, $file); | |
269 | |
270 return $dom; | |
271 } | |
272 | |
273 /** | |
274 * Processes anonymous services. | |
275 * | |
276 * @param \DOMDocument $xml | |
277 * @param string $file | |
278 */ | |
279 private function processAnonymousServices(\DOMDocument $xml, $file) | |
280 { | |
281 $definitions = array(); | |
282 $count = 0; | |
283 | |
284 $xpath = new \DOMXPath($xml); | |
285 $xpath->registerNamespace('container', self::NS); | |
286 | |
287 // anonymous services as arguments/properties | |
288 if (false !== $nodes = $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]')) { | |
289 foreach ($nodes as $node) { | |
290 // give it a unique name | |
291 $id = sprintf('%s_%d', hash('sha256', $file), ++$count); | |
292 $node->setAttribute('id', $id); | |
293 | |
294 if ($services = $this->getChildren($node, 'service')) { | |
295 $definitions[$id] = array($services[0], $file, false); | |
296 $services[0]->setAttribute('id', $id); | |
297 | |
298 // anonymous services are always private | |
299 // we could not use the constant false here, because of XML parsing | |
300 $services[0]->setAttribute('public', 'false'); | |
301 } | |
302 } | |
303 } | |
304 | |
305 // anonymous services "in the wild" | |
306 if (false !== $nodes = $xpath->query('//container:services/container:service[not(@id)]')) { | |
307 foreach ($nodes as $node) { | |
308 // give it a unique name | |
309 $id = sprintf('%s_%d', hash('sha256', $file), ++$count); | |
310 $node->setAttribute('id', $id); | |
311 $definitions[$id] = array($node, $file, true); | |
312 } | |
313 } | |
314 | |
315 // resolve definitions | |
316 krsort($definitions); | |
317 foreach ($definitions as $id => list($domElement, $file, $wild)) { | |
318 if (null !== $definition = $this->parseDefinition($domElement, $file)) { | |
319 $this->container->setDefinition($id, $definition); | |
320 } | |
321 | |
322 if (true === $wild) { | |
323 $tmpDomElement = new \DOMElement('_services', null, self::NS); | |
324 $domElement->parentNode->replaceChild($tmpDomElement, $domElement); | |
325 $tmpDomElement->setAttribute('id', $id); | |
326 } else { | |
327 $domElement->parentNode->removeChild($domElement); | |
328 } | |
329 } | |
330 } | |
331 | |
332 /** | |
333 * Returns arguments as valid php types. | |
334 * | |
335 * @param \DOMElement $node | |
336 * @param string $name | |
337 * @param bool $lowercase | |
338 * | |
339 * @return mixed | |
340 */ | |
341 private function getArgumentsAsPhp(\DOMElement $node, $name, $lowercase = true) | |
342 { | |
343 $arguments = array(); | |
344 foreach ($this->getChildren($node, $name) as $arg) { | |
345 if ($arg->hasAttribute('name')) { | |
346 $arg->setAttribute('key', $arg->getAttribute('name')); | |
347 } | |
348 | |
349 // this is used by DefinitionDecorator to overwrite a specific | |
350 // argument of the parent definition | |
351 if ($arg->hasAttribute('index')) { | |
352 $key = 'index_'.$arg->getAttribute('index'); | |
353 } elseif (!$arg->hasAttribute('key')) { | |
354 // Append an empty argument, then fetch its key to overwrite it later | |
355 $arguments[] = null; | |
356 $keys = array_keys($arguments); | |
357 $key = array_pop($keys); | |
358 } else { | |
359 $key = $arg->getAttribute('key'); | |
360 | |
361 // parameter keys are case insensitive | |
362 if ('parameter' == $name && $lowercase) { | |
363 $key = strtolower($key); | |
364 } | |
365 } | |
366 | |
367 switch ($arg->getAttribute('type')) { | |
368 case 'service': | |
369 $onInvalid = $arg->getAttribute('on-invalid'); | |
370 $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE; | |
371 if ('ignore' == $onInvalid) { | |
372 $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE; | |
373 } elseif ('null' == $onInvalid) { | |
374 $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE; | |
375 } | |
376 | |
377 $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior); | |
378 break; | |
379 case 'expression': | |
380 $arguments[$key] = new Expression($arg->nodeValue); | |
381 break; | |
382 case 'collection': | |
383 $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, false); | |
384 break; | |
385 case 'string': | |
386 $arguments[$key] = $arg->nodeValue; | |
387 break; | |
388 case 'constant': | |
389 $arguments[$key] = constant(trim($arg->nodeValue)); | |
390 break; | |
391 default: | |
392 $arguments[$key] = XmlUtils::phpize($arg->nodeValue); | |
393 } | |
394 } | |
395 | |
396 return $arguments; | |
397 } | |
398 | |
399 /** | |
400 * Get child elements by name. | |
401 * | |
402 * @param \DOMNode $node | |
403 * @param mixed $name | |
404 * | |
405 * @return array | |
406 */ | |
407 private function getChildren(\DOMNode $node, $name) | |
408 { | |
409 $children = array(); | |
410 foreach ($node->childNodes as $child) { | |
411 if ($child instanceof \DOMElement && $child->localName === $name && $child->namespaceURI === self::NS) { | |
412 $children[] = $child; | |
413 } | |
414 } | |
415 | |
416 return $children; | |
417 } | |
418 | |
419 /** | |
420 * Validates a documents XML schema. | |
421 * | |
422 * @param \DOMDocument $dom | |
423 * | |
424 * @return bool | |
425 * | |
426 * @throws RuntimeException When extension references a non-existent XSD file | |
427 */ | |
428 public function validateSchema(\DOMDocument $dom) | |
429 { | |
430 $schemaLocations = array('http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')); | |
431 | |
432 if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) { | |
433 $items = preg_split('/\s+/', $element); | |
434 for ($i = 0, $nb = count($items); $i < $nb; $i += 2) { | |
435 if (!$this->container->hasExtension($items[$i])) { | |
436 continue; | |
437 } | |
438 | |
439 if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) { | |
440 $path = str_replace($extension->getNamespace(), str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]); | |
441 | |
442 if (!is_file($path)) { | |
443 throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', get_class($extension), $path)); | |
444 } | |
445 | |
446 $schemaLocations[$items[$i]] = $path; | |
447 } | |
448 } | |
449 } | |
450 | |
451 $tmpfiles = array(); | |
452 $imports = ''; | |
453 foreach ($schemaLocations as $namespace => $location) { | |
454 $parts = explode('/', $location); | |
455 if (0 === stripos($location, 'phar://')) { | |
456 $tmpfile = tempnam(sys_get_temp_dir(), 'sf2'); | |
457 if ($tmpfile) { | |
458 copy($location, $tmpfile); | |
459 $tmpfiles[] = $tmpfile; | |
460 $parts = explode('/', str_replace('\\', '/', $tmpfile)); | |
461 } | |
462 } | |
463 $drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : ''; | |
464 $location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts)); | |
465 | |
466 $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location); | |
467 } | |
468 | |
469 $source = <<<EOF | |
470 <?xml version="1.0" encoding="utf-8" ?> | |
471 <xsd:schema xmlns="http://symfony.com/schema" | |
472 xmlns:xsd="http://www.w3.org/2001/XMLSchema" | |
473 targetNamespace="http://symfony.com/schema" | |
474 elementFormDefault="qualified"> | |
475 | |
476 <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/> | |
477 $imports | |
478 </xsd:schema> | |
479 EOF | |
480 ; | |
481 | |
482 $disableEntities = libxml_disable_entity_loader(false); | |
483 $valid = @$dom->schemaValidateSource($source); | |
484 libxml_disable_entity_loader($disableEntities); | |
485 | |
486 foreach ($tmpfiles as $tmpfile) { | |
487 @unlink($tmpfile); | |
488 } | |
489 | |
490 return $valid; | |
491 } | |
492 | |
493 /** | |
494 * Validates an alias. | |
495 * | |
496 * @param \DOMElement $alias | |
497 * @param string $file | |
498 */ | |
499 private function validateAlias(\DOMElement $alias, $file) | |
500 { | |
501 foreach ($alias->attributes as $name => $node) { | |
502 if (!in_array($name, array('alias', 'id', 'public'))) { | |
503 @trigger_error(sprintf('Using the attribute "%s" is deprecated for the service "%s" which is defined as an alias in "%s". Allowed attributes for service aliases are "alias", "id" and "public". The XmlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported attributes.', $name, $alias->getAttribute('id'), $file), E_USER_DEPRECATED); | |
504 } | |
505 } | |
506 | |
507 foreach ($alias->childNodes as $child) { | |
508 if ($child instanceof \DOMElement && $child->namespaceURI === self::NS) { | |
509 @trigger_error(sprintf('Using the element "%s" is deprecated for the service "%s" which is defined as an alias in "%s". The XmlFileLoader will raise an exception in Symfony 4.0, instead of silently ignoring unsupported elements.', $child->localName, $alias->getAttribute('id'), $file), E_USER_DEPRECATED); | |
510 } | |
511 } | |
512 } | |
513 | |
514 /** | |
515 * Validates an extension. | |
516 * | |
517 * @param \DOMDocument $dom | |
518 * @param string $file | |
519 * | |
520 * @throws InvalidArgumentException When no extension is found corresponding to a tag | |
521 */ | |
522 private function validateExtensions(\DOMDocument $dom, $file) | |
523 { | |
524 foreach ($dom->documentElement->childNodes as $node) { | |
525 if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) { | |
526 continue; | |
527 } | |
528 | |
529 // can it be handled by an extension? | |
530 if (!$this->container->hasExtension($node->namespaceURI)) { | |
531 $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions())); | |
532 throw new InvalidArgumentException(sprintf( | |
533 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', | |
534 $node->tagName, | |
535 $file, | |
536 $node->namespaceURI, | |
537 $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none' | |
538 )); | |
539 } | |
540 } | |
541 } | |
542 | |
543 /** | |
544 * Loads from an extension. | |
545 * | |
546 * @param \DOMDocument $xml | |
547 */ | |
548 private function loadFromExtensions(\DOMDocument $xml) | |
549 { | |
550 foreach ($xml->documentElement->childNodes as $node) { | |
551 if (!$node instanceof \DOMElement || $node->namespaceURI === self::NS) { | |
552 continue; | |
553 } | |
554 | |
555 $values = static::convertDomElementToArray($node); | |
556 if (!is_array($values)) { | |
557 $values = array(); | |
558 } | |
559 | |
560 $this->container->loadFromExtension($node->namespaceURI, $values); | |
561 } | |
562 } | |
563 | |
564 /** | |
565 * Converts a \DomElement object to a PHP array. | |
566 * | |
567 * The following rules applies during the conversion: | |
568 * | |
569 * * Each tag is converted to a key value or an array | |
570 * if there is more than one "value" | |
571 * | |
572 * * The content of a tag is set under a "value" key (<foo>bar</foo>) | |
573 * if the tag also has some nested tags | |
574 * | |
575 * * The attributes are converted to keys (<foo foo="bar"/>) | |
576 * | |
577 * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>) | |
578 * | |
579 * @param \DomElement $element A \DomElement instance | |
580 * | |
581 * @return array A PHP array | |
582 */ | |
583 public static function convertDomElementToArray(\DOMElement $element) | |
584 { | |
585 return XmlUtils::convertDomElementToArray($element); | |
586 } | |
587 } |