vendor/symfony/routing/Loader/YamlFileLoader.php line 99

  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 $filestring $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($pathYaml::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 $resourcestring $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.     protected function parseRoute(RouteCollection $collectionstring $name, array $configstring $path)
  95.     {
  96.         if (isset($config['alias'])) {
  97.             $alias $collection->addAlias($name$config['alias']);
  98.             $deprecation $config['deprecated'] ?? null;
  99.             if (null !== $deprecation) {
  100.                 $alias->setDeprecated(
  101.                     $deprecation['package'],
  102.                     $deprecation['version'],
  103.                     $deprecation['message'] ?? ''
  104.                 );
  105.             }
  106.             return;
  107.         }
  108.         $defaults $config['defaults'] ?? [];
  109.         $requirements $config['requirements'] ?? [];
  110.         $options $config['options'] ?? [];
  111.         foreach ($requirements as $placeholder => $requirement) {
  112.             if (\is_int($placeholder)) {
  113.                 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));
  114.             }
  115.         }
  116.         if (isset($config['controller'])) {
  117.             $defaults['_controller'] = $config['controller'];
  118.         }
  119.         if (isset($config['locale'])) {
  120.             $defaults['_locale'] = $config['locale'];
  121.         }
  122.         if (isset($config['format'])) {
  123.             $defaults['_format'] = $config['format'];
  124.         }
  125.         if (isset($config['utf8'])) {
  126.             $options['utf8'] = $config['utf8'];
  127.         }
  128.         if (isset($config['stateless'])) {
  129.             $defaults['_stateless'] = $config['stateless'];
  130.         }
  131.         $routes $this->createLocalizedRoute($collection$name$config['path']);
  132.         $routes->addDefaults($defaults);
  133.         $routes->addRequirements($requirements);
  134.         $routes->addOptions($options);
  135.         $routes->setSchemes($config['schemes'] ?? []);
  136.         $routes->setMethods($config['methods'] ?? []);
  137.         $routes->setCondition($config['condition'] ?? null);
  138.         if (isset($config['host'])) {
  139.             $this->addHost($routes$config['host']);
  140.         }
  141.     }
  142.     /**
  143.      * Parses an import and adds the routes in the resource to the RouteCollection.
  144.      */
  145.     protected function parseImport(RouteCollection $collection, array $configstring $pathstring $file)
  146.     {
  147.         $type $config['type'] ?? null;
  148.         $prefix $config['prefix'] ?? '';
  149.         $defaults $config['defaults'] ?? [];
  150.         $requirements $config['requirements'] ?? [];
  151.         $options $config['options'] ?? [];
  152.         $host $config['host'] ?? null;
  153.         $condition $config['condition'] ?? null;
  154.         $schemes $config['schemes'] ?? null;
  155.         $methods $config['methods'] ?? null;
  156.         $trailingSlashOnRoot $config['trailing_slash_on_root'] ?? true;
  157.         $namePrefix $config['name_prefix'] ?? null;
  158.         $exclude $config['exclude'] ?? null;
  159.         if (isset($config['controller'])) {
  160.             $defaults['_controller'] = $config['controller'];
  161.         }
  162.         if (isset($config['locale'])) {
  163.             $defaults['_locale'] = $config['locale'];
  164.         }
  165.         if (isset($config['format'])) {
  166.             $defaults['_format'] = $config['format'];
  167.         }
  168.         if (isset($config['utf8'])) {
  169.             $options['utf8'] = $config['utf8'];
  170.         }
  171.         if (isset($config['stateless'])) {
  172.             $defaults['_stateless'] = $config['stateless'];
  173.         }
  174.         $this->setCurrentDir(\dirname($path));
  175.         /** @var RouteCollection[] $imported */
  176.         $imported $this->import($config['resource'], $typefalse$file$exclude) ?: [];
  177.         if (!\is_array($imported)) {
  178.             $imported = [$imported];
  179.         }
  180.         foreach ($imported as $subCollection) {
  181.             $this->addPrefix($subCollection$prefix$trailingSlashOnRoot);
  182.             if (null !== $host) {
  183.                 $this->addHost($subCollection$host);
  184.             }
  185.             if (null !== $condition) {
  186.                 $subCollection->setCondition($condition);
  187.             }
  188.             if (null !== $schemes) {
  189.                 $subCollection->setSchemes($schemes);
  190.             }
  191.             if (null !== $methods) {
  192.                 $subCollection->setMethods($methods);
  193.             }
  194.             if (null !== $namePrefix) {
  195.                 $subCollection->addNamePrefix($namePrefix);
  196.             }
  197.             $subCollection->addDefaults($defaults);
  198.             $subCollection->addRequirements($requirements);
  199.             $subCollection->addOptions($options);
  200.             $collection->addCollection($subCollection);
  201.         }
  202.     }
  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(mixed $configstring $namestring $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 (isset($config['alias'])) {
  213.             $this->validateAlias($config$name$path);
  214.             return;
  215.         }
  216.         if ($extraKeys array_diff(array_keys($config), self::AVAILABLE_KEYS)) {
  217.             throw new \InvalidArgumentException(sprintf('The routing file "%s" contains unsupported keys for "%s": "%s". Expected one of: "%s".'$path$nameimplode('", "'$extraKeys), implode('", "'self::AVAILABLE_KEYS)));
  218.         }
  219.         if (isset($config['resource']) && isset($config['path'])) {
  220.             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));
  221.         }
  222.         if (!isset($config['resource']) && isset($config['type'])) {
  223.             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));
  224.         }
  225.         if (!isset($config['resource']) && !isset($config['path'])) {
  226.             throw new \InvalidArgumentException(sprintf('You must define a "path" for the route "%s" in file "%s".'$name$path));
  227.         }
  228.         if (isset($config['controller']) && isset($config['defaults']['_controller'])) {
  229.             throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" key and the defaults key "_controller" for "%s".'$path$name));
  230.         }
  231.         if (isset($config['stateless']) && isset($config['defaults']['_stateless'])) {
  232.             throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "stateless" key and the defaults key "_stateless" for "%s".'$path$name));
  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 $configstring $namestring $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. }