XmlFileLoader.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. * Loads an XML file.
  33. *
  34. * @param string $file An XML file path
  35. * @param string|null $type The resource type
  36. *
  37. * @return RouteCollection A RouteCollection instance
  38. *
  39. * @throws \InvalidArgumentException when the file cannot be loaded or when the XML cannot be
  40. * parsed because it does not validate against the scheme
  41. */
  42. public function load($file, string $type = null)
  43. {
  44. $path = $this->locator->locate($file);
  45. $xml = $this->loadFile($path);
  46. $collection = new RouteCollection();
  47. $collection->addResource(new FileResource($path));
  48. // process routes and imports
  49. foreach ($xml->documentElement->childNodes as $node) {
  50. if (!$node instanceof \DOMElement) {
  51. continue;
  52. }
  53. $this->parseNode($collection, $node, $path, $file);
  54. }
  55. return $collection;
  56. }
  57. /**
  58. * Parses a node from a loaded XML file.
  59. *
  60. * @param \DOMElement $node Element to parse
  61. * @param string $path Full path of the XML file being processed
  62. * @param string $file Loaded file name
  63. *
  64. * @throws \InvalidArgumentException When the XML is invalid
  65. */
  66. protected function parseNode(RouteCollection $collection, \DOMElement $node, string $path, string $file)
  67. {
  68. if (self::NAMESPACE_URI !== $node->namespaceURI) {
  69. return;
  70. }
  71. switch ($node->localName) {
  72. case 'route':
  73. $this->parseRoute($collection, $node, $path);
  74. break;
  75. case 'import':
  76. $this->parseImport($collection, $node, $path, $file);
  77. break;
  78. default:
  79. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "route" or "import".', $node->localName, $path));
  80. }
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function supports($resource, string $type = null)
  86. {
  87. return \is_string($resource) && 'xml' === pathinfo($resource, \PATHINFO_EXTENSION) && (!$type || 'xml' === $type);
  88. }
  89. /**
  90. * Parses a route and adds it to the RouteCollection.
  91. *
  92. * @param \DOMElement $node Element to parse that represents a Route
  93. * @param string $path Full path of the XML file being processed
  94. *
  95. * @throws \InvalidArgumentException When the XML is invalid
  96. */
  97. protected function parseRoute(RouteCollection $collection, \DOMElement $node, string $path)
  98. {
  99. if ('' === $id = $node->getAttribute('id')) {
  100. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must have an "id" attribute.', $path));
  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. * @param \DOMElement $node Element to parse that represents a Route
  126. * @param string $path Full path of the XML file being processed
  127. * @param string $file Loaded file name
  128. *
  129. * @throws \InvalidArgumentException When the XML is invalid
  130. */
  131. protected function parseImport(RouteCollection $collection, \DOMElement $node, string $path, string $file)
  132. {
  133. if ('' === $resource = $node->getAttribute('resource')) {
  134. throw new \InvalidArgumentException(sprintf('The <import> element in file "%s" must have a "resource" attribute.', $path));
  135. }
  136. $type = $node->getAttribute('type');
  137. $prefix = $node->getAttribute('prefix');
  138. $schemes = $node->hasAttribute('schemes') ? preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, \PREG_SPLIT_NO_EMPTY) : null;
  139. $methods = $node->hasAttribute('methods') ? preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, \PREG_SPLIT_NO_EMPTY) : null;
  140. $trailingSlashOnRoot = $node->hasAttribute('trailing-slash-on-root') ? XmlUtils::phpize($node->getAttribute('trailing-slash-on-root')) : true;
  141. $namePrefix = $node->getAttribute('name-prefix') ?: null;
  142. [$defaults, $requirements, $options, $condition, /* $paths */, $prefixes, $hosts] = $this->parseConfigs($node, $path);
  143. if ('' !== $prefix && $prefixes) {
  144. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must not have both a "prefix" attribute and <prefix> child nodes.', $path));
  145. }
  146. $exclude = [];
  147. foreach ($node->childNodes as $child) {
  148. if ($child instanceof \DOMElement && $child->localName === $exclude && self::NAMESPACE_URI === $child->namespaceURI) {
  149. $exclude[] = $child->nodeValue;
  150. }
  151. }
  152. if ($node->hasAttribute('exclude')) {
  153. if ($exclude) {
  154. throw new \InvalidArgumentException('You cannot use both the attribute "exclude" and <exclude> tags at the same time.');
  155. }
  156. $exclude = [$node->getAttribute('exclude')];
  157. }
  158. $this->setCurrentDir(\dirname($path));
  159. /** @var RouteCollection[] $imported */
  160. $imported = $this->import($resource, ('' !== $type ? $type : null), false, $file, $exclude) ?: [];
  161. if (!\is_array($imported)) {
  162. $imported = [$imported];
  163. }
  164. foreach ($imported as $subCollection) {
  165. $this->addPrefix($subCollection, $prefixes ?: $prefix, $trailingSlashOnRoot);
  166. if (null !== $hosts) {
  167. $this->addHost($subCollection, $hosts);
  168. }
  169. if (null !== $condition) {
  170. $subCollection->setCondition($condition);
  171. }
  172. if (null !== $schemes) {
  173. $subCollection->setSchemes($schemes);
  174. }
  175. if (null !== $methods) {
  176. $subCollection->setMethods($methods);
  177. }
  178. if (null !== $namePrefix) {
  179. $subCollection->addNamePrefix($namePrefix);
  180. }
  181. $subCollection->addDefaults($defaults);
  182. $subCollection->addRequirements($requirements);
  183. $subCollection->addOptions($options);
  184. $collection->addCollection($subCollection);
  185. }
  186. }
  187. /**
  188. * Loads an XML file.
  189. *
  190. * @param string $file An XML file path
  191. *
  192. * @return \DOMDocument
  193. *
  194. * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors
  195. * or when the XML structure is not as expected by the scheme -
  196. * see validate()
  197. */
  198. protected function loadFile(string $file)
  199. {
  200. return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH);
  201. }
  202. /**
  203. * Parses the config elements (default, requirement, option).
  204. *
  205. * @throws \InvalidArgumentException When the XML is invalid
  206. */
  207. private function parseConfigs(\DOMElement $node, string $path): array
  208. {
  209. $defaults = [];
  210. $requirements = [];
  211. $options = [];
  212. $condition = null;
  213. $prefixes = [];
  214. $paths = [];
  215. $hosts = [];
  216. /** @var \DOMElement $n */
  217. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  218. if ($node !== $n->parentNode) {
  219. continue;
  220. }
  221. switch ($n->localName) {
  222. case 'path':
  223. $paths[$n->getAttribute('locale')] = trim($n->textContent);
  224. break;
  225. case 'host':
  226. $hosts[$n->getAttribute('locale')] = trim($n->textContent);
  227. break;
  228. case 'prefix':
  229. $prefixes[$n->getAttribute('locale')] = trim($n->textContent);
  230. break;
  231. case 'default':
  232. if ($this->isElementValueNull($n)) {
  233. $defaults[$n->getAttribute('key')] = null;
  234. } else {
  235. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  236. }
  237. break;
  238. case 'requirement':
  239. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  240. break;
  241. case 'option':
  242. $options[$n->getAttribute('key')] = XmlUtils::phpize(trim($n->textContent));
  243. break;
  244. case 'condition':
  245. $condition = trim($n->textContent);
  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. * @return array|bool|float|int|string|null The parsed value of the "default" element
  283. */
  284. private function parseDefaultsConfig(\DOMElement $element, string $path)
  285. {
  286. if ($this->isElementValueNull($element)) {
  287. return null;
  288. }
  289. // Check for existing element nodes in the default element. There can
  290. // only be a single element inside a default element. So this element
  291. // (if one was found) can safely be returned.
  292. foreach ($element->childNodes as $child) {
  293. if (!$child instanceof \DOMElement) {
  294. continue;
  295. }
  296. if (self::NAMESPACE_URI !== $child->namespaceURI) {
  297. continue;
  298. }
  299. return $this->parseDefaultNode($child, $path);
  300. }
  301. // If the default element doesn't contain a nested "bool", "int", "float",
  302. // "string", "list", or "map" element, the element contents will be treated
  303. // as the string value of the associated default option.
  304. return trim($element->textContent);
  305. }
  306. /**
  307. * Recursively parses the value of a "default" element.
  308. *
  309. * @return array|bool|float|int|string The parsed value
  310. *
  311. * @throws \InvalidArgumentException when the XML is invalid
  312. */
  313. private function parseDefaultNode(\DOMElement $node, string $path)
  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. }