You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

437 lines
16 KiB

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