XmlFileLoader.php 17 KB

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