XmlFileLoader.php 18 KB

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