YamlFileLoader.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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\Routing\Loader\Configurator\Traits\HostTrait;
  14. use Symfony\Component\Routing\Loader\Configurator\Traits\LocalizedRouteTrait;
  15. use Symfony\Component\Routing\Loader\Configurator\Traits\PrefixTrait;
  16. use Symfony\Component\Routing\RouteCollection;
  17. use Symfony\Component\Yaml\Exception\ParseException;
  18. use Symfony\Component\Yaml\Parser as YamlParser;
  19. use Symfony\Component\Yaml\Yaml;
  20. /**
  21. * YamlFileLoader loads Yaml routing files.
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. * @author Tobias Schultze <http://tobion.de>
  25. */
  26. class YamlFileLoader extends FileLoader
  27. {
  28. use HostTrait;
  29. use LocalizedRouteTrait;
  30. use PrefixTrait;
  31. private const AVAILABLE_KEYS = [
  32. 'resource', 'type', 'prefix', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition', 'controller', 'name_prefix', 'trailing_slash_on_root', 'locale', 'format', 'utf8', 'exclude', 'stateless',
  33. ];
  34. private $yamlParser;
  35. /**
  36. * Loads a Yaml file.
  37. *
  38. * @param string $file A Yaml file path
  39. * @param string|null $type The resource type
  40. *
  41. * @return RouteCollection A RouteCollection instance
  42. *
  43. * @throws \InvalidArgumentException When a route can't be parsed because YAML is invalid
  44. */
  45. public function load($file, string $type = null)
  46. {
  47. $path = $this->locator->locate($file);
  48. if (!stream_is_local($path)) {
  49. throw new \InvalidArgumentException(sprintf('This is not a local file "%s".', $path));
  50. }
  51. if (!file_exists($path)) {
  52. throw new \InvalidArgumentException(sprintf('File "%s" not found.', $path));
  53. }
  54. if (null === $this->yamlParser) {
  55. $this->yamlParser = new YamlParser();
  56. }
  57. try {
  58. $parsedConfig = $this->yamlParser->parseFile($path, Yaml::PARSE_CONSTANT);
  59. } catch (ParseException $e) {
  60. throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML: ', $path).$e->getMessage(), 0, $e);
  61. }
  62. $collection = new RouteCollection();
  63. $collection->addResource(new FileResource($path));
  64. // empty file
  65. if (null === $parsedConfig) {
  66. return $collection;
  67. }
  68. // not an array
  69. if (!\is_array($parsedConfig)) {
  70. throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
  71. }
  72. foreach ($parsedConfig as $name => $config) {
  73. $this->validate($config, $name, $path);
  74. if (isset($config['resource'])) {
  75. $this->parseImport($collection, $config, $path, $file);
  76. } else {
  77. $this->parseRoute($collection, $name, $config, $path);
  78. }
  79. }
  80. return $collection;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function supports($resource, string $type = null)
  86. {
  87. return \is_string($resource) && \in_array(pathinfo($resource, \PATHINFO_EXTENSION), ['yml', 'yaml'], true) && (!$type || 'yaml' === $type);
  88. }
  89. /**
  90. * Parses a route and adds it to the RouteCollection.
  91. *
  92. * @param string $name Route name
  93. * @param array $config Route definition
  94. * @param string $path Full path of the YAML file being processed
  95. */
  96. protected function parseRoute(RouteCollection $collection, string $name, array $config, string $path)
  97. {
  98. $defaults = $config['defaults'] ?? [];
  99. $requirements = $config['requirements'] ?? [];
  100. $options = $config['options'] ?? [];
  101. foreach ($requirements as $placeholder => $requirement) {
  102. if (\is_int($placeholder)) {
  103. throw new \InvalidArgumentException(sprintf('A placeholder name must be a string (%d given). Did you forget to specify the placeholder key for the requirement "%s" of route "%s" in "%s"?', $placeholder, $requirement, $name, $path));
  104. }
  105. }
  106. if (isset($config['controller'])) {
  107. $defaults['_controller'] = $config['controller'];
  108. }
  109. if (isset($config['locale'])) {
  110. $defaults['_locale'] = $config['locale'];
  111. }
  112. if (isset($config['format'])) {
  113. $defaults['_format'] = $config['format'];
  114. }
  115. if (isset($config['utf8'])) {
  116. $options['utf8'] = $config['utf8'];
  117. }
  118. if (isset($config['stateless'])) {
  119. $defaults['_stateless'] = $config['stateless'];
  120. }
  121. $routes = $this->createLocalizedRoute($collection, $name, $config['path']);
  122. $routes->addDefaults($defaults);
  123. $routes->addRequirements($requirements);
  124. $routes->addOptions($options);
  125. $routes->setSchemes($config['schemes'] ?? []);
  126. $routes->setMethods($config['methods'] ?? []);
  127. $routes->setCondition($config['condition'] ?? null);
  128. if (isset($config['host'])) {
  129. $this->addHost($routes, $config['host']);
  130. }
  131. }
  132. /**
  133. * Parses an import and adds the routes in the resource to the RouteCollection.
  134. *
  135. * @param array $config Route definition
  136. * @param string $path Full path of the YAML file being processed
  137. * @param string $file Loaded file name
  138. */
  139. protected function parseImport(RouteCollection $collection, array $config, string $path, string $file)
  140. {
  141. $type = $config['type'] ?? null;
  142. $prefix = $config['prefix'] ?? '';
  143. $defaults = $config['defaults'] ?? [];
  144. $requirements = $config['requirements'] ?? [];
  145. $options = $config['options'] ?? [];
  146. $host = $config['host'] ?? null;
  147. $condition = $config['condition'] ?? null;
  148. $schemes = $config['schemes'] ?? null;
  149. $methods = $config['methods'] ?? null;
  150. $trailingSlashOnRoot = $config['trailing_slash_on_root'] ?? true;
  151. $namePrefix = $config['name_prefix'] ?? null;
  152. $exclude = $config['exclude'] ?? null;
  153. if (isset($config['controller'])) {
  154. $defaults['_controller'] = $config['controller'];
  155. }
  156. if (isset($config['locale'])) {
  157. $defaults['_locale'] = $config['locale'];
  158. }
  159. if (isset($config['format'])) {
  160. $defaults['_format'] = $config['format'];
  161. }
  162. if (isset($config['utf8'])) {
  163. $options['utf8'] = $config['utf8'];
  164. }
  165. if (isset($config['stateless'])) {
  166. $defaults['_stateless'] = $config['stateless'];
  167. }
  168. $this->setCurrentDir(\dirname($path));
  169. /** @var RouteCollection[] $imported */
  170. $imported = $this->import($config['resource'], $type, false, $file, $exclude) ?: [];
  171. if (!\is_array($imported)) {
  172. $imported = [$imported];
  173. }
  174. foreach ($imported as $subCollection) {
  175. $this->addPrefix($subCollection, $prefix, $trailingSlashOnRoot);
  176. if (null !== $host) {
  177. $this->addHost($subCollection, $host);
  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. * Validates the route configuration.
  199. *
  200. * @param array $config A resource config
  201. * @param string $name The config key
  202. * @param string $path The loaded file path
  203. *
  204. * @throws \InvalidArgumentException If one of the provided config keys is not supported,
  205. * something is missing or the combination is nonsense
  206. */
  207. protected function validate($config, string $name, string $path)
  208. {
  209. if (!\is_array($config)) {
  210. throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path));
  211. }
  212. if ($extraKeys = array_diff(array_keys($config), self::AVAILABLE_KEYS)) {
  213. throw new \InvalidArgumentException(sprintf('The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".', $path, $name, implode('", "', $extraKeys), implode('", "', self::AVAILABLE_KEYS)));
  214. }
  215. if (isset($config['resource']) && isset($config['path'])) {
  216. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "resource" key and the "path" key for "%s". Choose between an import and a route definition.', $path, $name));
  217. }
  218. if (!isset($config['resource']) && isset($config['type'])) {
  219. throw new \InvalidArgumentException(sprintf('The "type" key for the route definition "%s" in "%s" is unsupported. It is only available for imports in combination with the "resource" key.', $name, $path));
  220. }
  221. if (!isset($config['resource']) && !isset($config['path'])) {
  222. throw new \InvalidArgumentException(sprintf('You must define a "path" for the route "%s" in file "%s".', $name, $path));
  223. }
  224. if (isset($config['controller']) && isset($config['defaults']['_controller'])) {
  225. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" key and the defaults key "_controller" for "%s".', $path, $name));
  226. }
  227. if (isset($config['stateless']) && isset($config['defaults']['_stateless'])) {
  228. throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "stateless" key and the defaults key "_stateless" for "%s".', $path, $name));
  229. }
  230. }
  231. }