Completed
Push — master ( e1f5ea...1fc073 )
by Frank
02:44
created

AnnotatedI18nRouteLoader::configureRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 4
crap 1
1
<?php
2
3
namespace FrankDeJonge\SymfonyI18nRouting\Routing\Loader;
4
5
use Doctrine\Common\Annotations\Reader;
6
use FrankDeJonge\SymfonyI18nRouting\Routing\Annotation\I18nRoute;
7
use ReflectionClass;
8
use ReflectionMethod;
9
use Symfony\Component\Config\Resource\FileResource;
10
use Symfony\Component\Routing\Annotation\Route as SymfonyRoute;
11
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
12
use Symfony\Component\Routing\Route;
13
use Symfony\Component\Routing\RouteCollection;
14
use function array_diff;
15
use function array_keys;
16
use function join;
17
18
class AnnotatedI18nRouteLoader extends AnnotationClassLoader
19
{
20
    /**
21
     * Loads from annotations from a class.
22
     *
23
     * @param string      $class A class name
24
     * @param string|null $type  The resource type
25
     *
26
     * @return RouteCollection A RouteCollection instance
27
     *
28
     * @throws \InvalidArgumentException When route can't be parsed
29
     */
30 36
    public function load($class, $type = null)
31
    {
32 36
        if ( ! class_exists($class)) {
33 2
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
34
        }
35
36 34
        $class = new \ReflectionClass($class);
37 34
        if ($class->isAbstract()) {
38 2
            throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName()));
0 ignored issues
show
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
39
        }
40
41 32
        $globals = $this->getGlobals($class);
42
43 32
        $collection = new RouteCollection();
44 32
        $collection->addResource(new FileResource($class->getFileName()));
45
46 32
        foreach ($class->getMethods() as $method) {
47 32
            $this->defaultRouteIndex = 0;
48 32
            foreach ($this->reader->getMethodAnnotations($method) as $annot) {
49 28
                if ($annot instanceof SymfonyRoute || $annot instanceof I18nRoute) {
50 32
                    $this->addRoute($collection, $annot, $globals, $class, $method);
0 ignored issues
show
Compatibility introduced by
$annot of type object<Symfony\Component...uting\Annotation\Route> is not a sub-type of object<FrankDeJonge\Symf...g\Annotation\I18nRoute>. It seems like you assume a child class of the class Symfony\Component\Routing\Annotation\Route to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
51
                }
52
            }
53
        }
54
55 24
        if (0 === $collection->count() && $class->hasMethod('__invoke') && $annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)) {
56 4
            $globals['path'] = '';
57 4
            $globals['name'] = '';
58 4
            $globals['locales'] = [];
59 4
            $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
60
        }
61
62 24
        return $collection;
63
    }
64
65
    /**
66
     * @param RouteCollection  $collection
67
     * @param I18nRoute        $annotation
68
     * @param array            $globals
69
     * @param ReflectionClass  $class
70
     * @param ReflectionMethod $method
71
     */
72 32
    protected function addRoute(RouteCollection $collection, $annotation, $globals, ReflectionClass $class, ReflectionMethod $method)
