Completed
Push — 2.x ( 77cf8b...f2a999 )
by Christian
03:13 queued 11s
created

RestRouteLoader   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 145
Duplicated Lines 4.14 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 72.13%

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 7
dl 6
loc 145
ccs 44
cts 61
cp 0.7213
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 6 27 8
A getControllerReader() 0 4 1
A load() 0 10 1
A supports() 0 9 3
C getControllerLocator() 0 54 13

How to fix   Duplicated Code   

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:

1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.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
12
namespace FOS\RestBundle\Routing\Loader;
13
14
use FOS\RestBundle\Routing\Loader\Reader\RestControllerReader;
15
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
16
use Symfony\Component\Config\FileLocatorInterface;
17
use Symfony\Component\Config\Loader\Loader;
18
use Symfony\Component\DependencyInjection\ContainerInterface;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpKernel\Kernel;
21
22
/**
23
 * RestRouteLoader REST-enabled controller router loader.
24
 *
25
 * @author Konstantin Kudryashov <[email protected]>
26
 * @author Bulat Shakirzyanov <[email protected]>
27
 */
28
class RestRouteLoader extends Loader
29
{
30
    protected $container;
31
    protected $controllerParser;
32
    protected $controllerReader;
33
    protected $defaultFormat;
34
    protected $locator;
35
36
    /**
37
     * Initializes loader.
38
     *
39
     * @param ContainerInterface   $container
40
     * @param FileLocatorInterface $locator
41
     * @param RestControllerReader $controllerReader
42
     * @param string               $defaultFormat
43
     */
44 62
    public function __construct(
45
        ContainerInterface $container,
46
        FileLocatorInterface $locator,
47
        $controllerReader,
48
        $defaultFormat = 'html'
49
    ) {
50 62
        $this->container = $container;
51 62
        $this->locator = $locator;
52
53 62
        if ($controllerReader instanceof ControllerNameParser || null === $controllerReader) {
54 4
            @trigger_error(sprintf('Not passing an instance of %s as the 3rd argument of %s() is deprecated since FOSRestBundle 2.8.', RestControllerReader::class, __METHOD__), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
55
56 4
            $this->controllerParser = $controllerReader;
57
58 4 View Code Duplication
            if (!$defaultFormat instanceof RestControllerReader) {
59
                throw new \TypeError(sprintf('Argument 4 passed to %s() must be an instance of %s, %s given.', __METHOD__, RestControllerReader::class, is_object($defaultFormat) ? get_class($defaultFormat) : gettype($defaultFormat)));
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Argument 4 pass...ettype($defaultFormat)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
60
            }
61
62 4
            $this->controllerReader = $defaultFormat;
63 4
            $this->defaultFormat = func_num_args() > 4 ? func_get_arg(4) : 'html';
64 58 View Code Duplication
        } elseif (!$controllerReader instanceof RestControllerReader) {
65
            throw new \TypeError(sprintf('Argument 3 passed to %s() must be an instance of %s, %s given.', __METHOD__, RestControllerReader::class, is_object($controllerReader) ? get_class($controllerReader) : gettype($controllerReader)));
0 ignored issues
show
Unused Code introduced by
The call to TypeError::__construct() has too many arguments starting with sprintf('Argument 3 pass...ype($controllerReader)).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
66
        } else {
67 58
            $this->controllerReader = $controllerReader;
68 58
            $this->defaultFormat = $defaultFormat;
69
        }
70 62
    }
71
72
    /**
73
     * Returns controller reader.
74
     *
75
     * @return RestControllerReader
76
     */
77 28
    public function getControllerReader()
78
    {
79 28
        return $this->controllerReader;
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85 43
    public function load($controller, $type = null)
86
    {
87 43
        list($prefix, $class) = $this->getControllerLocator($controller);
88
89 43
        $collection = $this->controllerReader->read(new \ReflectionClass($class));
90 43
        $collection->prependRouteControllersWithPrefix($prefix);
91 43
        $collection->setDefaultFormat($this->defaultFormat);
92
93 43
        return $collection;
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 25
    public function supports($resource, $type = null)
100
    {
101 25
        return is_string($resource)
102 25
            && 'rest' === $type
103
            && !in_array(
104 25
                pathinfo($resource, PATHINFO_EXTENSION),
105 25
                ['xml', 'yml', 'yaml']
106
            );
107
    }
108
109
    /**
110
     * Returns controller locator by it's id.
111
     *
112
     * @param string $controller
113
     *
114
     * @throws \InvalidArgumentException
115
     *
116
     * @return array
117
     */
118 43
    private function getControllerLocator($controller)
119
    {
120 43
        $class = null;
121 43
        $prefix = null;
122
123 43
        if (0 === strpos($controller, '@')) {
124
            $file = $this->locator->locate($controller);
125
            $controllerClass = ClassUtils::findClassInFile($file);
0 ignored issues
show
Bug introduced by
It seems like $file defined by $this->locator->locate($controller) on line 124 can also be of type array; however, FOS\RestBundle\Routing\L...tils::findClassInFile() does only seem to accept string, 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...
126
127
            if (false === $controllerClass) {
128
                throw new \InvalidArgumentException(sprintf('Can\'t find class for controller "%s"', $controller));
129
            }
130
131
            $controller = $controllerClass;
132
        }
133
134 43
        if ($this->container->has($controller)) {
135
            // service_id
136 16
            $prefix = $controller.':';
137
138 16
            if (Kernel::VERSION_ID >= 40100) {
139 16
                $prefix .= ':';
140
            }
141
142 16
            $useScope = method_exists($this->container, 'enterScope') && $this->container->hasScope('request');
0 ignored issues
show
Bug introduced by
The method hasScope() does not seem to exist on object<Symfony\Component...ion\ContainerInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
143 16
            if ($useScope) {
144
                $this->container->enterScope('request');
0 ignored issues
show
Bug introduced by
The method enterScope() does not seem to exist on object<Symfony\Component...ion\ContainerInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
145
                $this->container->set('request', new Request());
146
            }
147 16
            $class = get_class($this->container->get($controller));
148 16
            if ($useScope) {
149 16
                $this->container->leaveScope('request');
0 ignored issues
show
Bug introduced by
The method leaveScope() does not seem to exist on object<Symfony\Component...ion\ContainerInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
150
            }
151 28
        } elseif (class_exists($controller)) {
152
            // full class name
153 28
            $class = $controller;
154 28
            $prefix = $class.'::';
155
        } elseif ($this->controllerParser && false !== strpos($controller, ':')) {
156
            // bundle:controller notation
157
            try {
158
                $notation = $this->controllerParser->parse($controller.':method');
159
                list($class) = explode('::', $notation);
160
                $prefix = $class.'::';
161
            } catch (\Exception $e) {
162
                throw new \InvalidArgumentException(sprintf('Can\'t locate "%s" controller.', $controller));
163
            }
164
        }
165
166 43
        if (empty($class)) {
167
            throw new \InvalidArgumentException(sprintf('Class could not be determined for Controller identified by "%s".', $controller));
168
        }
169
170 43
        return [$prefix, $class];
171
    }
172
}
173