Completed
Push — master ( 7fdb39...63a3cc )
by Frank
04:35
created

AnnotatedI18nRouteLoader::load()   C

Complexity

Conditions 11
Paths 22

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 11

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 23
cts 23
cp 1
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 23
nc 22
nop 2
crap 11

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
use function var_dump;
18
19
class AnnotatedI18nRouteLoader extends AnnotationClassLoader
20
{
21
    protected $routeAnnotationClass = I18nRoute::class;
22
23 34
    public function __construct(Reader $reader)
24
    {
25 34
        parent::__construct($reader);
26 34
        $this->setRouteAnnotationClass(I18nRoute::class);
27 34
    }
28
29
30
    /**
31
     * Loads from annotations from a class.
32
     *
33
     * @param string      $class A class name
34
     * @param string|null $type  The resource type
35
     *
36
     * @return RouteCollection A RouteCollection instance
37
     *
38
     * @throws \InvalidArgumentException When route can't be parsed
39
     */
40 34
    public function load($class, $type = null)
41
    {
42 34
        if ( ! class_exists($class)) {
43 2
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
44
        }
45
46 32
        $class = new \ReflectionClass($class);
47 32
        if ($class->isAbstract()) {
48 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...
49
        }
50
51 30
        $globals = $this->getGlobals($class);
52
53 30
        $collection = new RouteCollection();
54 30
        $collection->addResource(new FileResource($class->getFileName()));
55
56 30
        foreach ($class->getMethods() as $method) {
57 30
            $this->defaultRouteIndex = 0;
58 30
            foreach ($this->reader->getMethodAnnotations($method) as $annot) {
59 26
                if ($annot instanceof SymfonyRoute || $annot instanceof I18nRoute) {
60 30
                    $this->addRoute($collection, $annot, $globals, $class, $method);
0 ignored issues
show
Bug introduced by
It seems like $annot can also be of type object<Symfony\Component...uting\Annotation\Route>; however, FrankDeJonge\SymfonyI18n...RouteLoader::addRoute() does only seem to accept object<FrankDeJonge\Symf...g\Annotation\I18nRoute>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
61
                }
62
            }
63
        }
64
65 22
        if (0 === $collection->count() && $class->hasMethod('__invoke')) {
66 4
            $annot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)
67 4
                ?: $this->reader->getClassAnnotation($class, SymfonyRoute::class);
68
69 4
            if ($annot != null) {
70 4
                $globals['path'] = '';
71 4
                $globals['name'] = '';
72 4
                $globals['locales'] = [];
73 4
                $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
74
            }
75
        }
76
77 22
        return $collection;
78
    }
79
80
    /**
81
     * @param RouteCollection  $collection
82
     * @param I18nRoute        $annotation
83
     * @param array            $globals
84
     * @param ReflectionClass  $class
85
     * @param ReflectionMethod $method
86
     */
87 30
    protected function addRoute(RouteCollection $collection, $annotation, $globals, ReflectionClass $class, ReflectionMethod $method)
