XmlFileLoader.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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\Routing\RouteCollection;
  12. use Symfony\Component\Routing\Route;
  13. use Symfony\Component\Config\Resource\FileResource;
  14. use Symfony\Component\Config\Loader\FileLoader;
  15. use Symfony\Component\Config\Util\XmlUtils;
  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. $subCollection = $this->import($resource, ('' !== $type ? $type : null), false, $file);
  128. /* @var $subCollection RouteCollection */
  129. $subCollection->addPrefix($prefix);
  130. if (null !== $host) {
  131. $subCollection->setHost($host);
  132. }
  133. if (null !== $condition) {
  134. $subCollection->setCondition($condition);
  135. }
  136. if (null !== $schemes) {
  137. $subCollection->setSchemes($schemes);
  138. }
  139. if (null !== $methods) {
  140. $subCollection->setMethods($methods);
  141. }
  142. $subCollection->addDefaults($defaults);
  143. $subCollection->addRequirements($requirements);
  144. $subCollection->addOptions($options);
  145. $collection->addCollection($subCollection);
  146. }
  147. /**
  148. * Loads an XML file.
  149. *
  150. * @param string $file An XML file path
  151. *
  152. * @return \DOMDocument
  153. *
  154. * @throws \InvalidArgumentException When loading of XML file fails because of syntax errors
  155. * or when the XML structure is not as expected by the scheme -
  156. * see validate()
  157. */
  158. protected function loadFile($file)
  159. {
  160. return XmlUtils::loadFile($file, __DIR__.static::SCHEME_PATH);
  161. }
  162. /**
  163. * Parses the config elements (default, requirement, option).
  164. *
  165. * @param \DOMElement $node Element to parse that contains the configs
  166. * @param string $path Full path of the XML file being processed
  167. *
  168. * @return array An array with the defaults as first item, requirements as second and options as third
  169. *
  170. * @throws \InvalidArgumentException When the XML is invalid
  171. */
  172. private function parseConfigs(\DOMElement $node, $path)
  173. {
  174. $defaults = array();
  175. $requirements = array();
  176. $options = array();
  177. $condition = null;
  178. foreach ($node->getElementsByTagNameNS(self::NAMESPACE_URI, '*') as $n) {
  179. if ($node !== $n->parentNode) {
  180. continue;
  181. }
  182. switch ($n->localName) {
  183. case 'default':
  184. if ($this->isElementValueNull($n)) {
  185. $defaults[$n->getAttribute('key')] = null;
  186. } else {
  187. $defaults[$n->getAttribute('key')] = $this->parseDefaultsConfig($n, $path);
  188. }
  189. break;
  190. case 'requirement':
  191. $requirements[$n->getAttribute('key')] = trim($n->textContent);
  192. break;
  193. case 'option':
  194. $options[$n->getAttribute('key')] = trim($n->textContent);
  195. break;
  196. case 'condition':
  197. $condition = trim($n->textContent);
  198. break;
  199. default:
  200. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement" or "option".', $n->localName, $path));
  201. }
  202. }
  203. return array($defaults, $requirements, $options, $condition);
  204. }
  205. /**
  206. * Parses the "default" elements.
  207. *
  208. * @param \DOMElement $element The "default" element to parse
  209. * @param string $path Full path of the XML file being processed
  210. *
  211. * @return array|bool|float|int|string|null The parsed value of the "default" element
  212. */
  213. private function parseDefaultsConfig(\DOMElement $element, $path)
  214. {
  215. if ($this->isElementValueNull($element)) {
  216. return;
  217. }
  218. // Check for existing element nodes in the default element. There can
  219. // only be a single element inside a default element. So this element
  220. // (if one was found) can safely be returned.
  221. foreach ($element->childNodes as $child) {
  222. if (!$child instanceof \DOMElement) {
  223. continue;
  224. }
  225. if (self::NAMESPACE_URI !== $child->namespaceURI) {
  226. continue;
  227. }
  228. return $this->parseDefaultNode($child, $path);
  229. }
  230. // If the default element doesn't contain a nested "bool", "int", "float",
  231. // "string", "list", or "map" element, the element contents will be treated
  232. // as the string value of the associated default option.
  233. return trim($element->textContent);
  234. }
  235. /**
  236. * Recursively parses the value of a "default" element.
  237. *
  238. * @param \DOMElement $node The node value
  239. * @param string $path Full path of the XML file being processed
  240. *
  241. * @return array|bool|float|int|string The parsed value
  242. *
  243. * @throws \InvalidArgumentException when the XML is invalid
  244. */
  245. private function parseDefaultNode(\DOMElement $node, $path)
  246. {
  247. if ($this->isElementValueNull($node)) {
  248. return;
  249. }
  250. switch ($node->localName) {
  251. case 'bool':
  252. return 'true' === trim($node->nodeValue) || '1' === trim($node->nodeValue);
  253. case 'int':
  254. return (int) trim($node->nodeValue);
  255. case 'float':
  256. return (float) trim($node->nodeValue);
  257. case 'string':
  258. return trim($node->nodeValue);
  259. case 'list':
  260. $list = array();
  261. foreach ($node->childNodes as $element) {
  262. if (!$element instanceof \DOMElement) {
  263. continue;
  264. }
  265. if (self::NAMESPACE_URI !== $element->namespaceURI) {
  266. continue;
  267. }
  268. $list[] = $this->parseDefaultNode($element, $path);
  269. }
  270. return $list;
  271. case 'map':
  272. $map = 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. $map[$element->getAttribute('key')] = $this->parseDefaultNode($element, $path);
  281. }
  282. return $map;
  283. default:
  284. throw new \InvalidArgumentException(sprintf('Unknown tag "%s" used in file "%s". Expected "bool", "int", "float", "string", "list", or "map".', $node->localName, $path));
  285. }
  286. }
  287. private function isElementValueNull(\DOMElement $element)
  288. {
  289. $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';
  290. if (!$element->hasAttributeNS($namespaceUri, 'nil')) {
  291. return false;
  292. }
  293. return 'true' === $element->getAttributeNS($namespaceUri, 'nil') || '1' === $element->getAttributeNS($namespaceUri, 'nil');
  294. }
  295. }