Brak opisu

XmlFileLoader.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. public const NAMESPACE_URI = 'http://symfony.com/schema/routing';
  26. public 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, $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, $path, $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, $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, $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. [$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, $path, $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. [$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->setRequirement('_locale', preg_quote($locale, RouteCompiler::REGEX_DELIMITER));
  186. $localizedRoute->setDefault('_canonical_route', $name);
  187. $subCollection->add($name.'.'.$locale, $localizedRoute);
  188. }
  189. } elseif (!isset($prefixes[$locale])) {
  190. throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix when imported in "%s".', $name, $locale, $path));
  191. } else {
  192. $route->setPath($prefixes[$locale].(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  193. $subCollection->add($name, $route);
  194. }
  195. }
  196. }
  197. if (null !== $host) {
  198. $subCollection->setHost($host);
  199. }
  200. if (null !== $condition) {
  201. $subCollection->setCondition($condition);
  202. }
  203. if (null !== $schemes) {
  204. $subCollection->setSchemes($schemes);
  205. }
  206. if (null !== $methods) {
  207. $subCollection->setMethods($methods);
  208. }
  209. $subCollection->addDefaults($defaults);
  210. $subCollection->addRequirements($requirements);
  211. $subCollection->addOptions($options);
  212. if ($namePrefix = $node->getAttribute('name-prefix')) {
  213. $subCollection->addNamePrefix($namePrefix);
  214. }
  215. $collection->addCollection($subCollection);
  216. }
  217. }
  218. /**
  219. * Loads an XML file.
  220. *
  221. * @param string $file An XML file path
  222. *
  223. * @return \DOMDocument
  224. *
  225. * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors
  226. * or when the XML structure is not as expected by the scheme -
  227. * see validate()
  228. */
  229. protected function loadFile($file)
  230. {
  231. return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH);
  232. }
  233. /**
  234. * Parses the config elements (default, requirement, option).
  235. *
  236. * @throws \InvalidArgumentException When the XML is invalid
  237. */
  238. private function parseConfigs(\DOMElement $node, string $path): array
  239. {
  240. $defaults = [];
  241. $requirements = [];
  242. $options = [];
  243. $condition = null;
  244. $prefixes = [];
  245. $paths = [];
  246. /** @var \DOMElement $n */
  247. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  248. if ($node !== $n->parentNode) {
  249. continue;
  250. }
  251. switch ($n->localName) {
  252. case 'path':
  253. $paths[$n->getAttribute('locale')] = trim($n->textContent);
  254. break;
  255. case 'prefix':
  256. $prefixes[$n->getAttribute('locale')] = trim($n->textContent);
  257. break;
  258. case 'default':
  259. if ($this->isElementValueNull($n)) {
  260. $defaults[$n->getAttribute('key')] = null;
  261. } else {
  262. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  263. }
  264. break;
  265. case 'requirement':
  266. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  267. break;
  268. case 'option':
  269. $options[$n->getAttribute('key')] = XmlUtils::phpize(trim($n->textContent));
  270. break;
  271. case 'condition':
  272. $condition = trim($n->textContent);
  273. break;
  274. default:
  275. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path));
  276. }
  277. }
  278. if ($controller = $node->getAttribute('controller')) {
  279. if (isset($defaults['_controller'])) {
  280. $name = $node->hasAttribute('id') ? sprintf('"%s".', $node->getAttribute('id')) : sprintf('the "%s" tag.', $node->tagName);
  281. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" attribute and the defaults key "_controller" for ', $path).$name);
  282. }
  283. $defaults['_controller'] = $controller;
  284. }
  285. if ($node->hasAttribute('locale')) {
  286. $defaults['_locale'] = $node->getAttribute('locale');
  287. }
  288. if ($node->hasAttribute('format')) {
  289. $defaults['_format'] = $node->getAttribute('format');
  290. }
  291. if ($node->hasAttribute('utf8')) {
  292. $options['utf8'] = XmlUtils::phpize($node->getAttribute('utf8'));
  293. }
  294. return [$defaults, $requirements, $options, $condition, $paths, $prefixes];
  295. }
  296. /**
  297. * Parses the "default" elements.
  298. *
  299. * @return array|bool|float|int|string|null The parsed value of the "default" element
  300. */
  301. private function parseDefaultsConfig(\DOMElement $element, string $path)
  302. {
  303. if ($this->isElementValueNull($element)) {
  304. return null;
  305. }
  306. // Check for existing element nodes in the default element. There can
  307. // only be a single element inside a default element. So this element
  308. // (if one was found) can safely be returned.
  309. foreach ($element->childNodes as $child) {
  310. if (!$child instanceof \DOMElement) {
  311. continue;
  312. }
  313. if (self::NAMESPACE_URI !== $child->namespaceURI) {
  314. continue;
  315. }
  316. return $this->parseDefaultNode($child, $path);
  317. }
  318. // If the default element doesn't contain a nested "bool", "int", "float",
  319. // "string", "list", or "map" element, the element contents will be treated
  320. // as the string value of the associated default option.
  321. return trim($element->textContent);
  322. }
  323. /**
  324. * Recursively parses the value of a "default" element.
  325. *
  326. * @return array|bool|float|int|string|null The parsed value
  327. *
  328. * @throws \InvalidArgumentException when the XML is invalid
  329. */
  330. private function parseDefaultNode(\DOMElement $node, string $path)
  331. {
  332. if ($this->isElementValueNull($node)) {
  333. return null;
  334. }
  335. switch ($node->localName) {
  336. case 'bool':
  337. return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue);
  338. case 'int':
  339. return (int) trim($node->nodeValue);
  340. case 'float':
  341. return (float) trim($node->nodeValue);
  342. case 'string':
  343. return trim($node->nodeValue);
  344. case 'list':
  345. $list = [];
  346. foreach ($node->childNodes as $element) {
  347. if (!$element instanceof \DOMElement) {
  348. continue;
  349. }
  350. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  351. continue;
  352. }
  353. $list[] = $this->parseDefaultNode($element, $path);
  354. }
  355. return $list;
  356. case 'map':
  357. $map = [];
  358. foreach ($node->childNodes as $element) {
  359. if (!$element instanceof \DOMElement) {
  360. continue;
  361. }
  362. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  363. continue;
  364. }
  365. $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path);
  366. }
  367. return $map;
  368. default:
  369. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path));
  370. }
  371. }
  372. private function isElementValueNull(\DOMElement $element): bool
  373. {
  374. $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  375. if (!$element->hasAttributeNS($namespaceUri, 'nil')) {
  376. return false;
  377. }
  378. return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
  379. }
  380. }