XmlFileLoader.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 RouteCollection $collection Collection to associate with the node
  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 RouteCollection $collection RouteCollection instance
  89. * @param \DOMElement $node Element to parse that represents a Route
  90. * @param string $path Full path of the XML file being processed
  91. *
  92. * @throws \InvalidArgumentException When the XML is invalid
  93. */
  94. protected function parseRoute(RouteCollection $collection, \DOMElement $node, $path)
  95. {
  96. if ('' === $id = $node->getAttribute('id')) {
  97. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must have an "id" attribute.', $path));
  98. }
  99. $schemes = preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, PREG_SPLIT_NO_EMPTY);
  100. $methods = preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, PREG_SPLIT_NO_EMPTY);
  101. list($defaults, $requirements, $options, $condition, $paths) = $this->parseConfigs($node, $path);
  102. if (!$paths && '' === $node->getAttribute('path')) {
  103. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must have a "path" attribute or <path> child nodes.', $path));
  104. }
  105. if ($paths && '' !== $node->getAttribute('path')) {
  106. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must not have both a "path" attribute and <path> child nodes.', $path));
  107. }
  108. if (!$paths) {
  109. $route = new Route($node->getAttribute('path'), $defaults, $requirements, $options, $node->getAttribute('host'), $schemes, $methods, $condition);
  110. $collection->add($id, $route);
  111. } else {
  112. foreach ($paths as $locale => $p) {
  113. $defaults['_locale'] = $locale;
  114. $defaults['_canonical_route'] = $id;
  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 RouteCollection $collection RouteCollection instance
  124. * @param \DOMElement $node Element to parse that represents a Route
  125. * @param string $path Full path of the XML file being processed
  126. * @param string $file Loaded file name
  127. *
  128. * @throws \InvalidArgumentException When the XML is invalid
  129. */
  130. protected function parseImport(RouteCollection $collection, \DOMElement $node, $path, $file)
  131. {
  132. if ('' === $resource = $node->getAttribute('resource')) {
  133. throw new \InvalidArgumentException(sprintf('The <import> element in file "%s" must have a "resource" attribute.', $path));
  134. }
  135. $type = $node->getAttribute('type');
  136. $prefix = $node->getAttribute('prefix');
  137. $host = $node->hasAttribute('host') ? $node->getAttribute('host') : null;
  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. list($defaults, $requirements, $options, $condition, /* $paths */, $prefixes) = $this->parseConfigs($node, $path);
  142. if ('' !== $prefix && $prefixes) {
  143. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must not have both a "prefix" attribute and <prefix> child nodes.', $path));
  144. }
  145. $this->setCurrentDir(\dirname($path));
  146. $imported = $this->import($resource, ('' !== $type ? $type : null), false, $file);
  147. if (!\is_array($imported)) {
  148. $imported = [$imported];
  149. }
  150. foreach ($imported as $subCollection) {
  151. /* @var $subCollection RouteCollection */
  152. if ('' !== $prefix || !$prefixes) {
  153. $subCollection->addPrefix($prefix);
  154. if (!$trailingSlashOnRoot) {
  155. $rootPath = (new Route(trim(trim($prefix), '/').'/'))->getPath();
  156. foreach ($subCollection->all() as $route) {
  157. if ($route->getPath() === $rootPath) {
  158. $route->setPath(rtrim($rootPath, '/'));
  159. }
  160. }
  161. }
  162. } else {
  163. foreach ($prefixes as $locale => $localePrefix) {
  164. $prefixes[$locale] = trim(trim($localePrefix), '/');
  165. }
  166. foreach ($subCollection->all() as $name => $route) {
  167. if (null === $locale = $route->getDefault('_locale')) {
  168. $subCollection->remove($name);
  169. foreach ($prefixes as $locale => $localePrefix) {
  170. $localizedRoute = clone $route;
  171. $localizedRoute->setPath($localePrefix.(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  172. $localizedRoute->setDefault('_locale', $locale);
  173. $localizedRoute->setDefault('_canonical_route', $name);
  174. $subCollection->add($name.'.'.$locale, $localizedRoute);
  175. }
  176. } elseif (!isset($prefixes[$locale])) {
  177. throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix when imported in "%s".', $name, $locale, $path));
  178. } else {
  179. $route->setPath($prefixes[$locale].(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
  180. $subCollection->add($name, $route);
  181. }
  182. }
  183. }
  184. if (null !== $host) {
  185. $subCollection->setHost($host);
  186. }
  187. if (null !== $condition) {
  188. $subCollection->setCondition($condition);
  189. }
  190. if (null !== $schemes) {
  191. $subCollection->setSchemes($schemes);
  192. }
  193. if (null !== $methods) {
  194. $subCollection->setMethods($methods);
  195. }
  196. $subCollection->addDefaults($defaults);
  197. $subCollection->addRequirements($requirements);
  198. $subCollection->addOptions($options);
  199. if ($namePrefix = $node->getAttribute('name-prefix')) {
  200. $subCollection->addNamePrefix($namePrefix);
  201. }
  202. $collection->addCollection($subCollection);
  203. }
  204. }
  205. /**
  206. * Loads an XML file.
  207. *
  208. * @param string $file An XML file path
  209. *
  210. * @return \DOMDocument
  211. *
  212. * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors
  213. * or when the XML structure is not as expected by the scheme -
  214. * see validate()
  215. */
  216. protected function loadFile($file)
  217. {
  218. return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH);
  219. }
  220. /**
  221. * Parses the config elements (default, requirement, option).
  222. *
  223. * @param \DOMElement $node Element to parse that contains the configs
  224. * @param string $path Full path of the XML file being processed
  225. *
  226. * @return array An array with the defaults as first item, requirements as second and options as third
  227. *
  228. * @throws \InvalidArgumentException When the XML is invalid
  229. */
  230. private function parseConfigs(\DOMElement $node, $path)
  231. {
  232. $defaults = [];
  233. $requirements = [];
  234. $options = [];
  235. $condition = null;
  236. $prefixes = [];
  237. $paths = [];
  238. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  239. if ($node !== $n->parentNode) {
  240. continue;
  241. }
  242. switch ($n->localName) {
  243. case 'path':
  244. $paths[$n->getAttribute('locale')] = trim($n->textContent);
  245. break;
  246. case 'prefix':
  247. $prefixes[$n->getAttribute('locale')] = trim($n->textContent);
  248. break;
  249. case 'default':
  250. if ($this->isElementValueNull($n)) {
  251. $defaults[$n->getAttribute('key')] = null;
  252. } else {
  253. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  254. }
  255. break;
  256. case 'requirement':
  257. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  258. break;
  259. case 'option':
  260. $options[$n->getAttribute('key')] = trim($n->textContent);
  261. break;
  262. case 'condition':
  263. $condition = trim($n->textContent);
  264. break;
  265. default:
  266. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path));
  267. }
  268. }
  269. if ($controller = $node->getAttribute('controller')) {
  270. if (isset($defaults['_controller'])) {
  271. $name = $node->hasAttribute('id') ? sprintf('"%s"', $node->getAttribute('id')) : sprintf('the "%s" tag', $node->tagName);
  272. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" attribute and the defaults key "_controller" for %s.', $path, $name));
  273. }
  274. $defaults['_controller'] = $controller;
  275. }
  276. return [$defaults, $requirements, $options, $condition, $paths, $prefixes];
  277. }
  278. /**
  279. * Parses the "default" elements.
  280. *
  281. * @param \DOMElement $element The "default" element to parse
  282. * @param string $path Full path of the XML file being processed
  283. *
  284. * @return array|bool|float|int|string|null The parsed value of the "default" element
  285. */
  286. private function parseDefaultsConfig(\DOMElement $element, $path)
  287. {
  288. if ($this->isElementValueNull($element)) {
  289. return;
  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. * @param \DOMElement $node The node value
  312. * @param string $path Full path of the XML file being processed
  313. *
  314. * @return array|bool|float|int|string The parsed value
  315. *
  316. * @throws \InvalidArgumentException when the XML is invalid
  317. */
  318. private function parseDefaultNode(\DOMElement $node, $path)
  319. {
  320. if ($this->isElementValueNull($node)) {
  321. return;
  322. }
  323. switch ($node->localName) {
  324. case 'bool':
  325. return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue);
  326. case 'int':
  327. return (int) trim($node->nodeValue);
  328. case 'float':
  329. return (float) trim($node->nodeValue);
  330. case 'string':
  331. return trim($node->nodeValue);
  332. case 'list':
  333. $list = [];
  334. foreach ($node->childNodes as $element) {
  335. if (!$element instanceof \DOMElement) {
  336. continue;
  337. }
  338. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  339. continue;
  340. }
  341. $list[] = $this->parseDefaultNode($element, $path);
  342. }
  343. return $list;
  344. case 'map':
  345. $map = [];
  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. $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path);
  354. }
  355. return $map;
  356. default:
  357. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path));
  358. }
  359. }
  360. private function isElementValueNull(\DOMElement $element)
  361. {
  362. $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  363. if (!$element->hasAttributeNS($namespaceUri, 'nil')) {
  364. return false;
  365. }
  366. return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
  367. }
  368. }