Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
12
namespace Symfony\Component\Routing\Loader;
13
 
14
use Symfony\Component\Config\Loader\FileLoader;
15
use Symfony\Component\Config\Resource\FileResource;
16
use Symfony\Component\Routing\Loader\Configurator\Traits\HostTrait;
17
use Symfony\Component\Routing\Loader\Configurator\Traits\LocalizedRouteTrait;
18
use Symfony\Component\Routing\Loader\Configurator\Traits\PrefixTrait;
19
use Symfony\Component\Routing\RouteCollection;
20
use Symfony\Component\Yaml\Exception\ParseException;
21
use Symfony\Component\Yaml\Parser as YamlParser;
22
use Symfony\Component\Yaml\Yaml;
23
 
24
/**
25
 * YamlFileLoader loads Yaml routing files.
26
 *
27
 * @author Fabien Potencier <fabien@symfony.com>
28
 * @author Tobias Schultze <http://tobion.de>
29
 */
30
class YamlFileLoader extends FileLoader
31
{
32
    use HostTrait;
33
    use LocalizedRouteTrait;
34
    use PrefixTrait;
35
 
36
    private const AVAILABLE_KEYS = [
37
        'resource', 'type', 'prefix', 'path', 'host', 'schemes', 'methods', 'defaults', 'requirements', 'options', 'condition', 'controller', 'name_prefix', 'trailing_slash_on_root', 'locale', 'format', 'utf8', 'exclude', 'stateless',
38
    ];
39
    private YamlParser $yamlParser;
40
 
41
    /**
42
     * @throws \InvalidArgumentException When a route can't be parsed because YAML is invalid
43
     */
44
    public function load(mixed $file, string $type = null): RouteCollection
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
        $this->yamlParser ??= new YamlParser();
57
 
58
        try {
59
            $parsedConfig = $this->yamlParser->parseFile($path, Yaml::PARSE_CONSTANT);
60
        } catch (ParseException $e) {
61
            throw new \InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML: ', $path).$e->getMessage(), 0, $e);
62
        }
63
 
64
        $collection = new RouteCollection();
65
        $collection->addResource(new FileResource($path));
66
 
67
        // empty file
68
        if (null === $parsedConfig) {
69
            return $collection;
70
        }
71
 
72
        // not an array
73
        if (!\is_array($parsedConfig)) {
74
            throw new \InvalidArgumentException(sprintf('The file "%s" must contain a YAML array.', $path));
75
        }
76
 
77
        foreach ($parsedConfig as $name => $config) {
78
            if (str_starts_with($name, 'when@')) {
79
                if (!$this->env || 'when@'.$this->env !== $name) {
80
                    continue;
81
                }
82
 
83
                foreach ($config as $name => $config) {
84
                    $this->validate($config, $name.'" when "@'.$this->env, $path);
85
 
86
                    if (isset($config['resource'])) {
87
                        $this->parseImport($collection, $config, $path, $file);
88
                    } else {
89
                        $this->parseRoute($collection, $name, $config, $path);
90
                    }
91
                }
92
 
93
                continue;
94
            }
95
 
96
            $this->validate($config, $name, $path);
97
 
98
            if (isset($config['resource'])) {
99
                $this->parseImport($collection, $config, $path, $file);
100
            } else {
101
                $this->parseRoute($collection, $name, $config, $path);
102
            }
103
        }
104
 
105
        return $collection;
106
    }
107
 
108
    public function supports(mixed $resource, string $type = null): bool
109
    {
110
        return \is_string($resource) && \in_array(pathinfo($resource, \PATHINFO_EXTENSION), ['yml', 'yaml'], true) && (!$type || 'yaml' === $type);
111
    }
112
 
113
    /**
114
     * Parses a route and adds it to the RouteCollection.
115
     */
116
    protected function parseRoute(RouteCollection $collection, string $name, array $config, string $path)
117
    {
118
        if (isset($config['alias'])) {
119
            $alias = $collection->addAlias($name, $config['alias']);
120
            $deprecation = $config['deprecated'] ?? null;
121
            if (null !== $deprecation) {
122
                $alias->setDeprecated(
123
                    $deprecation['package'],
124
                    $deprecation['version'],
125
                    $deprecation['message'] ?? ''
126
                );
127
            }
128
 
129
            return;
130
        }
131
 
132
        $defaults = $config['defaults'] ?? [];
133
        $requirements = $config['requirements'] ?? [];
134
        $options = $config['options'] ?? [];
135
 
136
        foreach ($requirements as $placeholder => $requirement) {
137
            if (\is_int($placeholder)) {
138
                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));
139
            }
140
        }
141
 
142
        if (isset($config['controller'])) {
143
            $defaults['_controller'] = $config['controller'];
144
        }
145
        if (isset($config['locale'])) {
146
            $defaults['_locale'] = $config['locale'];
147
        }
148
        if (isset($config['format'])) {
149
            $defaults['_format'] = $config['format'];
150
        }
151
        if (isset($config['utf8'])) {
152
            $options['utf8'] = $config['utf8'];
153
        }
154
        if (isset($config['stateless'])) {
155
            $defaults['_stateless'] = $config['stateless'];
156
        }
157
 
158
        $routes = $this->createLocalizedRoute($collection, $name, $config['path']);
159
        $routes->addDefaults($defaults);
160
        $routes->addRequirements($requirements);
161
        $routes->addOptions($options);
162
        $routes->setSchemes($config['schemes'] ?? []);
