XmlFileLoader.php 17 KB

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