YamlFileLoader.php 11 KB

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