You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

280 lines
11 KiB

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