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 Doctrine\Common\Annotations\Reader;
15use Symfony\Component\Config\Loader\LoaderInterface;
16use Symfony\Component\Config\Loader\LoaderResolverInterface;
17use Symfony\Component\Config\Resource\FileResource;
18use Symfony\Component\Routing\Annotation\Route as RouteAnnotation;
19use Symfony\Component\Routing\Route;
20use Symfony\Component\Routing\RouteCollection;
21use Symfony\Component\Routing\RouteCompiler;
22
23/**
24 * AnnotationClassLoader loads routing information from a PHP class and its methods.
25 *
26 * You need to define an implementation for the getRouteDefaults() method. Most of the
27 * time, this method should define some PHP callable to be called for the route
28 * (a controller in MVC speak).
29 *
30 * The @Route annotation can be set on the class (for global parameters),
31 * and on each method.
32 *
33 * The @Route annotation main value is the route path. The annotation also
34 * recognizes several parameters: requirements, options, defaults, schemes,
35 * methods, host, and name. The name parameter is mandatory.
36 * Here is an example of how you should be able to use it:
37 *     /**
38 *      * @Route("/Blog")
39 *      * /
40 *     class Blog
41 *     {
42 *         /**
43 *          * @Route("/", name="blog_index")
44 *          * /
45 *         public function index()
46 *         {
47 *         }
48 *         /**
49 *          * @Route("/{id}", name="blog_post", requirements = {"id" = "\d+"})
50 *          * /
51 *         public function show()
52 *         {
53 *         }
54 *     }
55 *
56 * @author Fabien Potencier <fabien@symfony.com>
57 */
58abstract class AnnotationClassLoader implements LoaderInterface
59{
60    protected $reader;
61
62    /**
63     * @var string
64     */
65    protected $routeAnnotationClass = 'Symfony\\Component\\Routing\\Annotation\\Route';
66
67    /**
68     * @var int
69     */
70    protected $defaultRouteIndex = 0;
71
72    public function __construct(Reader $reader)
73    {
74        $this->reader = $reader;
75    }
76
77    /**
78     * Sets the annotation class to read route properties from.
79     */
80    public function setRouteAnnotationClass(string $class)
81    {
82        $this->routeAnnotationClass = $class;
83    }
84
85    /**
86     * Loads from annotations from a class.
87     *
88     * @param string $class A class name
89     *
90     * @return RouteCollection A RouteCollection instance
91     *
92     * @throws \InvalidArgumentException When route can't be parsed
93     */
94    public function load($class, string $type = null)
95    {
96        if (!class_exists($class)) {
97            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
98        }
99
100        $class = new \ReflectionClass($class);
101        if ($class->isAbstract()) {
102            throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName()));
103        }
104
105        $globals = $this->getGlobals($class);
106
107        $collection = new RouteCollection();
108        $collection->addResource(new FileResource($class->getFileName()));
109
110        foreach ($class->getMethods() as $method) {
111            $this->defaultRouteIndex = 0;
112            foreach ($this->reader->getMethodAnnotations($method) as $annot) {
113                if ($annot instanceof $this->routeAnnotationClass) {
114                    $this->addRoute($collection, $annot, $globals, $class, $method);
115                }
116            }
117        }
118
119        if (0 === $collection->count() && $class->hasMethod('__invoke')) {
120            $globals = $this->resetGlobals();
121            foreach ($this->reader->getClassAnnotations($class) as $annot) {
122                if ($annot instanceof $this->routeAnnotationClass) {
123                    $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
124                }
125            }
126        }
127
128        return $collection;
129    }
130
131    /**
132     * @param RouteAnnotation $annot or an object that exposes a similar interface
133     */
134    protected function addRoute(RouteCollection $collection, $annot, array $globals, \ReflectionClass $class, \ReflectionMethod $method)
135    {
136        $name = $annot->getName();
137        if (null === $name) {
138            $name = $this->getDefaultRouteName($class, $method);
139        }
140        $name = $globals['name'].$name;
141
142        $requirements = $annot->getRequirements();
143
144        foreach ($requirements as $placeholder => $requirement) {
145            if (\is_int($placeholder)) {
146                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::%s()"?', $placeholder, $requirement, $name, $class->getName(), $method->getName()));
147            }
148        }
149
150        $defaults = array_replace($globals['defaults'], $annot->getDefaults());
151        $requirements = array_replace($globals['requirements'], $requirements);
152        $options = array_replace($globals['options'], $annot->getOptions());
153        $schemes = array_merge($globals['schemes'], $annot->getSchemes());
154        $methods = array_merge($globals['methods'], $annot->getMethods());
155
156        $host = $annot->getHost();
157        if (null === $host) {
158            $host = $globals['host'];
159        }
160
161        $condition = $annot->getCondition();
162        if (null === $condition) {
163            $condition = $globals['condition'];
164        }
165
166        $path = $annot->getLocalizedPaths() ?: $annot->getPath();
167        $prefix = $globals['localized_paths'] ?: $globals['path'];
168        $paths = [];
169
170        if (\is_array($path)) {
171            if (!\is_array($prefix)) {
172                foreach ($path as $locale => $localePath) {
173                    $paths[$locale] = $prefix.$localePath;
174                }
175            } elseif ($missing = array_diff_key($prefix, $path)) {
176                throw new \LogicException(sprintf('Route to "%s" is missing paths for locale(s) "%s".', $class->name.'::'.$method->name, implode('", "', array_keys($missing))));
177            } else {
178                foreach ($path as $locale => $localePath) {
179                    if (!isset($prefix[$locale])) {
180                        throw new \LogicException(sprintf('Route to "%s" with locale "%s" is missing a corresponding prefix in class "%s".', $method->name, $locale, $class->name));
181                    }
182
183                    $paths[$locale] = $prefix[$locale].$localePath;
184                }
185            }
186        } elseif (\is_array($prefix)) {
187            foreach ($prefix as $locale => $localePrefix) {
188                $paths[$locale] = $localePrefix.$path;
189            }
190        } else {
191            $paths[] = $prefix.$path;
192        }
193
194        foreach ($method->getParameters() as $param) {
195            if (isset($defaults[$param->name]) || !$param->isDefaultValueAvailable()) {
196                continue;
197            }
198            foreach ($paths as $locale => $path) {
199                if (preg_match(sprintf('/\{%s(?:<.*?>)?\}/', preg_quote($param->name)), $path)) {
200                    $defaults[$param->name] = $param->getDefaultValue();
201                    break;
202                }
203            }
204        }
205
206        foreach ($paths as $locale => $path) {
207            $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
208            $this->configureRoute($route, $class, $method, $annot);
209            if (0 !== $locale) {
210                $route->setDefault('_locale', $locale);
211                $route->setRequirement('_locale', preg_quote($locale, RouteCompiler::REGEX_DELIMITER));
212                $route->setDefault('_canonical_route', $name);
213                $collection->add($name.'.'.$locale, $route);
214            } else {
215                $collection->add($name, $route);
216            }
217        }
218    }
219
220    /**
221     * {@inheritdoc}
222     */
223    public function supports($resource, string $type = null)
224    {
225        return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || 'annotation' === $type);
226    }
227
228    /**
229     * {@inheritdoc}
230     */
231    public function setResolver(LoaderResolverInterface $resolver)
232    {
233    }
234
235    /**
236     * {@inheritdoc}
237     */
238    public function getResolver()
239    {
240    }
241
242    /**
243     * Gets the default route name for a class method.
244     *
245     * @return string
246     */
247    protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
248    {
249        $name = str_replace('\\', '_', $class->name).'_'.$method->name;
250        $name = \function_exists('mb_strtolower') && preg_match('//u', $name) ? mb_strtolower($name, 'UTF-8') : strtolower($name);
251        if ($this->defaultRouteIndex > 0) {
252            $name .= '_'.$this->defaultRouteIndex;
253        }
254        ++$this->defaultRouteIndex;
255
256        return $name;
257    }
258
259    protected function getGlobals(\ReflectionClass $class)
260    {
261        $globals = $this->resetGlobals();
262
263        if ($annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)) {
264            if (null !== $annot->getName()) {
265                $globals['name'] = $annot->getName();
266            }
267
268            if (null !== $annot->getPath()) {
269                $globals['path'] = $annot->getPath();
270            }
271
272            $globals['localized_paths'] = $annot->getLocalizedPaths();
273
274            if (null !== $annot->getRequirements()) {
275                $globals['requirements'] = $annot->getRequirements();
276            }
277
278            if (null !== $annot->getOptions()) {
279                $globals['options'] = $annot->getOptions();
280            }
281
282            if (null !== $annot->getDefaults()) {
283                $globals['defaults'] = $annot->getDefaults();
284            }
285
286            if (null !== $annot->getSchemes()) {
287                $globals['schemes'] = $annot->getSchemes();
288            }
289
290            if (null !== $annot->getMethods()) {
291                $globals['methods'] = $annot->getMethods();
292            }
293
294            if (null !== $annot->getHost()) {
295                $globals['host'] = $annot->getHost();
296            }
297
298            if (null !== $annot->getCondition()) {
299                $globals['condition'] = $annot->getCondition();
300            }
301
302            foreach ($globals['requirements'] as $placeholder => $requirement) {
303                if (\is_int($placeholder)) {
304                    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" in "%s"?', $placeholder, $requirement, $class->getName()));
305                }
306            }
307        }
308
309        return $globals;
310    }
311
312    private function resetGlobals(): array
313    {
314        return [
315            'path' => null,
316            'localized_paths' => [],
317            'requirements' => [],
318            'options' => [],
319            'defaults' => [],
320            'schemes' => [],
321            'methods' => [],
322            'host' => '',
323            'condition' => '',
324            'name' => '',
325        ];
326    }
327
328    protected function createRoute(string $path, array $defaults, array $requirements, array $options, ?string $host, array $schemes, array $methods, ?string $condition)
329    {
330        return new Route($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
331    }
332
333    abstract protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot);
334}
335