88
    {
89 30
        $name = $annotation->getName();
90
91 30
        if (null === $name) {
92 2
            throw MissingRouteName::forAnnotation($class->name . '::' . $method->name);
93
        }
94
95 28
        $defaults = array_replace($globals['defaults'], $annotation->getDefaults());
96
97 28
        foreach ($method->getParameters() as $param) {
98 2
            if ( ! isset($defaults[$param->name]) && $param->isDefaultValueAvailable()) {
99 2
                $defaults[$param->name] = $param->getDefaultValue();
100
            }
101
        }
102
103 28
        $requirements = array_replace($globals['requirements'], $annotation->getRequirements());
104 28
        $options = array_replace($globals['options'], $annotation->getOptions());
105 28
        $schemes = array_merge($globals['schemes'], $annotation->getSchemes());
106 28
        $methods = array_merge($globals['methods'], $annotation->getMethods());
107 28
        $host = $annotation->getHost() ?: $globals['host'];
108 28
        $condition = $annotation->getCondition() ?: $globals['condition'];
109 28
        $path = $annotation->getPath();
110 28
        $locales = $annotation instanceof I18nRoute ? $annotation->getLocales() : [];
111
112 28
        $hasLocalizedPrefix = empty($globals['locales']) === false;
113 28
        $hasPrefix = $hasLocalizedPrefix || empty($globals['path']) === false;
114 28
        $isLocalized = ! empty($locales);
115 28
        $hasPathOrLocales = empty($path) === false || $isLocalized;
116
117 28
        if ($hasPrefix === false && $hasPathOrLocales === false) {
118 2
            throw MissingRoutePath::forAnnotation("{$class->name}::{$method->name}");
119
        }
120
121 26
        if ( ! $hasPathOrLocales) {
122 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...
123 2
                foreach ($globals['locales'] as $locale => $localePath) {
124 2
                    $routeName = "{$name}.{$locale}";
125 2
                    $route = $this->createRoute($localePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
126 2
                    $this->configureRoute($route, $class, $method, $annotation);
127 2
                    $route->setDefault('_locale', $locale);
128 2
                    $collection->add($routeName, $route);
129
                }
130
            } else {
131 2
                $route = $this->createRoute($globals['path'], $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
132 2
                $this->configureRoute($route, $class, $method, $annotation);
133 4
                $collection->add($name, $route);
134
            }
135 22
        } elseif ( ! $hasPrefix) {
136 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...
137 4
                foreach ($locales as $locale => $localePath) {
138 4
                    $routeName = "{$name}.{$locale}";
139 4
                    $route = $this->createRoute($localePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
140 4
                    $this->configureRoute($route, $class, $method, $annotation);
141 4
                    $route->setDefault('_locale', $locale);
142 4
                    $collection->add($routeName, $route);
143
                }
144
            } else {
145 6
                $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
146 6
                $this->configureRoute($route, $class, $method, $annotation);
147 10
                $collection->add($name, $route);
148
            }
149
        } else {
150 12
            if ($hasLocalizedPrefix) {
151 8
                if ($isLocalized) {
152 6
                    $missing = array_diff(array_keys($globals['locales']), array_keys($locales));
153
154 6
                    if ( ! empty($missing)) {
155 2
                        throw MissingRouteLocale::forClass($class, $method, join(' and ', $missing));
156
                    }
157
158 4
                    foreach ($locales as $locale => $localePath) {
159 4
                        if ( ! isset($globals['locales'][$locale])) {
160 2
                            throw MissingRouteLocale::forClass($class, $method, $locale);
161
                        }
162
163 4
                        $routePath = $globals['locales'][$locale] . $localePath;
164 4
                        $routeName = "{$name}.{$locale}";
165 4
                        $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
166 4
                        $this->configureRoute($route, $class, $method, $annotation);
167 4
                        $route->setDefault('_locale', $locale);
168 4
                        $collection->add($routeName, $route);
169
                    }
170
                } else {
171 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...
172 2
                        $routeName = "{$name}.{$locale}";
173 2
                        $routePath = $localePrefix . $path;
174 2
                        $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
175 2
                        $this->configureRoute($route, $class, $method, $annotation);
176 2
                        $route->setDefault('_locale', $locale);
177 4
                        $collection->add($routeName, $route);
178
                    }
179
                }
180
            } else {
181 4
                if ($isLocalized) {
182 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...
183 2
                        $routePath = $globals['path'] . $localePath;
184 2
                        $routeName = "{$name}.{$locale}";
185 2
                        $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
186 2
                        $this->configureRoute($route, $class, $method, $annotation);
187 2
                        $route->setDefault('_locale', $locale);
188 2
                        $collection->add($routeName, $route);
189
                    }
190
                } else {
191 2
                    $routePath = $globals['path'] . $path;
192 2
                    $route = $this->createRoute($routePath, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
193 2
                    $this->configureRoute($route, $class, $method, $annotation);
194 2
                    $collection->add($name, $route);
195
                }
196
            }
197
        }
198 22
    }
199
200
    /**
201
     * @inheritdoc
202
     */
203 30
    protected function getGlobals(ReflectionClass $class)
204
    {
205
        $globals = [
206 30
            'path'         => '',
207
            'locales'      => [],
208
            'requirements' => [],
209
            'options'      => [],
210
            'defaults'     => [],
211
            'schemes'      => [],
212
            'methods'      => [],
213
            'host'         => '',
214
            'condition'    => '',
215
        ];
216
217 30
        $annotation = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
218
219 30
        if ( ! $annotation instanceof I18nRoute && ! $annotation instanceof SymfonyRoute) {
220 10
            return $globals;
221
        }
222 20
        if ($annotation instanceof I18nRoute) {
223 20
            $globals['locales'] = $annotation->getLocales();
224
        }
225 20
        if (null !== $annotation->getPath()) {
226 8
            $globals['path'] = $annotation->getPath();
227
        }
228 20
        if (null !== $annotation->getRequirements()) {
229 20
            $globals['requirements'] = $annotation->getRequirements();
230
        }
231 20
        if (null !== $annotation->getOptions()) {
232 20
            $globals['options'] = $annotation->getOptions();
233
        }
234 20
        if (null !== $annotation->getDefaults()) {
235 20
            $globals['defaults'] = $annotation->getDefaults();
236
        }
237 20
        if (null !== $annotation->getSchemes()) {
238 20
            $globals['schemes'] = $annotation->getSchemes();
239
        }
240 20
        if (null !== $annotation->getMethods()) {
241 20
            $globals['methods'] = $annotation->getMethods();
242
        }
243 20
        if (null !== $annotation->getHost()) {
244 2
            $globals['host'] = $annotation->getHost();
245
        }
246 20
        if (null !== $annotation->getCondition()) {
247 2
            $globals['condition'] = $annotation->getCondition();
248
        }
249
250 20
        return $globals;
251
    }
252
253 24
    protected function configureRoute(Route $route, ReflectionClass $class, ReflectionMethod $method, $annot)
254
    {
255 24
        $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...
256 24
    }
257
}
258