YamlFileLoader.php 12 KB

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