XmlFileLoader.php 18 KB

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