XmlFileLoader.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Routing\Loader;
  11. use Symfony\Component\Config\Loader\FileLoader;
  12. use Symfony\Component\Config\Resource\FileResource;
  13. use Symfony\Component\Config\Util\XmlUtils;
  14. use Symfony\Component\Routing\Loader\Configurator\Traits\HostTrait;
  15. use Symfony\Component\Routing\Loader\Configurator\Traits\LocalizedRouteTrait;
  16. use Symfony\Component\Routing\Loader\Configurator\Traits\PrefixTrait;
  17. use Symfony\Component\Routing\RouteCollection;
  18. /**
  19. * XmlFileLoader loads XML routing files.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. * @author Tobias Schultze <http://tobion.de>
  23. */
  24. class XmlFileLoader extends FileLoader
  25. {
  26. use HostTrait;
  27. use LocalizedRouteTrait;
  28. use PrefixTrait;
  29. public const NAMESPACE_URI = 'http://symfony.com/schema/routing';
  30. public const SCHEME_PATH = '/schema/routing/routing-1.0.xsd';
  31. /**
  32. * @throws \InvalidArgumentException when the file cannot be loaded or when the XML cannot be
  33. * parsed because it does not validate against the scheme
  34. */
  35. public function load(mixed $file, ?string $type = null): RouteCollection
  36. {
  37. $path = $this->locator->locate($file);
  38. $xml = $this->loadFile($path);
  39. $collection = new RouteCollection();
  40. $collection->addResource(new FileResource($path));
  41. // process routes and imports
  42. foreach ($xml->documentElement->childNodes as $node) {
  43. if (!$node instanceof \DOMElement) {
  44. continue;
  45. }
  46. $this->parseNode($collection, $node, $path, $file);
  47. }
  48. return $collection;
  49. }
  50. /**
  51. * Parses a node from a loaded XML file.
  52. *
  53. * @return void
  54. *
  55. * @throws \InvalidArgumentException When the XML is invalid
  56. */
  57. protected function parseNode(RouteCollection $collection, \DOMElement $node, string $path, string $file)
  58. {
  59. if (self::NAMESPACE_URI !== $node->namespaceURI) {
  60. return;
  61. }
  62. switch ($node->localName) {
  63. case 'route':
  64. $this->parseRoute($collection, $node, $path);
  65. break;
  66. case 'import':
  67. $this->parseImport($collection, $node, $path, $file);
  68. break;
  69. case 'when':
  70. if (!$this->env || $node->getAttribute('env') !== $this->env) {
  71. break;
  72. }
  73. foreach ($node->childNodes as $node) {
  74. if ($node instanceof \DOMElement) {
  75. $this->parseNode($collection, $node, $path, $file);
  76. }
  77. }
  78. break;
  79. default:
  80. throw new \InvalidArgumentException(\sprintf('Unknown tag "%s" used in file "%s". Expected "route" or "import".', $node->localName, $path));
  81. }
  82. }
  83. public function supports(mixed $resource, ?string $type = null): bool
  84. {
  85. return \is_string($resource) && 'xml' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'xml' === $type);
  86. }
  87. /**
  88. * Parses a route and adds it to the RouteCollection.
  89. *
  90. * @return void
  91. *
  92. * @throws \InvalidArgumentException When the XML is invalid
  93. */
  94. protected function parseRoute(RouteCollection $collection, \DOMElement $node, string $path)
  95. {
  96. if ('' === $id = $node->getAttribute('id')) {
  97. throw new \InvalidArgumentException(\sprintf('The <route> element in file "%s" must have an "id" attribute.', $path));
  98. }
  99. if ('' !== $alias = $node->getAttribute('alias')) {
  100. $alias = $collection->addAlias($id, $alias);
  101. if ($deprecationInfo = $this->parseDeprecation($node, $path)) {
  102. $alias->setDeprecated($deprecationInfo['package'], $deprecationInfo['version'], $deprecationInfo['message']);
  103. }
  104. return;
  105. }
  106. $schemes = preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY);
  107. $methods = preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY);
  108. [$defaults, $requirements, $options, $condition, $paths, /* $prefixes */, $hosts] = $this->parseConfigs($node, $path);
  109. if (!$paths && '' === $node->getAttribute('path')) {
  110. throw new \InvalidArgumentException(\sprintf('The <route> element in file "%s" must have a "path" attribute or <path> child nodes.', $path));
  111. }
  112. if ($paths && '' !== $node->getAttribute('path')) {
  113. throw new \InvalidArgumentException(\sprintf('The <route> element in file "%s" must not have both a "path" attribute and <path> child nodes.', $path));
  114. }
  115. $routes = $this->createLocalizedRoute(new RouteCollection(), $id, $paths ?: $node->getAttribute('path'));
  116. $routes->addDefaults($defaults);
  117. $routes->addRequirements($requirements);
  118. $routes->addOptions($options);
  119. $routes->setSchemes($schemes);
  120. $routes->setMethods($methods);
  121. $routes->setCondition($condition);
  122. if (null !== $hosts) {
  123. $this->addHost($routes, $hosts);
  124. }
  125. $collection->addCollection($routes);
  126. }
  127. /**
  128. * Parses an import and adds the routes in the resource to the RouteCollection.
  129. *
  130. * @return void
  131. *
  132. * @throws \InvalidArgumentException When the XML is invalid
  133. */
  134. protected function parseImport(RouteCollection $collection, \DOMElement $node, string $path, string $file)
  135. {
  136. /** @var \DOMElement $resourceElement */
  137. if (!($resource = $node->getAttribute('resource') ?: null) && $resourceElement = $node->getElementsByTagName('resource')[0] ?? null) {
  138. $resource = [];
  139. /** @var \DOMAttr $attribute */
  140. foreach ($resourceElement->attributes as $attribute) {
  141. $resource[$attribute->name] = $attribute->value;
  142. }
  143. }
  144. if (!$resource) {
  145. throw new \InvalidArgumentException(\sprintf('The <import> element in file "%s" must have a "resource" attribute or element.', $path));
  146. }
  147. $type = $node->getAttribute('type');
  148. $prefix = $node->getAttribute('prefix');
  149. $schemes = $node->hasAttribute('schemes') ? preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY) : null;
  150. $methods = $node->hasAttribute('methods') ? preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY) : null;
  151. $trailingSlashOnRoot = $node->hasAttribute('trailing-slash-on-root') ? XmlUtils::phpize($node->getAttribute('trailing-slash-on-root')) : true;
  152. $namePrefix = $node->getAttribute('name-prefix') ?: null;
  153. [$defaults, $requirements, $options, $condition, /* $paths */, $prefixes, $hosts] = $this->parseConfigs($node, $path);
  154. if ('' !== $prefix && $prefixes) {
  155. throw new \InvalidArgumentException(\sprintf('The <route> element in file "%s" must not have both a "prefix" attribute and <prefix> child nodes.', $path));
  156. }
  157. $exclude = [];
  158. foreach ($node->childNodes as $child) {
  159. if ($child instanceof \DOMElement && $child->localName === $exclude && self::NAMESPACE_URI === $child->namespaceURI) {
  160. $exclude[] = $child->nodeValue;
  161. }
  162. }
  163. if ($node->hasAttribute('exclude')) {
  164. if ($exclude) {
  165. throw new \InvalidArgumentException('You cannot use both the attribute "exclude" and <exclude> tags at the same time.');
  166. }
  167. $exclude = [$node->getAttribute('exclude')];
  168. }
  169. $this->setCurrentDir(\dirname($path));
  170. /** @var RouteCollection[] $imported */
  171. $imported = $this->import($resource, '' !== $type ? $type : null, false, $file, $exclude) ?: [];
  172. if (!\is_array($imported)) {
  173. $imported = [$imported];
  174. }
  175. foreach ($imported as $subCollection) {
  176. $this->addPrefix($subCollection, $prefixes ?: $prefix, $trailingSlashOnRoot);
  177. if (null !== $hosts) {
  178. $this->addHost($subCollection, $hosts);
  179. }
  180. if (null !== $condition) {
  181. $subCollection->setCondition($condition);
  182. }
  183. if (null !== $schemes) {
  184. $subCollection->setSchemes($schemes);
  185. }
  186. if (null !== $methods) {
  187. $subCollection->setMethods($methods);
  188. }
  189. if (null !== $namePrefix) {
  190. $subCollection->addNamePrefix($namePrefix);
  191. }
  192. $subCollection->addDefaults($defaults);
  193. $subCollection->addRequirements($requirements);
  194. $subCollection->addOptions($options);
  195. $collection->addCollection($subCollection);
  196. }
  197. }
  198. /**
  199. * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors
  200. * or when the XML structure is not as expected by the scheme -
  201. * see validate()
  202. */
  203. protected function loadFile(string $file): \DOMDocument
  204. {
  205. return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH);
  206. }
  207. /**
  208. * Parses the config elements (default, requirement, option).
  209. *
  210. * @throws \InvalidArgumentException When the XML is invalid
  211. */
  212. private function parseConfigs(\DOMElement $node, string $path): array
  213. {
  214. $defaults = [];
  215. $requirements = [];
  216. $options = [];
  217. $condition = null;
  218. $prefixes = [];
  219. $paths = [];
  220. $hosts = [];
  221. /** @var \DOMElement $n */
  222. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  223. if ($node !== $n->parentNode) {
  224. continue;
  225. }
  226. switch ($n->localName) {
  227. case 'path':
  228. $paths[$n->getAttribute('locale')] = trim($n->textContent);
  229. break;
  230. case 'host':
  231. $hosts[$n->getAttribute('locale')] = trim($n->textContent);
  232. break;
  233. case 'prefix':
  234. $prefixes[$n->getAttribute('locale')] = trim($n->textContent);
  235. break;
  236. case 'default':
  237. if ($this->isElementValueNull($n)) {
  238. $defaults[$n->getAttribute('key')] = null;
  239. } else {
  240. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  241. }
  242. break;
  243. case 'requirement':
  244. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  245. break;
  246. case 'option':
  247. $options[$n->getAttribute('key')] = XmlUtils::phpize(trim($n->textContent));
  248. break;
  249. case 'condition':
  250. $condition = trim($n->textContent);
  251. break;
  252. case 'resource':
  253. break;
  254. default:
  255. throw new \InvalidArgumentException(\sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path));
  256. }
  257. }
  258. if ($controller = $node->getAttribute('controller')) {
  259. if (isset($defaults['_controller'])) {
  260. $name = $node->hasAttribute('id') ? \sprintf('"%s".', $node->getAttribute('id')) : \sprintf('the "%s" tag.', $node->tagName);
  261. throw new \InvalidArgumentException(\sprintf('The routing file "%s" must not specify both the "controller" attribute and the defaults key "_controller" for ', $path).$name);
  262. }
  263. $defaults['_controller'] = $controller;
  264. }
  265. if ($node->hasAttribute('locale')) {
  266. $defaults['_locale'] = $node->getAttribute('locale');
  267. }
  268. if ($node->hasAttribute('format')) {
  269. $defaults['_format'] = $node->getAttribute('format');
  270. }
  271. if ($node->hasAttribute('utf8')) {
  272. $options['utf8'] = XmlUtils::phpize($node->getAttribute('utf8'));
  273. }
  274. if ($stateless = $node->getAttribute('stateless')) {
  275. if (isset($defaults['_stateless'])) {
  276. $name = $node->hasAttribute('id') ? \sprintf('"%s".', $node->getAttribute('id')) : \sprintf('the "%s" tag.', $node->tagName);
  277. throw new \InvalidArgumentException(\sprintf('The routing file "%s" must not specify both the "stateless" attribute and the defaults key "_stateless" for ', $path).$name);
  278. }
  279. $defaults['_stateless'] = XmlUtils::phpize($stateless);
  280. }
  281. if (!$hosts) {
  282. $hosts = $node->hasAttribute('host') ? $node->getAttribute('host') : null;
  283. }
  284. return [$defaults, $requirements, $options, $condition, $paths, $prefixes, $hosts];
  285. }
  286. /**
  287. * Parses the "default" elements.
  288. */
  289. private function parseDefaultsConfig(\DOMElement $element, string $path): array|bool|float|int|string|null
  290. {
  291. if ($this->isElementValueNull($element)) {
  292. return null;
  293. }
  294. // Check for existing element nodes in the default element. There can
  295. // only be a single element inside a default element. So this element
  296. // (if one was found) can safely be returned.
  297. foreach ($element->childNodes as $child) {
  298. if (!$child instanceof \DOMElement) {
  299. continue;
  300. }
  301. if (self::NAMESPACE_URI !== $child->namespaceURI) {
  302. continue;
  303. }
  304. return $this->parseDefaultNode($child, $path);
  305. }
  306. // If the default element doesn't contain a nested "bool", "int", "float",
  307. // "string", "list", or "map" element, the element contents will be treated
  308. // as the string value of the associated default option.
  309. return trim($element->textContent);
  310. }
  311. /**
  312. * Recursively parses the value of a "default" element.
  313. *
  314. * @throws \InvalidArgumentException when the XML is invalid
  315. */
  316. private function parseDefaultNode(\DOMElement $node, string $path): array|bool|float|int|string|null
  317. {
  318. if ($this->isElementValueNull($node)) {
  319. return null;
  320. }
  321. switch ($node->localName) {
  322. case 'bool':
  323. return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue);
  324. case 'int':
  325. return (int) trim($node->nodeValue);
  326. case 'float':
  327. return (float) trim($node->nodeValue);
  328. case 'string':
  329. return trim($node->nodeValue);
  330. case 'list':
  331. $list = [];
  332. foreach ($node->childNodes as $element) {
  333. if (!$element instanceof \DOMElement) {
  334. continue;
  335. }
  336. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  337. continue;
  338. }
  339. $list[] = $this->parseDefaultNode($element, $path);
  340. }
  341. return $list;
  342. case 'map':
  343. $map = [];
  344. foreach ($node->childNodes as $element) {
  345. if (!$element instanceof \DOMElement) {
  346. continue;
  347. }
  348. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  349. continue;
  350. }
  351. $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path);
  352. }
  353. return $map;
  354. default:
  355. throw new \InvalidArgumentException(\sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path));
  356. }
  357. }
  358. private function isElementValueNull(\DOMElement $element): bool
  359. {
  360. $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  361. if (!$element->hasAttributeNS($namespaceUri, 'nil')) {
  362. return false;
  363. }
  364. return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
  365. }
  366. /**
  367. * Parses the deprecation elements.
  368. *
  369. * @throws \InvalidArgumentException When the XML is invalid
  370. */
  371. private function parseDeprecation(\DOMElement $node, string $path): array
  372. {
  373. $deprecatedNode = null;
  374. foreach ($node->childNodes as $child) {
  375. if (!$child instanceof \DOMElement || self::NAMESPACE_URI !== $child->namespaceURI) {
  376. continue;
  377. }
  378. if ('deprecated' !== $child->localName) {
  379. throw new \InvalidArgumentException(\sprintf('Invalid child element "%s" defined for alias "%s" in "%s".', $child->localName, $node->getAttribute('id'), $path));
  380. }
  381. $deprecatedNode = $child;
  382. }
  383. if (null === $deprecatedNode) {
  384. return [];
  385. }
  386. if (!$deprecatedNode->hasAttribute('package')) {
  387. throw new \InvalidArgumentException(\sprintf('The <deprecated> element in file "%s" must have a "package" attribute.', $path));
  388. }
  389. if (!$deprecatedNode->hasAttribute('version')) {
  390. throw new \InvalidArgumentException(\sprintf('The <deprecated> element in file "%s" must have a "version" attribute.', $path));
  391. }
  392. return [
  393. 'package' => $deprecatedNode->getAttribute('package'),
  394. 'version' => $deprecatedNode->getAttribute('version'),
  395. 'message' => trim($deprecatedNode->nodeValue),
  396. ];
  397. }
  398. }