XmlFileLoader.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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')) || !$node->hasAttribute('path')) {
  97. throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must have an "id" and a "path" 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) = $this->parseConfigs($node, $path);
  102. $route = new Route($node->getAttribute('path'), $defaults, $requirements, $options, $node->getAttribute('host'), $schemes, $methods, $condition);
  103. $collection->add($id, $route);
  104. }
  105. /**
  106. * Parses an import and adds the routes in the resource to the RouteCollection.
  107. *
  108. * @param RouteCollection $collection RouteCollection instance
  109. * @param \DOMElement $node Element to parse that represents a Route
  110. * @param string $path Full path of the XML file being processed
  111. * @param string $file Loaded file name
  112. *
  113. * @throws \InvalidArgumentException When the XML is invalid
  114. */
  115. protected function parseImport(RouteCollection $collection, \DOMElement $node, $path, $file)
  116. {
  117. if ('' === $resource = $node->getAttribute('resource')) {
  118. throw new \InvalidArgumentException(sprintf('The <import> element in file "%s" must have a "resource" attribute.', $path));
  119. }
  120. $type = $node->getAttribute('type');
  121. $prefix = $node->getAttribute('prefix');
  122. $host = $node->hasAttribute('host') ? $node->getAttribute('host') : null;
  123. $schemes = $node->hasAttribute('schemes') ? preg_split('/[\s,\|]++/', $node->getAttribute('schemes'), -1, PREG_SPLIT_NO_EMPTY) : null;
  124. $methods = $node->hasAttribute('methods') ? preg_split('/[\s,\|]++/', $node->getAttribute('methods'), -1, PREG_SPLIT_NO_EMPTY) : null;
  125. list($defaults, $requirements, $options, $condition) = $this->parseConfigs($node, $path);
  126. $this->setCurrentDir(\dirname($path));
  127. $imported = $this->import($resource, ('' !== $type ? $type : null), false, $file);
  128. if (!\is_array($imported)) {
  129. $imported = [$imported];
  130. }
  131. foreach ($imported as $subCollection) {
  132. /* @var $subCollection RouteCollection */
  133. $subCollection->addPrefix($prefix);
  134. if (null !== $host) {
  135. $subCollection->setHost($host);
  136. }
  137. if (null !== $condition) {
  138. $subCollection->setCondition($condition);
  139. }
  140. if (null !== $schemes) {
  141. $subCollection->setSchemes($schemes);
  142. }
  143. if (null !== $methods) {
  144. $subCollection->setMethods($methods);
  145. }
  146. $subCollection->addDefaults($defaults);
  147. $subCollection->addRequirements($requirements);
  148. $subCollection->addOptions($options);
  149. $collection->addCollection($subCollection);
  150. }
  151. }
  152. /**
  153. * Loads an XML file.
  154. *
  155. * @param string $file An XML file path
  156. *
  157. * @return \DOMDocument
  158. *
  159. * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors
  160. * or when the XML structure is not as expected by the scheme -
  161. * see validate()
  162. */
  163. protected function loadFile($file)
  164. {
  165. return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH);
  166. }
  167. /**
  168. * Parses the config elements (default, requirement, option).
  169. *
  170. * @param \DOMElement $node Element to parse that contains the configs
  171. * @param string $path Full path of the XML file being processed
  172. *
  173. * @return array An array with the defaults as first item, requirements as second and options as third
  174. *
  175. * @throws \InvalidArgumentException When the XML is invalid
  176. */
  177. private function parseConfigs(\DOMElement $node, $path)
  178. {
  179. $defaults = [];
  180. $requirements = [];
  181. $options = [];
  182. $condition = null;
  183. /** @var \DOMElement $n */
  184. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  185. if ($node !== $n->parentNode) {
  186. continue;
  187. }
  188. switch ($n->localName) {
  189. case 'default':
  190. if ($this->isElementValueNull($n)) {
  191. $defaults[$n->getAttribute('key')] = null;
  192. } else {
  193. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  194. }
  195. break;
  196. case 'requirement':
  197. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  198. break;
  199. case 'option':
  200. $options[$n->getAttribute('key')] = XmlUtils::phpize(trim($n->textContent));
  201. break;
  202. case 'condition':
  203. $condition = trim($n->textContent);
  204. break;
  205. default:
  206. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path));
  207. }
  208. }
  209. if ($controller = $node->getAttribute('controller')) {
  210. if (isset($defaults['_controller'])) {
  211. $name = $node->hasAttribute('id') ? sprintf('"%s"', $node->getAttribute('id')) : sprintf('the "%s" tag', $node->tagName);
  212. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" attribute and the defaults key "_controller" for %s.', $path, $name));
  213. }
  214. $defaults['_controller'] = $controller;
  215. }
  216. return [$defaults, $requirements, $options, $condition];
  217. }
  218. /**
  219. * Parses the "default" elements.
  220. *
  221. * @param \DOMElement $element The "default" element to parse
  222. * @param string $path Full path of the XML file being processed
  223. *
  224. * @return array|bool|float|int|string|null The parsed value of the "default" element
  225. */
  226. private function parseDefaultsConfig(\DOMElement $element, $path)
  227. {
  228. if ($this->isElementValueNull($element)) {
  229. return;
  230. }
  231. // Check for existing element nodes in the default element. There can
  232. // only be a single element inside a default element. So this element
  233. // (if one was found) can safely be returned.
  234. foreach ($element->childNodes as $child) {
  235. if (!$child instanceof \DOMElement) {
  236. continue;
  237. }
  238. if (self::NAMESPACE_URI !== $child->namespaceURI) {
  239. continue;
  240. }
  241. return $this->parseDefaultNode($child, $path);
  242. }
  243. // If the default element doesn't contain a nested "bool", "int", "float",
  244. // "string", "list", or "map" element, the element contents will be treated
  245. // as the string value of the associated default option.
  246. return trim($element->textContent);
  247. }
  248. /**
  249. * Recursively parses the value of a "default" element.
  250. *
  251. * @param \DOMElement $node The node value
  252. * @param string $path Full path of the XML file being processed
  253. *
  254. * @return array|bool|float|int|string The parsed value
  255. *
  256. * @throws \InvalidArgumentException when the XML is invalid
  257. */
  258. private function parseDefaultNode(\DOMElement $node, $path)
  259. {
  260. if ($this->isElementValueNull($node)) {
  261. return;
  262. }
  263. switch ($node->localName) {
  264. case 'bool':
  265. return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue);
  266. case 'int':
  267. return (int) trim($node->nodeValue);
  268. case 'float':
  269. return (float) trim($node->nodeValue);
  270. case 'string':
  271. return trim($node->nodeValue);
  272. case 'list':
  273. $list = [];
  274. foreach ($node->childNodes as $element) {
  275. if (!$element instanceof \DOMElement) {
  276. continue;
  277. }
  278. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  279. continue;
  280. }
  281. $list[] = $this->parseDefaultNode($element, $path);
  282. }
  283. return $list;
  284. case 'map':
  285. $map = [];
  286. foreach ($node->childNodes as $element) {
  287. if (!$element instanceof \DOMElement) {
  288. continue;
  289. }
  290. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  291. continue;
  292. }
  293. $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path);
  294. }
  295. return $map;
  296. default:
  297. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path));
  298. }
  299. }
  300. private function isElementValueNull(\DOMElement $element)
  301. {
  302. $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  303. if (!$element->hasAttributeNS($namespaceUri, 'nil')) {
  304. return false;
  305. }
  306. return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
  307. }
  308. }