73
    {
74 32
        $name = $annotation->getName();
75
76 32
        if (null === $name) {
77 2
            throw MissingRouteName::forAnnotation($class->name . '::' . $method->name);
78
        }
79
80 30
        $defaults = array_replace($globals['defaults'], $annotation->getDefaults());
81
82 30
        foreach ($method->getParameters() as $param) {
83 2
            if ( ! isset($defaults[$param->name]) && $param->isDefaultValueAvailable()) {
84 2
                $defaults[$param->name] = $param->getDefaultValue();
85
            }
86
        }
87
88 30
        $requirements = array_replace($globals['requirements'], $annotation->getRequirements());
89 30
        $options = array_replace($globals['options'], $annotation->getOptions());
90 30
        $schemes = array_merge($globals['schemes'], $annotation->getSchemes());
91 30
        $methods = array_merge($globals['methods'], $annotation->getMethods());
92 30
        $host = $annotation->getHost() ?: $globals['host'];
93 30
        $condition = $annotation->getCondition() ?: $globals['condition'];
94 30
        $path = $annotation->getPath();
95 30
        $locales = $annotation instanceof I18nRoute ? $annotation->getLocales() : [];
96
97 30
        $hasLocalizedPrefix = empty($globals['locales']) === false;
98 30
        $hasPrefix = $hasLocalizedPrefix || empty($globals['path']) === false;
99 30
        $isLocalized = ! empty($locales);
100 30
        $hasPathOrLocales = empty($path) === false || $isLocalized;
101
102 30
        if ($hasPrefix === false && $hasPathOrLocales === false) {
103 2
            throw MissingRoutePath::forAnnotation("{$class->name}::{$method->name}");
104
        }
105
106 28
        if ( ! $hasPathOrLocales) {
107 4 View Code Duplication
            if ($hasLocalizedPrefix) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108 2
                foreach ($globals['locales'] as $locale => $localePath) {
109 2
                    $routeName = "{$name}.{$locale}";
110 2
                    $route = $this->createRoute($localePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
111 2
                    $this->configureRoute($route, $class, $method, $annotation);
112 2
                    $route->setDefault('_locale', $locale);
113 2
                    $collection->add($routeName, $route);
114
                }
115
            } else {
116 2
                $route = $this->createRoute($globals['path'], $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
117 2
                $this->configureRoute($route, $class, $method, $annotation);
118 4
                $collection->add($name, $route);
119
            }
120 24
        } elseif ( ! $hasPrefix) {
121 10 View Code Duplication
            if ($isLocalized) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122 4
                foreach ($locales as $locale => $localePath) {
123 4
                    $routeName = "{$name}.{$locale}";
124 4
                    $route = $this->createRoute($localePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
125 4
                    $this->configureRoute($route, $class, $method, $annotation);
126 4
                    $route->setDefault('_locale', $locale);
127 4
                    $collection->add($routeName, $route);
128
                }
129
            } else {
130 6
                $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
131 6
                $this->configureRoute($route, $class, $method, $annotation);
132 10
                $collection->add($name, $route);
133
            }
134
        } else {
135 14
            if ($hasLocalizedPrefix) {
136 8
                if ($isLocalized) {
137 6
                    $missing = array_diff(array_keys($globals['locales']), array_keys($locales));
138
139 6
                    if ( ! empty($missing)) {
140 2
                        throw MissingRouteLocale::forClass($class, $method, join(' and ', $missing));
141
                    }
142
143 4
                    foreach ($locales as $locale => $localePath) {
144 4
                        if ( ! isset($globals['locales'][$locale])) {
145 2
                            throw MissingRouteLocale::forClass($class, $method, $locale);
146
                        }
147
148 4
                        $routePath = $globals['locales'][$locale] . $localePath;
149 4
                        $routeName = "{$name}.{$locale}";
150 4
                        $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
151 4
                        $this->configureRoute($route, $class, $method, $annotation);
152 4
                        $route->setDefault('_locale', $locale);
153 4
                        $collection->add($routeName, $route);
154
                    }
155
                } else {
156 2 View Code Duplication
                    foreach ($globals['locales'] as $locale => $localePrefix) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157 2
                        $routeName = "{$name}.{$locale}";
158 2
                        $routePath = $localePrefix . $path;
159 2
                        $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
160 2
                        $this->configureRoute($route, $class, $method, $annotation);
161 2
                        $route->setDefault('_locale', $locale);
162 4
                        $collection->add($routeName, $route);
163
                    }
164
                }
165
            } else {
166 6
                if ($isLocalized) {
167 2 View Code Duplication
                    foreach ($locales as $locale => $localePath) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168 2
                        $routePath = $globals['path'] . $localePath;
169 2
                        $routeName = "{$name}.{$locale}";
170 2
                        $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
171 2
                        $this->configureRoute($route, $class, $method, $annotation);
172 2
                        $route->setDefault('_locale', $locale);
173 2
                        $collection->add($routeName, $route);
174
                    }
175
                } else {
176 4
                    $routePath = $globals['path'] . $path;
177 4
                    $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
178 4
                    $this->configureRoute($route, $class, $method, $annotation);
179 4
                    $collection->add($name, $route);
180
                }
181
            }
182
        }
183 24
    }
184
185
    /**
186
     * @inheritdoc
187
     */
188 32
    protected function getGlobals(ReflectionClass $class)
189
    {
190
        $globals = [
191 32
            'path'         => '',
192
            'locales'      => [],
193
            'requirements' => [],
194
            'options'      => [],
195
            'defaults'     => [],
196
            'schemes'      => [],
197
            'methods'      => [],
198
            'host'         => '',
199
            'condition'    => '',
200
        ];
201
202 32
        $annotation = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
203
204 32
        if ($annotation instanceof I18nRoute === false && $annotation instanceof SymfonyRoute === false) {
205 10
            return $globals;
206
        }
207 22
        if ($annotation instanceof I18nRoute) {
208 20
            $globals['locales'] = $annotation->getLocales();
209
        }
210 22
        if (null !== $annotation->getPath()) {
211 10
            $globals['path'] = $annotation->getPath();
212
        }
213 22
        if (null !== $annotation->getRequirements()) {
214 22
            $globals['requirements'] = $annotation->getRequirements();
215
        }
216 22
        if (null !== $annotation->getOptions()) {
217 22
            $globals['options'] = $annotation->getOptions();
218
        }
219 22
        if (null !== $annotation->getDefaults()) {
220 22
            $globals['defaults'] = $annotation->getDefaults();
221
        }
222 22
        if (null !== $annotation->getSchemes()) {
223 22
            $globals['schemes'] = $annotation->getSchemes();
224
        }
225 22
        if (null !== $annotation->getMethods()) {
226 22
            $globals['methods'] = $annotation->getMethods();
227
        }
228 22
        if (null !== $annotation->getHost()) {
229 2
            $globals['host'] = $annotation->getHost();
230
        }
231 22
        if (null !== $annotation->getCondition()) {
232 2
            $globals['condition'] = $annotation->getCondition();
233
        }
234
235 22
        return $globals;
236
    }
237
238 26
    protected function configureRoute(Route $route, ReflectionClass $class, ReflectionMethod $method, $annot)
239
    {
240 26
        $route->setDefault('_controller', $class->name . '::' . $method->getName());
0 ignored issues
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
241 26
    }
242
}
243