XmlFileLoader.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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\Route;
  15. use Symfony\Component\Routing\RouteCollection;
  16. use Symfony\Component\Routing\RouteCompiler;
  17. /**
  18. * XmlFileLoader loads XML routing files.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. * @author Tobias Schultze <http://tobion.de>
  22. */
  23. class XmlFileLoader extends FileLoader
  24. {
  25. const NAMESPACE_URI = 'http://symfony.com/schema/routing';
  26. const SCHEME_PATH = '/schema/routing/routing-1.0.xsd';
  27. /**
  28. * Loads an XML file.
  29. *
  30. * @param string $file An XML file path
  31. * @param string|null $type The resource type
  32. *
  33. * @return RouteCollection A RouteCollection instance
  34. *
  35. * @throws \InvalidArgumentException when the file cannot be loaded or when the XML cannot be
  36. * parsed because it does not validate against the scheme
  37. */
  38. public function load($file, string $type = null)
  39. {
  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. * @param \DOMElement $node Element to parse
  57. * @param string $path Full path of the XML file being processed
  58. * @param string $file Loaded file name
  59. *
  60. * @throws \InvalidArgumentException When the XML is invalid
  61. */
  62. protected function parseNode(RouteCollection $collection, \DOMElement $node, string $path, string $file)
  63. {
  64. if (self::NAMESPACE_URI !== $node->namespaceURI) {
  65. return;
  66. }
  67. switch ($node->localName) {
  68. case 'route':
  69. $this->parseRoute($collection, $node, $path);
  70. break;
  71. case 'import':
  72. $this->parseImport($collection, $node, $path, $file);
  73. break;
  74. default:
  75. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "route" or "import".', $node->localName, $path));
  76. }
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. public function supports($resource, string $type = null)
  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. * @param \DOMElement $node Element to parse that represents a Route
  89. * @param string $path Full path of the XML file being processed
  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. $schemes = preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, PREG_SPLIT_NO_EMPTY);
  99. $methods = preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, PREG_SPLIT_NO_EMPTY);
  100. list($defaults, $requirements, $options, $condition, $paths) = $this->parseConfigs($node, $path);
  101. if (!$paths && '' === $node->getAttribute('path')) {
  102. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must have a "path" attribute or <path> child nodes.', $path));
  103. }
  104. if ($paths && '' !== $node->getAttribute('path')) {
  105. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must not have both a "path" attribute and <path> child nodes.', $path));
  106. }
  107. if (!$paths) {
  108. $route = new Route($node->getAttribute('path'), $defaults, $requirements, $options, $node->getAttribute('host'), $schemes, $methods, $condition);
  109. $collection->add($id, $route);
  110. } else {
  111. foreach ($paths as $locale => $p) {
  112. $defaults['_locale'] = $locale;
  113. $defaults['_canonical_route'] = $id;
  114. $requirements['_locale'] = preg_quote($locale, RouteCompiler::REGEX_DELIMITER);
  115. $route = new Route($p, $defaults, $requirements, $options, $node->getAttribute('host'), $schemes, $methods, $condition);
  116. $collection->add($id.'.'.$locale, $route);
  117. }
  118. }
  119. }
  120. /**
  121. * Parses an import and adds the routes in the resource to the RouteCollection.
  122. *
  123. * @param \DOMElement $node Element to parse that represents a Route
  124. * @param string $path Full path of the XML file being processed
  125. * @param string $file Loaded file name
  126. *
  127. * @throws \InvalidArgumentException When the XML is invalid
  128. */
  129. protected function parseImport(RouteCollection $collection, \DOMElement $node, string $path, string $file)
  130. {
  131. if ('' === $resource = $node->getAttribute('resource')) {
  132. throw new \InvalidArgumentException(sprintf('The <import> element in file "%s" must have a "resource" attribute.', $path));
  133. }
  134. $type = $node->getAttribute('type');
  135. $prefix = $node->getAttribute('prefix');
  136. $host = $node->hasAttribute('host') ? $node->getAttribute('host') : null;
  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. list($defaults, $requirements, $options, $condition, /* $paths */, $prefixes) = $this->parseConfigs($node, $path);
  141. if ('' !== $prefix && $prefixes) {
  142. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must not have both a "prefix" attribute and <prefix> child nodes.', $path));
  143. }
  144. $exclude = [];
  145. foreach ($node->childNodes as $child) {
  146. if ($child instanceof \DOMElement && $child->localName === $exclude && self::NAMESPACE_URI === $child->namespaceURI) {
  147. $exclude[] = $child->nodeValue;
  148. }
  149. }
  150. if ($node->hasAttribute('exclude')) {
  151. if ($exclude) {
  152. throw new \InvalidArgumentException('You cannot use both the attribute "exclude" and <exclude> tags at the same time.');
  153. }
  154. $exclude = [$node->getAttribute('exclude')];
  155. }
  156. $this->setCurrentDir(\dirname($path));
  157. /** @var RouteCollection[] $imported */
  158. $imported = $this->import($resource, ('' !== $type ? $type : null), false, $file, $exclude) ?: [];
  159. if (!\is_array($imported)) {
  160. $imported = [$imported];
  161. }
  162. foreach ($imported as $subCollection) {
  163. /* @var $subCollection RouteCollection */
  164. if ('' !== $prefix || !$prefixes) {
  165. $subCollection->addPrefix($prefix);
  166. if (!$trailingSlashOnRoot) {
  167. $rootPath = (new Route(trim(trim($prefix), '/').'/'))->getPath();
  168. foreach ($subCollection->all() as $route) {
  169. if ($route->getPath() === $rootPath) {
  170. $route->setPath(rtrim($rootPath, '/'));
  171. }
  172. }
  173. }
  174. } else {
  175. foreach ($prefixes as $locale => $localePrefix) {
  176. $prefixes[$locale] = trim(trim($localePrefix), '/');
  177. }
  178. foreach ($subCollection->all() as $name => $route) {
  179. if (null === $locale = $route->getDefault('_locale')) {
  180. $subCollection->remove($name);
  181. foreach ($prefixes as $locale => $localePrefix) {
  182. $localizedRoute = clone $route;
  183. $localizedRoute->setPath($localePrefix.(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  184. $localizedRoute->setDefault('_locale', $locale);
  185. $localizedRoute->setDefault('_canonical_route', $name);
  186. $subCollection->add($name.'.'.$locale, $localizedRoute);
  187. }
  188. } elseif (!isset($prefixes[$locale])) {
  189. throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix when imported in "%s".', $name, $locale, $path));
  190. } else {
  191. $route->setPath($prefixes[$locale].(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  192. $subCollection->add($name, $route);
  193. }
  194. }
  195. }
  196. if (null !== $host) {
  197. $subCollection->setHost($host);
  198. }
  199. if (null !== $condition) {
  200. $subCollection->setCondition($condition);
  201. }
  202. if (null !== $schemes) {
  203. $subCollection->setSchemes($schemes);
  204. }
  205. if (null !== $methods) {
  206. $subCollection->setMethods($methods);
  207. }
  208. $subCollection->addDefaults($defaults);
  209. $subCollection->addRequirements($requirements);
  210. $subCollection->addOptions($options);
  211. if ($namePrefix = $node->getAttribute('name-prefix')) {
  212. $subCollection->addNamePrefix($namePrefix);
  213. }
  214. $collection->addCollection($subCollection);
  215. }
  216. }
  217. /**
  218. * Loads an XML file.
  219. *
  220. * @param string $file An XML file path
  221. *
  222. * @return \DOMDocument
  223. *
  224. * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors
  225. * or when the XML structure is not as expected by the scheme -
  226. * see validate()
  227. */
  228. protected function loadFile(string $file)
  229. {
  230. return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH);
  231. }
  232. /**
  233. * Parses the config elements (default, requirement, option).
  234. *
  235. * @throws \InvalidArgumentException When the XML is invalid
  236. */
  237. private function parseConfigs(\DOMElement $node, string $path): array
  238. {
  239. $defaults = [];
  240. $requirements = [];
  241. $options = [];
  242. $condition = null;
  243. $prefixes = [];
  244. $paths = [];
  245. /** @var \DOMElement $n */
  246. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  247. if ($node !== $n->parentNode) {
  248. continue;
  249. }
  250. switch ($n->localName) {
  251. case 'path':
  252. $paths[$n->getAttribute('locale')] = trim($n->textContent);
  253. break;
  254. case 'prefix':
  255. $prefixes[$n->getAttribute('locale')] = trim($n->textContent);
  256. break;
  257. case 'default':
  258. if ($this->isElementValueNull($n)) {
  259. $defaults[$n->getAttribute('key')] = null;
  260. } else {
  261. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  262. }
  263. break;
  264. case 'requirement':
  265. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  266. break;
  267. case 'option':
  268. $options[$n->getAttribute('key')] = XmlUtils::phpize(trim($n->textContent));
  269. break;
  270. case 'condition':
  271. $condition = trim($n->textContent);
  272. break;
  273. default:
  274. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path));
  275. }
  276. }
  277. if ($controller = $node->getAttribute('controller')) {
  278. if (isset($defaults['_controller'])) {
  279. $name = $node->hasAttribute('id') ? sprintf('"%s"', $node->getAttribute('id')) : sprintf('the "%s" tag', $node->tagName);
  280. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" attribute and the defaults key "_controller" for %s.', $path, $name));
  281. }
  282. $defaults['_controller'] = $controller;
  283. }
  284. if ($node->hasAttribute('locale')) {
  285. $defaults['_locale'] = $node->getAttribute('locale');
  286. }
  287. if ($node->hasAttribute('format')) {
  288. $defaults['_format'] = $node->getAttribute('format');
  289. }
  290. if ($node->hasAttribute('utf8')) {
  291. $options['utf8'] = XmlUtils::phpize($node->getAttribute('utf8'));
  292. }
  293. return [$defaults, $requirements, $options, $condition, $paths, $prefixes];
  294. }
  295. /**
  296. * Parses the "default" elements.
  297. *
  298. * @return array|bool|float|int|string|null The parsed value of the "default" element
  299. */
  300. private function parseDefaultsConfig(\DOMElement $element, string $path)
  301. {
  302. if ($this->isElementValueNull($element)) {
  303. return null;
  304. }
  305. // Check for existing element nodes in the default element. There can
  306. // only be a single element inside a default element. So this element
  307. // (if one was found) can safely be returned.
  308. foreach ($element->childNodes as $child) {
  309. if (!$child instanceof \DOMElement) {
  310. continue;
  311. }
  312. if (self::NAMESPACE_URI !== $child->namespaceURI) {
  313. continue;
  314. }
  315. return $this->parseDefaultNode($child, $path);
  316. }
  317. // If the default element doesn't contain a nested "bool", "int", "float",
  318. // "string", "list", or "map" element, the element contents will be treated
  319. // as the string value of the associated default option.
  320. return trim($element->textContent);
  321. }
  322. /**
  323. * Recursively parses the value of a "default" element.
  324. *
  325. * @return array|bool|float|int|string The parsed value
  326. *
  327. * @throws \InvalidArgumentException when the XML is invalid
  328. */
  329. private function parseDefaultNode(\DOMElement $node, string $path)
  330. {
  331. if ($this->isElementValueNull($node)) {
  332. return null;
  333. }
  334. switch ($node->localName) {
  335. case 'bool':
  336. return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue);
  337. case 'int':
  338. return (int) trim($node->nodeValue);
  339. case 'float':
  340. return (float) trim($node->nodeValue);
  341. case 'string':
  342. return trim($node->nodeValue);
  343. case 'list':
  344. $list = [];
  345. foreach ($node->childNodes as $element) {
  346. if (!$element instanceof \DOMElement) {
  347. continue;
  348. }
  349. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  350. continue;
  351. }
  352. $list[] = $this->parseDefaultNode($element, $path);
  353. }
  354. return $list;
  355. case 'map':
  356. $map = [];
  357. foreach ($node->childNodes as $element) {
  358. if (!$element instanceof \DOMElement) {
  359. continue;
  360. }
  361. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  362. continue;
  363. }
  364. $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path);
  365. }
  366. return $map;
  367. default:
  368. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path));
  369. }
  370. }
  371. private function isElementValueNull(\DOMElement $element): bool
  372. {
  373. $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  374. if (!$element->hasAttributeNS($namespaceUri, 'nil')) {
  375. return false;
  376. }
  377. return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
  378. }
  379. }