Completed
Push — 2.x ( a0426f...f16329 )
by Christian
01:41 queued 01:38
created

RestRouteLoader   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 130
Duplicated Lines 4.62 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 73.77%

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 7
dl 6
loc 130
ccs 45
cts 61
cp 0.7377
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
C getControllerLocator() 0 54 13
A supports() 0 9 3

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 1
@trigger_error(sprintf('The %s\RestRouteLoader class is deprecated since FOSRestBundle 2.8.', __NAMESPACE__), 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...
15
16
use FOS\RestBundle\Routing\Loader\Reader\RestControllerReader;
17
use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
18
use Symfony\Component\Config\FileLocatorInterface;
19
use Symfony\Component\Config\Loader\Loader;
20
use Symfony\Component\DependencyInjection\ContainerInterface;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpKernel\Kernel;
23
24
/**
25
 * RestRouteLoader REST-enabled controller router loader.
26
 *
27
 * @author Konstantin Kudryashov <[email protected]>
28
 * @author Bulat Shakirzyanov <[email protected]>
29
 *
30
 * @deprecated since 2.8
31
 */
32
class RestRouteLoader extends Loader
33
{
34
    protected $container;
35
    protected $controllerParser;
36
    protected $controllerReader;
37
    protected $defaultFormat;
38
    protected $locator;
39
40
    /**
41
     * @param RestControllerReader $controllerReader
42
     * @param string               $defaultFormat
43
     */
44 50
    public function __construct(
45
        ContainerInterface $container,
46
        FileLocatorInterface $locator,
47
        $controllerReader,
48
        $defaultFormat = 'html'
49
    ) {
50 50
        $this->container = $container;
51 50
        $this->locator = $locator;
52
53 50
        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 46 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 46
            $this->controllerReader = $controllerReader;
68 46
            $this->defaultFormat = $defaultFormat;
69
        }
70 50
    }
71
72
    /**
73
     * @return RestControllerReader
74
     */
75 28
    public function getControllerReader()
76
    {
77 28
        return $this->controllerReader;
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 29
    public function load($controller, $type = null)
84
    {
85 29
        list($prefix, $class) = $this->getControllerLocator($controller);
86
87 29
        $collection = $this->controllerReader->read(new \ReflectionClass($class));
88 29
        $collection->prependRouteControllersWithPrefix($prefix);
89 29
        $collection->setDefaultFormat($this->defaultFormat);
90
91 29
        return $collection;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 14
    public function supports($resource, $type = null)
98
    {
99 14
        return is_string($resource)
100 14
            && 'rest' === $type
101 11
            && !in_array(
102 11
                pathinfo($resource, PATHINFO_EXTENSION),
103 14
                ['xml', 'yml', 'yaml']
104
            );
105
    }
106
107 29
    private function getControllerLocator(string $controller): array
108
    {
109 29
        $class = null;
110 29
        $prefix = null;
111
112 29
        if (0 === strpos($controller, '@')) {
113
            $file = $this->locator->locate($controller);
114
            $controllerClass = ClassUtils::findClassInFile($file);
0 ignored issues
show
Bug introduced by
It seems like $file defined by $this->locator->locate($controller) on line 113 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...
115
116
            if (null === $controllerClass) {
117
                throw new \InvalidArgumentException(sprintf('Can\'t find class for controller "%s"', $controller));
118
            }
119
120
            $controller = $controllerClass;
121
        }
122
123 29
        if ($this->container->has($controller)) {
124
            // service_id
125 2
            $prefix = $controller.':';
126
127 2
            if (Kernel::VERSION_ID >= 40100) {
128 2
                $prefix .= ':';
129
            }
130
131 2
            $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...
132 2
            if ($useScope) {
133
                $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...
134
                $this->container->set('request', new Request());
135
            }
136 2
            $class = get_class($this->container->get($controller));
137 2
            if ($useScope) {
138 2
                $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...
139
            }
140 28
        } elseif (class_exists($controller)) {
141
            // full class name
142 28
            $class = $controller;
143 28
            $prefix = $class.'::';
144
        } elseif ($this->controllerParser && false !== strpos($controller, ':')) {
145
            // bundle:controller notation
146
            try {
147
                $notation = $this->controllerParser->parse($controller.':method');
148
                list($class) = explode('::', $notation);
149
                $prefix = $class.'::';
150
            } catch (\Exception $e) {
151
                throw new \InvalidArgumentException(sprintf('Can\'t locate "%s" controller.', $controller));
152
            }
153
        }
154
155 29
        if (empty($class)) {
156
            throw new \InvalidArgumentException(sprintf('Class could not be determined for Controller identified by "%s".', $controller));
157
        }
158
159 29
        return [$prefix, $class];
160
    }
161
}
162