XmlFileLoader.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 = array($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 = array();
  180. $requirements = array();
  181. $options = array();
  182. $condition = null;
  183. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  184. if ($node !== $n->parentNode) {
  185. continue;
  186. }
  187. switch ($n->localName) {
  188. case 'default':
  189. if ($this->isElementValueNull($n)) {
  190. $defaults[$n->getAttribute('key')] = null;
  191. } else {
  192. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  193. }
  194. break;
  195. case 'requirement':
  196. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  197. break;
  198. case 'option':
  199. $options[$n->getAttribute('key')] = trim($n->textContent);
  200. break;
  201. case 'condition':
  202. $condition = trim($n->textContent);
  203. break;
  204. default:
  205. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path));
  206. }
  207. }
  208. if ($controller = $node->getAttribute('controller')) {
  209. if (isset($defaults['_controller'])) {
  210. $name = $node->hasAttribute('id') ? sprintf('"%s"', $node->getAttribute('id')) : sprintf('the "%s" tag', $node->tagName);
  211. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" attribute and the defaults key "_controller" for %s.', $path, $name));
  212. }
  213. $defaults['_controller'] = $controller;
  214. }
  215. return array($defaults, $requirements, $options, $condition);
  216. }
  217. /**
  218. * Parses the "default" elements.
  219. *
  220. * @param \DOMElement $element The "default" element to parse
  221. * @param string $path Full path of the XML file being processed
  222. *
  223. * @return array|bool|float|int|string|null The parsed value of the "default" element
  224. */
  225. private function parseDefaultsConfig(\DOMElement $element, $path)
  226. {
  227. if ($this->isElementValueNull($element)) {
  228. return;
  229. }
  230. // Check for existing element nodes in the default element. There can
  231. // only be a single element inside a default element. So this element
  232. // (if one was found) can safely be returned.
  233. foreach ($element->childNodes as $child) {
  234. if (!$child instanceof \DOMElement) {
  235. continue;
  236. }
  237. if (self::NAMESPACE_URI !== $child->namespaceURI) {
  238. continue;
  239. }
  240. return $this->parseDefaultNode($child, $path);
  241. }
  242. // If the default element doesn't contain a nested "bool", "int", "float",
  243. // "string", "list", or "map" element, the element contents will be treated
  244. // as the string value of the associated default option.
  245. return trim($element->textContent);
  246. }
  247. /**
  248. * Recursively parses the value of a "default" element.
  249. *
  250. * @param \DOMElement $node The node value
  251. * @param string $path Full path of the XML file being processed
  252. *
  253. * @return array|bool|float|int|string The parsed value
  254. *
  255. * @throws \InvalidArgumentException when the XML is invalid
  256. */
  257. private function parseDefaultNode(\DOMElement $node, $path)
  258. {
  259. if ($this->isElementValueNull($node)) {
  260. return;
  261. }
  262. switch ($node->localName) {
  263. case 'bool':
  264. return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue);
  265. case 'int':
  266. return (int) trim($node->nodeValue);
  267. case 'float':
  268. return (float) trim($node->nodeValue);
  269. case 'string':
  270. return trim($node->nodeValue);
  271. case 'list':
  272. $list = array();
  273. foreach ($node->childNodes as $element) {
  274. if (!$element instanceof \DOMElement) {
  275. continue;
  276. }
  277. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  278. continue;
  279. }
  280. $list[] = $this->parseDefaultNode($element, $path);
  281. }
  282. return $list;
  283. case 'map':
  284. $map = array();
  285. foreach ($node->childNodes as $element) {
  286. if (!$element instanceof \DOMElement) {
  287. continue;
  288. }
  289. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  290. continue;
  291. }
  292. $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path);
  293. }
  294. return $map;
  295. default:
  296. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path));
  297. }
  298. }
  299. private function isElementValueNull(\DOMElement $element)
  300. {
  301. $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  302. if (!$element->hasAttributeNS($namespaceUri, 'nil')) {
  303. return false;
  304. }
  305. return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
  306. }
  307. }