YamlFileLoader.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 $yamlParser;
  35. /**
  36. * @throws \InvalidArgumentException When a route can't be parsed because YAML is invalid
  37. */
  38. public function load(mixed $file, ?string $type = null): RouteCollection
  39. {
  40. $path = $this->locator->locate($file);
  41. if (!stream_is_local($path)) {
  42. throw new \InvalidArgumentException(\sprintf('This is not a local file "%s".', $path));
  43. }
  44. if (!file_exists($path)) {
  45. throw new \InvalidArgumentException(\sprintf('File "%s" not found.', $path));
  46. }
  47. $this->yamlParser ??= new YamlParser();
  48. try {
  49. $parsedConfig = $this->yamlParser->parseFile($path, Yaml::PARSE_CONSTANT);
  50. } catch (ParseException $e) {
  51. throw new \InvalidArgumentException(\sprintf('The file "%s" does not contain valid YAML: ', $path).$e->getMessage(), 0, $e);
  52. }
  53. $collection = new RouteCollection();
  54. $collection->addResource(new FileResource($path));
  55. // empty file
  56. if (null === $parsedConfig) {
  57. return $collection;
  58. }
  59. // not an array
  60. if (!\is_array($parsedConfig)) {
  61. throw new \InvalidArgumentException(\sprintf('The file "%s" must contain a YAML array.', $path));
  62. }
  63. $this->loadContent($collection, $parsedConfig, $path, $file);
  64. return $collection;
  65. }
  66. public function supports(mixed $resource, ?string $type = null): bool
  67. {
  68. return \is_string($resource) && \in_array(pathinfo($resource, \PATHINFO_EXTENSION), ['yml', 'yaml'], true) && (!$type || 'yaml' === $type);
  69. }
  70. /**
  71. * Parses a route and adds it to the RouteCollection.
  72. */
  73. protected function parseRoute(RouteCollection $collection, string $name, array $config, string $path): void
  74. {
  75. if (isset($config['alias'])) {
  76. $alias = $collection->addAlias($name, $config['alias']);
  77. $deprecation = $config['deprecated'] ?? null;
  78. if (null !== $deprecation) {
  79. $alias->setDeprecated(
  80. $deprecation['package'],
  81. $deprecation['version'],
  82. $deprecation['message'] ?? ''
  83. );
  84. }
  85. return;
  86. }
  87. $defaults = $config['defaults'] ?? [];
  88. $requirements = $config['requirements'] ?? [];
  89. $options = $config['options'] ?? [];
  90. foreach ($requirements as $placeholder => $requirement) {
  91. if (\is_int($placeholder)) {
  92. 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));
  93. }
  94. }
  95. if (isset($config['controller'])) {
  96. $defaults['_controller'] = $config['controller'];
  97. }
  98. if (isset($config['locale'])) {
  99. $defaults['_locale'] = $config['locale'];
  100. }
  101. if (isset($config['format'])) {
  102. $defaults['_format'] = $config['format'];
  103. }
  104. if (isset($config['utf8'])) {
  105. $options['utf8'] = $config['utf8'];
  106. }
  107. if (isset($config['stateless'])) {
  108. $defaults['_stateless'] = $config['stateless'];
  109. }
  110. $routes = $this->createLocalizedRoute(new RouteCollection(), $name, $config['path']);
  111. $routes->addDefaults($defaults);
  112. $routes->addRequirements($requirements);
  113. $routes->addOptions($options);
  114. $routes->setSchemes($config['schemes'] ?? []);
  115. $routes->setMethods($config['methods'] ?? []);
  116. $routes->setCondition($config['condition'] ?? null);
  117. if (isset($config['host'])) {
  118. $this->addHost($routes, $config['host']);
  119. }
  120. $collection->addCollection($routes);
  121. }
  122. /**
  123. * Parses an import and adds the routes in the resource to the RouteCollection.
  124. */
  125. protected function parseImport(RouteCollection $collection, array $config, string $path, string $file): void
  126. {
  127. $type = $config['type'] ?? null;
  128. $prefix = $config['prefix'] ?? '';
  129. $defaults = $config['defaults'] ?? [];
  130. $requirements = $config['requirements'] ?? [];
  131. $options = $config['options'] ?? [];
  132. $host = $config['host'] ?? null;
  133. $condition = $config['condition'] ?? null;
  134. $schemes = $config['schemes'] ?? null;
  135. $methods = $config['methods'] ?? null;
  136. $trailingSlashOnRoot = $config['trailing_slash_on_root'] ?? true;
  137. $namePrefix = $config['name_prefix'] ?? null;
  138. $exclude = $config['exclude'] ?? null;
  139. if (isset($config['controller'])) {
  140. $defaults['_controller'] = $config['controller'];
  141. }
  142. if (isset($config['locale'])) {
  143. $defaults['_locale'] = $config['locale'];
  144. }
  145. if (isset($config['format'])) {
  146. $defaults['_format'] = $config['format'];
  147. }
  148. if (isset($config['utf8'])) {
  149. $options['utf8'] = $config['utf8'];
  150. }
  151. if (isset($config['stateless'])) {
  152. $defaults['_stateless'] = $config['stateless'];
  153. }
  154. $this->setCurrentDir(\dirname($path));
  155. /** @var RouteCollection[] $imported */
  156. $imported = $this->import($config['resource'], $type, false, $file, $exclude) ?: [];
  157. if (!\is_array($imported)) {
  158. $imported = [$imported];
  159. }
  160. foreach ($imported as $subCollection) {
  161. $this->addPrefix($subCollection, $prefix, $trailingSlashOnRoot);
  162. if (null !== $host) {
  163. $this->addHost($subCollection, $host);
  164. }
  165. if (null !== $condition) {
  166. $subCollection->setCondition($condition);
  167. }
  168. if (null !== $schemes) {
  169. $subCollection->setSchemes($schemes);
  170. }
  171. if (null !== $methods) {
  172. $subCollection->setMethods($methods);
  173. }
  174. if (null !== $namePrefix) {
  175. $subCollection->addNamePrefix($namePrefix);
  176. }
  177. $subCollection->addDefaults($defaults);
  178. $subCollection->addRequirements($requirements);
  179. $subCollection->addOptions($options);
  180. $collection->addCollection($subCollection);
  181. }
  182. }
  183. /**
  184. * @throws \InvalidArgumentException If one of the provided config keys is not supported,
  185. * something is missing or the combination is nonsense
  186. */
  187. protected function validate(mixed $config, string $name, string $path): void
  188. {
  189. if (!\is_array($config)) {
  190. throw new \InvalidArgumentException(\sprintf('The definition of "%s" in "%s" must be an array.', $name, $path));
  191. }
  192. if (isset($config['alias'])) {
  193. $this->validateAlias($config, $name, $path);
  194. return;
  195. }
  196. if ($extraKeys = array_diff(array_keys($config), self::AVAILABLE_KEYS)) {
  197. 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)));
  198. }
  199. if (isset($config['resource']) && isset($config['path'])) {
  200. 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));
  201. }
  202. if (!isset($config['resource']) && isset($config['type'])) {
  203. 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));
  204. }
  205. if (!isset($config['resource']) && !isset($config['path'])) {
  206. throw new \InvalidArgumentException(\sprintf('You must define a "path" for the route "%s" in file "%s".', $name, $path));
  207. }
  208. if (isset($config['controller']) && isset($config['defaults']['_controller'])) {
  209. throw new \InvalidArgumentException(\sprintf('The routing file "%s" must not specify both the "controller" key and the defaults key "_controller" for "%s".', $path, $name));
  210. }
  211. if (isset($config['stateless']) && isset($config['defaults']['_stateless'])) {
  212. throw new \InvalidArgumentException(\sprintf('The routing file "%s" must not specify both the "stateless" key and the defaults key "_stateless" for "%s".', $path, $name));
  213. }
  214. }
  215. private function loadContent(RouteCollection $collection, array $config, string $path, string $file): void
  216. {
  217. foreach ($config as $name => $config) {
  218. if (!str_starts_with($when = $name, 'when@')) {
  219. $config = [$name => $config];
  220. } elseif (!$this->env || 'when@'.$this->env !== $name) {
  221. continue;
  222. } else {
  223. $when .= '" when "@'.$this->env;
  224. }
  225. foreach ($config as $name => $config) {
  226. $this->validate($config, $when, $path);
  227. if (isset($config['resource'])) {
  228. $this->parseImport($collection, $config, $path, $file);
  229. } else {
  230. $this->parseRoute($collection, $name, $config, $path);
  231. }
  232. }
  233. }
  234. }
  235. /**
  236. * @throws \InvalidArgumentException If one of the provided config keys is not supported,
  237. * something is missing or the combination is nonsense
  238. */
  239. private function validateAlias(array $config, string $name, string $path): void
  240. {
  241. foreach ($config as $key => $value) {
  242. if (!\in_array($key, ['alias', 'deprecated'], true)) {
  243. throw new \InvalidArgumentException(\sprintf('The routing file "%s" must not specify other keys than "alias" and "deprecated" for "%s".', $path, $name));
  244. }
  245. if ('deprecated' === $key) {
  246. if (!isset($value['package'])) {
  247. throw new \InvalidArgumentException(\sprintf('The routing file "%s" must specify the attribute "package" of the "deprecated" option for "%s".', $path, $name));
  248. }
  249. if (!isset($value['version'])) {
  250. throw new \InvalidArgumentException(\sprintf('The routing file "%s" must specify the attribute "version" of the "deprecated" option for "%s".', $path, $name));
  251. }
  252. }
  253. }
  254. }
  255. }