annotate vendor/symfony/dependency-injection/Loader/XmlFileLoader.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Symfony\Component\DependencyInjection\Loader;
Chris@0 13
Chris@0 14 use Symfony\Component\Config\Util\XmlUtils;
Chris@0 15 use Symfony\Component\DependencyInjection\Alias;
Chris@14 16 use Symfony\Component\DependencyInjection\Argument\BoundArgument;
Chris@14 17 use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
Chris@17 18 use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
Chris@14 19 use Symfony\Component\DependencyInjection\ChildDefinition;
Chris@14 20 use Symfony\Component\DependencyInjection\ContainerBuilder;
Chris@17 21 use Symfony\Component\DependencyInjection\ContainerInterface;
Chris@17 22 use Symfony\Component\DependencyInjection\Definition;
Chris@0 23 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
Chris@0 24 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
Chris@17 25 use Symfony\Component\DependencyInjection\Reference;
Chris@0 26 use Symfony\Component\ExpressionLanguage\Expression;
Chris@0 27
Chris@0 28 /**
Chris@0 29 * XmlFileLoader loads XML files service definitions.
Chris@0 30 *
Chris@0 31 * @author Fabien Potencier <fabien@symfony.com>
Chris@0 32 */
Chris@0 33 class XmlFileLoader extends FileLoader
Chris@0 34 {
Chris@0 35 const NS = 'http://symfony.com/schema/dic/services';
Chris@0 36
Chris@0 37 /**
Chris@0 38 * {@inheritdoc}
Chris@0 39 */
Chris@0 40 public function load($resource, $type = null)
Chris@0 41 {
Chris@0 42 $path = $this->locator->locate($resource);
Chris@0 43
Chris@0 44 $xml = $this->parseFileToDOM($path);
Chris@0 45
Chris@14 46 $this->container->fileExists($path);
Chris@14 47
Chris@14 48 $defaults = $this->getServiceDefaults($xml, $path);
Chris@0 49
Chris@0 50 // anonymous services
Chris@14 51 $this->processAnonymousServices($xml, $path, $defaults);
Chris@0 52
Chris@0 53 // imports
Chris@0 54 $this->parseImports($xml, $path);
Chris@0 55
Chris@0 56 // parameters
Chris@14 57 $this->parseParameters($xml, $path);
Chris@0 58
Chris@0 59 // extensions
Chris@0 60 $this->loadFromExtensions($xml);
Chris@0 61
Chris@0 62 // services
Chris@14 63 try {
Chris@14 64 $this->parseDefinitions($xml, $path, $defaults);
Chris@14 65 } finally {
Chris@17 66 $this->instanceof = [];
Chris@14 67 }
Chris@0 68 }
Chris@0 69
Chris@0 70 /**
Chris@0 71 * {@inheritdoc}
Chris@0 72 */
Chris@0 73 public function supports($resource, $type = null)
Chris@0 74 {
Chris@17 75 if (!\is_string($resource)) {
Chris@14 76 return false;
Chris@14 77 }
Chris@14 78
Chris@14 79 if (null === $type && 'xml' === pathinfo($resource, PATHINFO_EXTENSION)) {
Chris@14 80 return true;
Chris@14 81 }
Chris@14 82
Chris@14 83 return 'xml' === $type;
Chris@0 84 }
Chris@0 85
Chris@0 86 /**
Chris@0 87 * Parses parameters.
Chris@0 88 *
Chris@0 89 * @param \DOMDocument $xml
Chris@14 90 * @param string $file
Chris@0 91 */
Chris@14 92 private function parseParameters(\DOMDocument $xml, $file)
Chris@0 93 {
Chris@0 94 if ($parameters = $this->getChildren($xml->documentElement, 'parameters')) {
Chris@14 95 $this->container->getParameterBag()->add($this->getArgumentsAsPhp($parameters[0], 'parameter', $file));
Chris@0 96 }
Chris@0 97 }
Chris@0 98
Chris@0 99 /**
Chris@0 100 * Parses imports.
Chris@0 101 *
Chris@0 102 * @param \DOMDocument $xml
Chris@0 103 * @param string $file
Chris@0 104 */
Chris@0 105 private function parseImports(\DOMDocument $xml, $file)
Chris@0 106 {
Chris@0 107 $xpath = new \DOMXPath($xml);
Chris@0 108 $xpath->registerNamespace('container', self::NS);
Chris@0 109
Chris@0 110 if (false === $imports = $xpath->query('//container:imports/container:import')) {
Chris@0 111 return;
Chris@0 112 }
Chris@0 113
Chris@17 114 $defaultDirectory = \dirname($file);
Chris@0 115 foreach ($imports as $import) {
Chris@0 116 $this->setCurrentDir($defaultDirectory);
Chris@14 117 $this->import($import->getAttribute('resource'), XmlUtils::phpize($import->getAttribute('type')) ?: null, (bool) XmlUtils::phpize($import->getAttribute('ignore-errors')), $file);
Chris@0 118 }
Chris@0 119 }
Chris@0 120
Chris@0 121 /**
Chris@0 122 * Parses multiple definitions.
Chris@0 123 *
Chris@0 124 * @param \DOMDocument $xml
Chris@0 125 * @param string $file
Chris@0 126 */
Chris@14 127 private function parseDefinitions(\DOMDocument $xml, $file, $defaults)
Chris@0 128 {
Chris@0 129 $xpath = new \DOMXPath($xml);
Chris@0 130 $xpath->registerNamespace('container', self::NS);
Chris@0 131
Chris@14 132 if (false === $services = $xpath->query('//container:services/container:service|//container:services/container:prototype')) {
Chris@0 133 return;
Chris@0 134 }
Chris@17 135 $this->setCurrentDir(\dirname($file));
Chris@0 136
Chris@17 137 $this->instanceof = [];
Chris@14 138 $this->isLoadingInstanceof = true;
Chris@14 139 $instanceof = $xpath->query('//container:services/container:instanceof');
Chris@14 140 foreach ($instanceof as $service) {
Chris@17 141 $this->setDefinition((string) $service->getAttribute('id'), $this->parseDefinition($service, $file, []));
Chris@14 142 }
Chris@14 143
Chris@14 144 $this->isLoadingInstanceof = false;
Chris@0 145 foreach ($services as $service) {
Chris@14 146 if (null !== $definition = $this->parseDefinition($service, $file, $defaults)) {
Chris@14 147 if ('prototype' === $service->tagName) {
Chris@14 148 $this->registerClasses($definition, (string) $service->getAttribute('namespace'), (string) $service->getAttribute('resource'), (string) $service->getAttribute('exclude'));
Chris@14 149 } else {
Chris@14 150 $this->setDefinition((string) $service->getAttribute('id'), $definition);
Chris@14 151 }
Chris@0 152 }
Chris@0 153 }
Chris@0 154 }
Chris@0 155
Chris@0 156 /**
Chris@14 157 * Get service defaults.
Chris@14 158 *
Chris@14 159 * @return array
Chris@14 160 */
Chris@14 161 private function getServiceDefaults(\DOMDocument $xml, $file)
Chris@14 162 {
Chris@14 163 $xpath = new \DOMXPath($xml);
Chris@14 164 $xpath->registerNamespace('container', self::NS);
Chris@14 165
Chris@14 166 if (null === $defaultsNode = $xpath->query('//container:services/container:defaults')->item(0)) {
Chris@17 167 return [];
Chris@14 168 }
Chris@17 169 $defaults = [
Chris@14 170 'tags' => $this->getChildren($defaultsNode, 'tag'),
Chris@14 171 'bind' => array_map(function ($v) { return new BoundArgument($v); }, $this->getArgumentsAsPhp($defaultsNode, 'bind', $file)),
Chris@17 172 ];
Chris@14 173
Chris@14 174 foreach ($defaults['tags'] as $tag) {
Chris@14 175 if ('' === $tag->getAttribute('name')) {
Chris@14 176 throw new InvalidArgumentException(sprintf('The tag name for tag "<defaults>" in %s must be a non-empty string.', $file));
Chris@14 177 }
Chris@14 178 }
Chris@14 179
Chris@14 180 if ($defaultsNode->hasAttribute('autowire')) {
Chris@14 181 $defaults['autowire'] = XmlUtils::phpize($defaultsNode->getAttribute('autowire'));
Chris@14 182 }
Chris@14 183 if ($defaultsNode->hasAttribute('public')) {
Chris@14 184 $defaults['public'] = XmlUtils::phpize($defaultsNode->getAttribute('public'));
Chris@14 185 }
Chris@14 186 if ($defaultsNode->hasAttribute('autoconfigure')) {
Chris@14 187 $defaults['autoconfigure'] = XmlUtils::phpize($defaultsNode->getAttribute('autoconfigure'));
Chris@14 188 }
Chris@14 189
Chris@14 190 return $defaults;
Chris@14 191 }
Chris@14 192
Chris@14 193 /**
Chris@0 194 * Parses an individual Definition.
Chris@0 195 *
Chris@0 196 * @param \DOMElement $service
Chris@0 197 * @param string $file
Chris@14 198 * @param array $defaults
Chris@0 199 *
Chris@0 200 * @return Definition|null
Chris@0 201 */
Chris@14 202 private function parseDefinition(\DOMElement $service, $file, array $defaults)
Chris@0 203 {
Chris@0 204 if ($alias = $service->getAttribute('alias')) {
Chris@0 205 $this->validateAlias($service, $file);
Chris@0 206
Chris@14 207 $this->container->setAlias((string) $service->getAttribute('id'), $alias = new Alias($alias));
Chris@0 208 if ($publicAttr = $service->getAttribute('public')) {
Chris@14 209 $alias->setPublic(XmlUtils::phpize($publicAttr));
Chris@14 210 } elseif (isset($defaults['public'])) {
Chris@14 211 $alias->setPublic($defaults['public']);
Chris@0 212 }
Chris@0 213
Chris@0 214 return;
Chris@0 215 }
Chris@0 216
Chris@14 217 if ($this->isLoadingInstanceof) {
Chris@14 218 $definition = new ChildDefinition('');
Chris@14 219 } elseif ($parent = $service->getAttribute('parent')) {
Chris@14 220 if (!empty($this->instanceof)) {
Chris@14 221 throw new InvalidArgumentException(sprintf('The service "%s" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.', $service->getAttribute('id')));
Chris@14 222 }
Chris@14 223
Chris@14 224 foreach ($defaults as $k => $v) {
Chris@14 225 if ('tags' === $k) {
Chris@14 226 // since tags are never inherited from parents, there is no confusion
Chris@14 227 // thus we can safely add them as defaults to ChildDefinition
Chris@14 228 continue;
Chris@14 229 }
Chris@14 230 if ('bind' === $k) {
Chris@14 231 if ($defaults['bind']) {
Chris@14 232 throw new InvalidArgumentException(sprintf('Bound values on service "%s" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file.', $service->getAttribute('id')));
Chris@14 233 }
Chris@14 234
Chris@14 235 continue;
Chris@14 236 }
Chris@14 237 if (!$service->hasAttribute($k)) {
Chris@14 238 throw new InvalidArgumentException(sprintf('Attribute "%s" on service "%s" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.', $k, $service->getAttribute('id')));
Chris@14 239 }
Chris@14 240 }
Chris@14 241
Chris@14 242 $definition = new ChildDefinition($parent);
Chris@0 243 } else {
Chris@0 244 $definition = new Definition();
Chris@14 245
Chris@14 246 if (isset($defaults['public'])) {
Chris@14 247 $definition->setPublic($defaults['public']);
Chris@14 248 }
Chris@14 249 if (isset($defaults['autowire'])) {
Chris@14 250 $definition->setAutowired($defaults['autowire']);
Chris@14 251 }
Chris@14 252 if (isset($defaults['autoconfigure'])) {
Chris@14 253 $definition->setAutoconfigured($defaults['autoconfigure']);
Chris@14 254 }
Chris@14 255
Chris@17 256 $definition->setChanges([]);
Chris@0 257 }
Chris@0 258
Chris@17 259 foreach (['class', 'public', 'shared', 'synthetic', 'lazy', 'abstract'] as $key) {
Chris@0 260 if ($value = $service->getAttribute($key)) {
Chris@0 261 $method = 'set'.$key;
Chris@0 262 $definition->$method(XmlUtils::phpize($value));
Chris@0 263 }
Chris@0 264 }
Chris@0 265
Chris@0 266 if ($value = $service->getAttribute('autowire')) {
Chris@0 267 $definition->setAutowired(XmlUtils::phpize($value));
Chris@0 268 }
Chris@0 269
Chris@14 270 if ($value = $service->getAttribute('autoconfigure')) {
Chris@14 271 if (!$definition instanceof ChildDefinition) {
Chris@14 272 $definition->setAutoconfigured(XmlUtils::phpize($value));
Chris@14 273 } elseif ($value = XmlUtils::phpize($value)) {
Chris@14 274 throw new InvalidArgumentException(sprintf('The service "%s" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service.', $service->getAttribute('id')));
Chris@14 275 }
Chris@14 276 }
Chris@14 277
Chris@0 278 if ($files = $this->getChildren($service, 'file')) {
Chris@0 279 $definition->setFile($files[0]->nodeValue);
Chris@0 280 }
Chris@0 281
Chris@0 282 if ($deprecated = $this->getChildren($service, 'deprecated')) {
Chris@0 283 $definition->setDeprecated(true, $deprecated[0]->nodeValue ?: null);
Chris@0 284 }
Chris@0 285
Chris@14 286 $definition->setArguments($this->getArgumentsAsPhp($service, 'argument', $file, false, $definition instanceof ChildDefinition));
Chris@14 287 $definition->setProperties($this->getArgumentsAsPhp($service, 'property', $file));
Chris@0 288
Chris@0 289 if ($factories = $this->getChildren($service, 'factory')) {
Chris@0 290 $factory = $factories[0];
Chris@0 291 if ($function = $factory->getAttribute('function')) {
Chris@0 292 $definition->setFactory($function);
Chris@0 293 } else {
Chris@14 294 if ($childService = $factory->getAttribute('service')) {
Chris@0 295 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
Chris@0 296 } else {
Chris@14 297 $class = $factory->hasAttribute('class') ? $factory->getAttribute('class') : null;
Chris@0 298 }
Chris@0 299
Chris@17 300 $definition->setFactory([$class, $factory->getAttribute('method')]);
Chris@0 301 }
Chris@0 302 }
Chris@0 303
Chris@0 304 if ($configurators = $this->getChildren($service, 'configurator')) {
Chris@0 305 $configurator = $configurators[0];
Chris@0 306 if ($function = $configurator->getAttribute('function')) {
Chris@0 307 $definition->setConfigurator($function);
Chris@0 308 } else {
Chris@14 309 if ($childService = $configurator->getAttribute('service')) {
Chris@0 310 $class = new Reference($childService, ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE);
Chris@0 311 } else {
Chris@0 312 $class = $configurator->getAttribute('class');
Chris@0 313 }
Chris@0 314
Chris@17 315 $definition->setConfigurator([$class, $configurator->getAttribute('method')]);
Chris@0 316 }
Chris@0 317 }
Chris@0 318
Chris@0 319 foreach ($this->getChildren($service, 'call') as $call) {
Chris@14 320 $definition->addMethodCall($call->getAttribute('method'), $this->getArgumentsAsPhp($call, 'argument', $file));
Chris@0 321 }
Chris@0 322
Chris@14 323 $tags = $this->getChildren($service, 'tag');
Chris@14 324
Chris@14 325 if (!empty($defaults['tags'])) {
Chris@14 326 $tags = array_merge($tags, $defaults['tags']);
Chris@14 327 }
Chris@14 328
Chris@14 329 foreach ($tags as $tag) {
Chris@17 330 $parameters = [];
Chris@0 331 foreach ($tag->attributes as $name => $node) {
Chris@0 332 if ('name' === $name) {
Chris@0 333 continue;
Chris@0 334 }
Chris@0 335
Chris@18 336 if (false !== strpos($name, '-') && false === strpos($name, '_') && !\array_key_exists($normalizedName = str_replace('-', '_', $name), $parameters)) {
Chris@0 337 $parameters[$normalizedName] = XmlUtils::phpize($node->nodeValue);
Chris@0 338 }
Chris@0 339 // keep not normalized key
Chris@0 340 $parameters[$name] = XmlUtils::phpize($node->nodeValue);
Chris@0 341 }
Chris@0 342
Chris@0 343 if ('' === $tag->getAttribute('name')) {
Chris@0 344 throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', (string) $service->getAttribute('id'), $file));
Chris@0 345 }
Chris@0 346
Chris@0 347 $definition->addTag($tag->getAttribute('name'), $parameters);
Chris@0 348 }
Chris@0 349
Chris@0 350 foreach ($this->getChildren($service, 'autowiring-type') as $type) {
Chris@0 351 $definition->addAutowiringType($type->textContent);
Chris@0 352 }
Chris@0 353
Chris@14 354 $bindings = $this->getArgumentsAsPhp($service, 'bind', $file);
Chris@14 355 if (isset($defaults['bind'])) {
Chris@14 356 // deep clone, to avoid multiple process of the same instance in the passes
Chris@14 357 $bindings = array_merge(unserialize(serialize($defaults['bind'])), $bindings);
Chris@14 358 }
Chris@14 359 if ($bindings) {
Chris@14 360 $definition->setBindings($bindings);
Chris@14 361 }
Chris@14 362
Chris@0 363 if ($value = $service->getAttribute('decorates')) {
Chris@0 364 $renameId = $service->hasAttribute('decoration-inner-name') ? $service->getAttribute('decoration-inner-name') : null;
Chris@0 365 $priority = $service->hasAttribute('decoration-priority') ? $service->getAttribute('decoration-priority') : 0;
Chris@0 366 $definition->setDecoratedService($value, $renameId, $priority);
Chris@0 367 }
Chris@0 368
Chris@0 369 return $definition;
Chris@0 370 }
Chris@0 371
Chris@0 372 /**
Chris@0 373 * Parses a XML file to a \DOMDocument.
Chris@0 374 *
Chris@0 375 * @param string $file Path to a file
Chris@0 376 *
Chris@0 377 * @return \DOMDocument
Chris@0 378 *
Chris@0 379 * @throws InvalidArgumentException When loading of XML file returns error
Chris@0 380 */
Chris@0 381 private function parseFileToDOM($file)
Chris@0 382 {
Chris@0 383 try {
Chris@17 384 $dom = XmlUtils::loadFile($file, [$this, 'validateSchema']);
Chris@0 385 } catch (\InvalidArgumentException $e) {
Chris@17 386 throw new InvalidArgumentException(sprintf('Unable to parse file "%s": %s', $file, $e->getMessage()), $e->getCode(), $e);
Chris@0 387 }
Chris@0 388
Chris@0 389 $this->validateExtensions($dom, $file);
Chris@0 390
Chris@0 391 return $dom;
Chris@0 392 }
Chris@0 393
Chris@0 394 /**
Chris@0 395 * Processes anonymous services.
Chris@0 396 *
Chris@0 397 * @param \DOMDocument $xml
Chris@0 398 * @param string $file
Chris@14 399 * @param array $defaults
Chris@0 400 */
Chris@14 401 private function processAnonymousServices(\DOMDocument $xml, $file, $defaults)
Chris@0 402 {
Chris@17 403 $definitions = [];
Chris@0 404 $count = 0;
Chris@17 405 $suffix = '~'.ContainerBuilder::hash($file);
Chris@0 406
Chris@0 407 $xpath = new \DOMXPath($xml);
Chris@0 408 $xpath->registerNamespace('container', self::NS);
Chris@0 409
Chris@0 410 // anonymous services as arguments/properties
Chris@14 411 if (false !== $nodes = $xpath->query('//container:argument[@type="service"][not(@id)]|//container:property[@type="service"][not(@id)]|//container:bind[not(@id)]|//container:factory[not(@service)]|//container:configurator[not(@service)]')) {
Chris@0 412 foreach ($nodes as $node) {
Chris@14 413 if ($services = $this->getChildren($node, 'service')) {
Chris@14 414 // give it a unique name
Chris@17 415 $id = sprintf('%d_%s', ++$count, preg_replace('/^.*\\\\/', '', $services[0]->getAttribute('class')).$suffix);
Chris@14 416 $node->setAttribute('id', $id);
Chris@14 417 $node->setAttribute('service', $id);
Chris@0 418
Chris@17 419 $definitions[$id] = [$services[0], $file, false];
Chris@0 420 $services[0]->setAttribute('id', $id);
Chris@0 421
Chris@0 422 // anonymous services are always private
Chris@0 423 // we could not use the constant false here, because of XML parsing
Chris@0 424 $services[0]->setAttribute('public', 'false');
Chris@0 425 }
Chris@0 426 }
Chris@0 427 }
Chris@0 428
Chris@0 429 // anonymous services "in the wild"
Chris@0 430 if (false !== $nodes = $xpath->query('//container:services/container:service[not(@id)]')) {
Chris@0 431 foreach ($nodes as $node) {
Chris@14 432 @trigger_error(sprintf('Top-level anonymous services are deprecated since Symfony 3.4, the "id" attribute will be required in version 4.0 in %s at line %d.', $file, $node->getLineNo()), E_USER_DEPRECATED);
Chris@14 433
Chris@0 434 // give it a unique name
Chris@14 435 $id = sprintf('%d_%s', ++$count, preg_replace('/^.*\\\\/', '', $node->getAttribute('class')).$suffix);
Chris@0 436 $node->setAttribute('id', $id);
Chris@17 437 $definitions[$id] = [$node, $file, true];
Chris@0 438 }
Chris@0 439 }
Chris@0 440
Chris@0 441 // resolve definitions
Chris@14 442 uksort($definitions, 'strnatcmp');
Chris@14 443 foreach (array_reverse($definitions) as $id => list($domElement, $file, $wild)) {
Chris@17 444 if (null !== $definition = $this->parseDefinition($domElement, $file, $wild ? $defaults : [])) {
Chris@14 445 $this->setDefinition($id, $definition);
Chris@0 446 }
Chris@0 447
Chris@0 448 if (true === $wild) {
Chris@0 449 $tmpDomElement = new \DOMElement('_services', null, self::NS);
Chris@0 450 $domElement->parentNode->replaceChild($tmpDomElement, $domElement);
Chris@0 451 $tmpDomElement->setAttribute('id', $id);
Chris@0 452 }
Chris@0 453 }
Chris@0 454 }
Chris@0 455
Chris@0 456 /**
Chris@0 457 * Returns arguments as valid php types.
Chris@0 458 *
Chris@0 459 * @param \DOMElement $node
Chris@0 460 * @param string $name
Chris@14 461 * @param string $file
Chris@0 462 * @param bool $lowercase
Chris@0 463 *
Chris@0 464 * @return mixed
Chris@0 465 */
Chris@14 466 private function getArgumentsAsPhp(\DOMElement $node, $name, $file, $lowercase = true, $isChildDefinition = false)
Chris@0 467 {
Chris@17 468 $arguments = [];
Chris@0 469 foreach ($this->getChildren($node, $name) as $arg) {
Chris@0 470 if ($arg->hasAttribute('name')) {
Chris@0 471 $arg->setAttribute('key', $arg->getAttribute('name'));
Chris@0 472 }
Chris@0 473
Chris@14 474 // this is used by ChildDefinition to overwrite a specific
Chris@0 475 // argument of the parent definition
Chris@0 476 if ($arg->hasAttribute('index')) {
Chris@14 477 $key = ($isChildDefinition ? 'index_' : '').$arg->getAttribute('index');
Chris@0 478 } elseif (!$arg->hasAttribute('key')) {
Chris@0 479 // Append an empty argument, then fetch its key to overwrite it later
Chris@0 480 $arguments[] = null;
Chris@0 481 $keys = array_keys($arguments);
Chris@0 482 $key = array_pop($keys);
Chris@0 483 } else {
Chris@0 484 $key = $arg->getAttribute('key');
Chris@14 485 }
Chris@0 486
Chris@14 487 $onInvalid = $arg->getAttribute('on-invalid');
Chris@14 488 $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
Chris@14 489 if ('ignore' == $onInvalid) {
Chris@14 490 $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
Chris@14 491 } elseif ('ignore_uninitialized' == $onInvalid) {
Chris@14 492 $invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
Chris@14 493 } elseif ('null' == $onInvalid) {
Chris@14 494 $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
Chris@0 495 }
Chris@0 496
Chris@0 497 switch ($arg->getAttribute('type')) {
Chris@0 498 case 'service':
Chris@17 499 if ('' === $arg->getAttribute('id')) {
Chris@14 500 throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service" has no or empty "id" attribute in "%s".', $name, $file));
Chris@14 501 }
Chris@14 502 if ($arg->hasAttribute('strict')) {
Chris@14 503 @trigger_error(sprintf('The "strict" attribute used when referencing the "%s" service is deprecated since Symfony 3.3 and will be removed in 4.0.', $arg->getAttribute('id')), E_USER_DEPRECATED);
Chris@0 504 }
Chris@0 505
Chris@0 506 $arguments[$key] = new Reference($arg->getAttribute('id'), $invalidBehavior);
Chris@0 507 break;
Chris@0 508 case 'expression':
Chris@14 509 if (!class_exists(Expression::class)) {
Chris@14 510 throw new \LogicException(sprintf('The type="expression" attribute cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".'));
Chris@14 511 }
Chris@14 512
Chris@0 513 $arguments[$key] = new Expression($arg->nodeValue);
Chris@0 514 break;
Chris@0 515 case 'collection':
Chris@14 516 $arguments[$key] = $this->getArgumentsAsPhp($arg, $name, $file, false);
Chris@14 517 break;
Chris@14 518 case 'iterator':
Chris@14 519 $arg = $this->getArgumentsAsPhp($arg, $name, $file, false);
Chris@14 520 try {
Chris@14 521 $arguments[$key] = new IteratorArgument($arg);
Chris@14 522 } catch (InvalidArgumentException $e) {
Chris@14 523 throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="iterator" only accepts collections of type="service" references in "%s".', $name, $file));
Chris@14 524 }
Chris@14 525 break;
Chris@14 526 case 'tagged':
Chris@14 527 if (!$arg->getAttribute('tag')) {
Chris@14 528 throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="tagged" has no or empty "tag" attribute in "%s".', $name, $file));
Chris@14 529 }
Chris@14 530 $arguments[$key] = new TaggedIteratorArgument($arg->getAttribute('tag'));
Chris@0 531 break;
Chris@0 532 case 'string':
Chris@0 533 $arguments[$key] = $arg->nodeValue;
Chris@0 534 break;
Chris@0 535 case 'constant':
Chris@17 536 $arguments[$key] = \constant(trim($arg->nodeValue));
Chris@0 537 break;
Chris@0 538 default:
Chris@0 539 $arguments[$key] = XmlUtils::phpize($arg->nodeValue);
Chris@0 540 }
Chris@0 541 }
Chris@0 542
Chris@0 543 return $arguments;
Chris@0 544 }
Chris@0 545
Chris@0 546 /**
Chris@0 547 * Get child elements by name.
Chris@0 548 *
Chris@0 549 * @param \DOMNode $node
Chris@0 550 * @param mixed $name
Chris@0 551 *
Chris@17 552 * @return \DOMElement[]
Chris@0 553 */
Chris@0 554 private function getChildren(\DOMNode $node, $name)
Chris@0 555 {
Chris@17 556 $children = [];
Chris@0 557 foreach ($node->childNodes as $child) {
Chris@14 558 if ($child instanceof \DOMElement && $child->localName === $name && self::NS === $child->namespaceURI) {
Chris@0 559 $children[] = $child;
Chris@0 560 }
Chris@0 561 }
Chris@0 562
Chris@0 563 return $children;
Chris@0 564 }
Chris@0 565
Chris@0 566 /**
Chris@0 567 * Validates a documents XML schema.
Chris@0 568 *
Chris@0 569 * @param \DOMDocument $dom
Chris@0 570 *
Chris@0 571 * @return bool
Chris@0 572 *
Chris@0 573 * @throws RuntimeException When extension references a non-existent XSD file
Chris@0 574 */
Chris@0 575 public function validateSchema(\DOMDocument $dom)
Chris@0 576 {
Chris@17 577 $schemaLocations = ['http://symfony.com/schema/dic/services' => str_replace('\\', '/', __DIR__.'/schema/dic/services/services-1.0.xsd')];
Chris@0 578
Chris@0 579 if ($element = $dom->documentElement->getAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation')) {
Chris@0 580 $items = preg_split('/\s+/', $element);
Chris@17 581 for ($i = 0, $nb = \count($items); $i < $nb; $i += 2) {
Chris@0 582 if (!$this->container->hasExtension($items[$i])) {
Chris@0 583 continue;
Chris@0 584 }
Chris@0 585
Chris@0 586 if (($extension = $this->container->getExtension($items[$i])) && false !== $extension->getXsdValidationBasePath()) {
Chris@18 587 $ns = $extension->getNamespace();
Chris@18 588 $path = str_replace([$ns, str_replace('http://', 'https://', $ns)], str_replace('\\', '/', $extension->getXsdValidationBasePath()).'/', $items[$i + 1]);
Chris@0 589
Chris@0 590 if (!is_file($path)) {
Chris@17 591 throw new RuntimeException(sprintf('Extension "%s" references a non-existent XSD file "%s"', \get_class($extension), $path));
Chris@0 592 }
Chris@0 593
Chris@0 594 $schemaLocations[$items[$i]] = $path;
Chris@0 595 }
Chris@0 596 }
Chris@0 597 }
Chris@0 598
Chris@17 599 $tmpfiles = [];
Chris@0 600 $imports = '';
Chris@0 601 foreach ($schemaLocations as $namespace => $location) {
Chris@0 602 $parts = explode('/', $location);
Chris@14 603 $locationstart = 'file:///';
Chris@0 604 if (0 === stripos($location, 'phar://')) {
Chris@14 605 $tmpfile = tempnam(sys_get_temp_dir(), 'symfony');
Chris@0 606 if ($tmpfile) {
Chris@0 607 copy($location, $tmpfile);
Chris@0 608 $tmpfiles[] = $tmpfile;
Chris@0 609 $parts = explode('/', str_replace('\\', '/', $tmpfile));
Chris@14 610 } else {
Chris@14 611 array_shift($parts);
Chris@14 612 $locationstart = 'phar:///';
Chris@0 613 }
Chris@0 614 }
Chris@17 615 $drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
Chris@14 616 $location = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
Chris@0 617
Chris@0 618 $imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
Chris@0 619 }
Chris@0 620
Chris@0 621 $source = <<<EOF
Chris@0 622 <?xml version="1.0" encoding="utf-8" ?>
Chris@0 623 <xsd:schema xmlns="http://symfony.com/schema"
Chris@0 624 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
Chris@0 625 targetNamespace="http://symfony.com/schema"
Chris@0 626 elementFormDefault="qualified">
Chris@0 627
Chris@0 628 <xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
Chris@0 629 $imports
Chris@0 630 </xsd:schema>
Chris@0 631 EOF
Chris@0 632 ;
Chris@0 633
Chris@0 634 $disableEntities = libxml_disable_entity_loader(false);
Chris@0 635 $valid = @$dom->schemaValidateSource($source);
Chris@0 636 libxml_disable_entity_loader($disableEntities);
Chris@0 637
Chris@0 638 foreach ($tmpfiles as $tmpfile) {
Chris@0 639 @unlink($tmpfile);
Chris@0 640 }
Chris@0 641
Chris@0 642 return $valid;
Chris@0 643 }
Chris@0 644
Chris@0 645 /**
Chris@0 646 * Validates an alias.
Chris@0 647 *
Chris@0 648 * @param \DOMElement $alias
Chris@0 649 * @param string $file
Chris@0 650 */
Chris@0 651 private function validateAlias(\DOMElement $alias, $file)
Chris@0 652 {
Chris@0 653 foreach ($alias->attributes as $name => $node) {
Chris@17 654 if (!\in_array($name, ['alias', 'id', 'public'])) {
Chris@0 655 @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);
Chris@0 656 }
Chris@0 657 }
Chris@0 658
Chris@0 659 foreach ($alias->childNodes as $child) {
Chris@14 660 if ($child instanceof \DOMElement && self::NS === $child->namespaceURI) {
Chris@0 661 @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);
Chris@0 662 }
Chris@0 663 }
Chris@0 664 }
Chris@0 665
Chris@0 666 /**
Chris@0 667 * Validates an extension.
Chris@0 668 *
Chris@0 669 * @param \DOMDocument $dom
Chris@0 670 * @param string $file
Chris@0 671 *
Chris@0 672 * @throws InvalidArgumentException When no extension is found corresponding to a tag
Chris@0 673 */
Chris@0 674 private function validateExtensions(\DOMDocument $dom, $file)
Chris@0 675 {
Chris@0 676 foreach ($dom->documentElement->childNodes as $node) {
Chris@0 677 if (!$node instanceof \DOMElement || 'http://symfony.com/schema/dic/services' === $node->namespaceURI) {
Chris@0 678 continue;
Chris@0 679 }
Chris@0 680
Chris@0 681 // can it be handled by an extension?
Chris@0 682 if (!$this->container->hasExtension($node->namespaceURI)) {
Chris@0 683 $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getNamespace(); }, $this->container->getExtensions()));
Chris@17 684 throw new InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s', $node->tagName, $file, $node->namespaceURI, $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'));
Chris@0 685 }
Chris@0 686 }
Chris@0 687 }
Chris@0 688
Chris@0 689 /**
Chris@0 690 * Loads from an extension.
Chris@0 691 *
Chris@0 692 * @param \DOMDocument $xml
Chris@0 693 */
Chris@0 694 private function loadFromExtensions(\DOMDocument $xml)
Chris@0 695 {
Chris@0 696 foreach ($xml->documentElement->childNodes as $node) {
Chris@14 697 if (!$node instanceof \DOMElement || self::NS === $node->namespaceURI) {
Chris@0 698 continue;
Chris@0 699 }
Chris@0 700
Chris@0 701 $values = static::convertDomElementToArray($node);
Chris@17 702 if (!\is_array($values)) {
Chris@17 703 $values = [];
Chris@0 704 }
Chris@0 705
Chris@0 706 $this->container->loadFromExtension($node->namespaceURI, $values);
Chris@0 707 }
Chris@0 708 }
Chris@0 709
Chris@0 710 /**
Chris@14 711 * Converts a \DOMElement object to a PHP array.
Chris@0 712 *
Chris@0 713 * The following rules applies during the conversion:
Chris@0 714 *
Chris@0 715 * * Each tag is converted to a key value or an array
Chris@0 716 * if there is more than one "value"
Chris@0 717 *
Chris@0 718 * * The content of a tag is set under a "value" key (<foo>bar</foo>)
Chris@0 719 * if the tag also has some nested tags
Chris@0 720 *
Chris@0 721 * * The attributes are converted to keys (<foo foo="bar"/>)
Chris@0 722 *
Chris@0 723 * * The nested-tags are converted to keys (<foo><foo>bar</foo></foo>)
Chris@0 724 *
Chris@14 725 * @param \DOMElement $element A \DOMElement instance
Chris@0 726 *
Chris@0 727 * @return array A PHP array
Chris@0 728 */
Chris@0 729 public static function convertDomElementToArray(\DOMElement $element)
Chris@0 730 {
Chris@0 731 return XmlUtils::convertDomElementToArray($element);
Chris@0 732 }
Chris@0 733 }