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