AnnotatedI18nRouteLoader::addRoute()   F
last analyzed

Complexity

Conditions 26
Paths 3072

Size

Total Lines 113
Code Lines 84

Duplication

Lines 42
Ratio 37.17 %

Code Coverage

Tests 79
CRAP Score 26

Importance

Changes 0
Metric Value
dl 42
loc 113
ccs 79
cts 79
cp 1
rs 2
c 0
b 0
f 0
cc 26
eloc 84
nc 3072
nop 5
crap 26

How to fix   Long Method    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 FrankDeJonge\SymfonyI18nRouting\Routing\Annotation\I18nRoute;
6
use ReflectionClass;
7
use ReflectionMethod;
8
use Symfony\Component\Config\Resource\FileResource;
9
use Symfony\Component\Routing\Annotation\Route as SymfonyRoute;
10
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
11
use Symfony\Component\Routing\Route;
12
use Symfony\Component\Routing\RouteCollection;
13
use function array_diff;
14
use function array_keys;
15
use function join;
16
17
class AnnotatedI18nRouteLoader extends AnnotationClassLoader
18
{
19
    /**
20
     * Loads from annotations from a class.
21
     *
22
     * @param string      $class A class name
23
     * @param string|null $type  The resource type
24
     *
25
     * @return RouteCollection A RouteCollection instance
26
     *
27
     * @throws \InvalidArgumentException When route can't be parsed
28
     */
29 36
    public function load($class, $type = null)
30
    {
31 36
        if ( ! class_exists($class)) {
32 2
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
33
        }
34
35 34
        $class = new \ReflectionClass($class);
36 34
        if ($class->isAbstract()) {
37 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...
38
        }
39
40 32
        $globals = $this->getGlobals($class);
41
42 32
        $collection = new RouteCollection();
43 32
        $collection->addResource(new FileResource($class->getFileName()));
44
45 32
        foreach ($class->getMethods() as $method) {
46 32
            $this->defaultRouteIndex = 0;
47 32
            foreach ($this->reader->getMethodAnnotations($method) as $annotation) {
48 28
                if ($annotation instanceof SymfonyRoute) {
49 32
                    $this->addRoute($collection, $annotation, $globals, $class, $method);
50
                }
51
            }
52
        }
53
54 26
        if (0 === $collection->count() && $class->hasMethod('__invoke') && $annotation = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass)) {
55 4
            $globals['path'] = '';
56 4
            $globals['name'] = '';
57 4
            $globals['locales'] = [];
58 4
            $this->addRoute($collection, $annotation, $globals, $class, $class->getMethod('__invoke'));
59
        }
60
61 26
        return $collection;
62
    }
63
64
    /**
65
     * @param RouteCollection  $collection
66
     * @param SymfonyRoute     $annotation
67
     * @param array            $globals
68
     * @param ReflectionClass  $class
69
     * @param ReflectionMethod $method
70
     */
71 32
    protected function addRoute(RouteCollection $collection, $annotation, $globals, ReflectionClass $class, ReflectionMethod $method)
72
    {
73 32
        $name = $annotation->getName();
74
75 32
        if (null === $name) {
76 2
            $name = $this->getDefaultRouteName($class, $method);
77
        }
78
79 32
        $name = $globals['name_prefix'].$name;
80 32
        $defaults = array_replace($globals['defaults'], $annotation->getDefaults());
81
82 32
        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 32
        $requirements = array_replace($globals['requirements'], $annotation->getRequirements());
89 32
        $options = array_replace($globals['options'], $annotation->getOptions());
90 32
        $schemes = array_merge($globals['schemes'], $annotation->getSchemes());
91 32
        $methods = array_merge($globals['methods'], $annotation->getMethods());
92 32
        $host = $annotation->getHost() ?: $globals['host'];
93 32
        $condition = $annotation->getCondition() ?: $globals['condition'];
94 32
        $path = $annotation->getPath();
95 32
        $locales = $annotation instanceof I18nRoute ? $annotation->getLocales() : [];
96
97 32
        $hasLocalizedPrefix = empty($globals['locales']) === false;
98 32
        $hasPrefix = $hasLocalizedPrefix || empty($globals['path']) === false;
99 32
        $isLocalized = ! empty($locales);
100 32
        $hasPathOrLocales = empty($path) === false || $isLocalized;
101
102 32
        if ($hasPrefix === false && $hasPathOrLocales === false) {
103 2
            throw MissingRoutePath::forAnnotation("{$class->name}::{$method->name}");
104
        }
105
106 30
        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 26
        } elseif ( ! $hasPrefix) {
121 12 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 8
                $route = $this->createRoute($path, $defaults, $requirements, $options, $host, $schemes, $methods, $condition);
131 8
                $this->configureRoute($route, $class, $method, $annotation);
132 12
                $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 26
    }
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
            'name_prefix'  => '',
201
        ];
202
203 32
        $annotation = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
204
205 32
        if ($annotation instanceof SymfonyRoute === false) {
206 10
            return $globals;
207
        }
208 22
        if ($annotation instanceof I18nRoute) {
209 20
            $globals['locales'] = $annotation->getLocales();
210
        }
211 22
        if (null !== $annotation->getPath()) {
212 10
            $globals['path'] = $annotation->getPath();
213
        }
214 22
        if (null !== $annotation->getRequirements()) {
215 22
            $globals['requirements'] = $annotation->getRequirements();
216
        }
217 22
        if (null !== $annotation->getOptions()) {
218 22
            $globals['options'] = $annotation->getOptions();
219
        }
220 22
        if (null !== $annotation->getDefaults()) {
221 22
            $globals['defaults'] = $annotation->getDefaults();
222
        }
223 22
        if (null !== $annotation->getSchemes()) {
224 22
            $globals['schemes'] = $annotation->getSchemes();
225
        }
226 22
        if (null !== $annotation->getMethods()) {
227 22
            $globals['methods'] = $annotation->getMethods();
228
        }
229 22
        if (null !== $annotation->getHost()) {
230 2
            $globals['host'] = $annotation->getHost();
231
        }
232 22
        if (null !== $annotation->getCondition()) {
233 2
            $globals['condition'] = $annotation->getCondition();
234
        }
235
236 22
        return $globals;
237
    }
238
239 28
    protected function configureRoute(Route $route, ReflectionClass $class, ReflectionMethod $method, $annot)
240
    {
241 28
        $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...
242 28
    }
243
}
244