163
        $routes->setMethods($config['methods'] ?? []);
164
        $routes->setCondition($config['condition'] ?? null);
165
 
166
        if (isset($config['host'])) {
167
            $this->addHost($routes, $config['host']);
168
        }
169
    }
170
 
171
    /**
172
     * Parses an import and adds the routes in the resource to the RouteCollection.
173
     */
174
    protected function parseImport(RouteCollection $collection, array $config, string $path, string $file)
175
    {
176
        $type = $config['type'] ?? null;
177
        $prefix = $config['prefix'] ?? '';
178
        $defaults = $config['defaults'] ?? [];
179
        $requirements = $config['requirements'] ?? [];
180
        $options = $config['options'] ?? [];
181
        $host = $config['host'] ?? null;
182
        $condition = $config['condition'] ?? null;
183
        $schemes = $config['schemes'] ?? null;
184
        $methods = $config['methods'] ?? null;
185
        $trailingSlashOnRoot = $config['trailing_slash_on_root'] ?? true;
186
        $namePrefix = $config['name_prefix'] ?? null;
187
        $exclude = $config['exclude'] ?? null;
188
 
189
        if (isset($config['controller'])) {
190
            $defaults['_controller'] = $config['controller'];
191
        }
192
        if (isset($config['locale'])) {
193
            $defaults['_locale'] = $config['locale'];
194
        }
195
        if (isset($config['format'])) {
196
            $defaults['_format'] = $config['format'];
197
        }
198
        if (isset($config['utf8'])) {
199
            $options['utf8'] = $config['utf8'];
200
        }
201
        if (isset($config['stateless'])) {
202
            $defaults['_stateless'] = $config['stateless'];
203
        }
204
 
205
        $this->setCurrentDir(\dirname($path));
206
 
207
        /** @var RouteCollection[] $imported */
208
        $imported = $this->import($config['resource'], $type, false, $file, $exclude) ?: [];
209
 
210
        if (!\is_array($imported)) {
211
            $imported = [$imported];
212
        }
213
 
214
        foreach ($imported as $subCollection) {
215
            $this->addPrefix($subCollection, $prefix, $trailingSlashOnRoot);
216
 
217
            if (null !== $host) {
218
                $this->addHost($subCollection, $host);
219
            }
220
            if (null !== $condition) {
221
                $subCollection->setCondition($condition);
222
            }
223
            if (null !== $schemes) {
224
                $subCollection->setSchemes($schemes);
225
            }
226
            if (null !== $methods) {
227
                $subCollection->setMethods($methods);
228
            }
229
            if (null !== $namePrefix) {
230
                $subCollection->addNamePrefix($namePrefix);
231
            }
232
            $subCollection->addDefaults($defaults);
233
            $subCollection->addRequirements($requirements);
234
            $subCollection->addOptions($options);
235
 
236
            $collection->addCollection($subCollection);
237
        }
238
    }
239
 
240
    /**
241
     * @throws \InvalidArgumentException If one of the provided config keys is not supported,
242
     *                                   something is missing or the combination is nonsense
243
     */
244
    protected function validate(mixed $config, string $name, string $path)
245
    {
246
        if (!\is_array($config)) {
247
            throw new \InvalidArgumentException(sprintf('The definition of "%s" in "%s" must be a YAML array.', $name, $path));
248
        }
249
        if (isset($config['alias'])) {
250
            $this->validateAlias($config, $name, $path);
251
 
252
            return;
253
        }
254
        if ($extraKeys = array_diff(array_keys($config), self::AVAILABLE_KEYS)) {
255
            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)));
256
        }
257
        if (isset($config['resource']) && isset($config['path'])) {
258
            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));
259
        }
260
        if (!isset($config['resource']) && isset($config['type'])) {
261
            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));
262
        }
263
        if (!isset($config['resource']) && !isset($config['path'])) {
264
            throw new \InvalidArgumentException(sprintf('You must define a "path" for the route "%s" in file "%s".', $name, $path));
265
        }
266
        if (isset($config['controller']) && isset($config['defaults']['_controller'])) {
267
            throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "controller" key and the defaults key "_controller" for "%s".', $path, $name));
268
        }
269
        if (isset($config['stateless']) && isset($config['defaults']['_stateless'])) {
270
            throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify both the "stateless" key and the defaults key "_stateless" for "%s".', $path, $name));
271
        }
272
    }
273
 
274
    /**
275
     * @throws \InvalidArgumentException If one of the provided config keys is not supported,
276
     *                                   something is missing or the combination is nonsense
277
     */
278
    private function validateAlias(array $config, string $name, string $path): void
279
    {
280
        foreach ($config as $key => $value) {
281
            if (!\in_array($key, ['alias', 'deprecated'], true)) {
282
                throw new \InvalidArgumentException(sprintf('The routing file "%s" must not specify other keys than "alias" and "deprecated" for "%s".', $path, $name));
283
            }
284
 
285
            if ('deprecated' === $key) {
286
                if (!isset($value['package'])) {
287
                    throw new \InvalidArgumentException(sprintf('The routing file "%s" must specify the attribute "package" of the "deprecated" option for "%s".', $path, $name));
288
                }
289
 
290
                if (!isset($value['version'])) {
291
                    throw new \InvalidArgumentException(sprintf('The routing file "%s" must specify the attribute "version" of the "deprecated" option for "%s".', $path, $name));
292
                }
293
            }
294
        }
295
    }
296
}