AnnotatedI18nRouteLoader   B
last analyzed

Complexity

Total Complexity 47

Size/Duplication

Total Lines 227
Duplicated Lines 18.5 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 47
lcom 1
cbo 9
dl 42
loc 227
ccs 126
cts 126
cp 1
rs 8.439
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
D load() 0 34 9
F addRoute() 42 113 26
F getGlobals() 0 50 11
A configureRoute() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AnnotatedI18nRouteLoader often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AnnotatedI18nRouteLoader, and based on these observations, apply Extract Interface, too.

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