Completed
Push — master ( 4883e1...3da805 )
by Pavel
04:15
created

BaseResolver   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 247
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 41.73%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 50
c 3
b 1
f 0
lcom 1
cbo 5
dl 0
loc 247
ccs 53
cts 127
cp 0.4173
rs 8.6206

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
C getController() 0 48 9
A instantiateController() 0 4 1
A createController() 0 14 3
C getControllerError() 0 63 16
A getArguments() 0 13 4
D doGetArguments() 0 25 9
B checkType() 0 24 6

How to fix   Complexity   

Complex Class

Complex classes like BaseResolver 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 BaseResolver, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Bankiru\Api\Rpc\Routing\ControllerResolver;
4
5
use Bankiru\Api\Rpc\Exception\InvalidMethodParametersException;
6
use Bankiru\Api\Rpc\Http\RequestInterface;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\NullLogger;
9
10
class BaseResolver implements ControllerResolverInterface
11
{
12
    /** @var  LoggerInterface */
13
    private $logger;
14
15
    /**
16
     * Resolver constructor.
17
     *
18
     * @param LoggerInterface $logger
19
     */
20 7
    public function __construct(LoggerInterface $logger = null)
21
    {
22 7
        $this->logger = $logger ?: new NullLogger();
23 7
    }
24
25
    /** {@inheritdoc} */
26 7
    public function getController(RequestInterface $request)
27
    {
28 7
        if (!$controller = $request->getAttributes()->get('_controller')) {
29 1
            $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing.');
30
31 1
            return false;
32
        }
33
34 6
        if (is_array($controller)) {
35
            return $controller;
36
        }
37
38 6
        if (is_object($controller)) {
39
            if (method_exists($controller, '__invoke')) {
40
                return $controller;
41
            }
42
43
            throw new \InvalidArgumentException(
44
                sprintf(
45
                    'Controller "%s" for method "%s" is not callable.',
46
                    get_class($controller),
47
                    $request->getMethod()
48
                )
49
            );
50
        }
51
52 6
        if (false === strpos($controller, ':')) {
53
            if (method_exists($controller, '__invoke')) {
54
                return $this->instantiateController($controller);
55
            } elseif (function_exists($controller)) {
56
                return $controller;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $controller; (integer|double|string|null|boolean) is incompatible with the return type declared by the interface Bankiru\Api\Rpc\Routing\...nterface::getController of type callable|false.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
57
            }
58
        }
59
60 6
        $callable = $this->createController($controller);
61
62 6
        if (!is_callable($callable)) {
63
            throw new \InvalidArgumentException(
64
                sprintf(
65
                    'The controller for method "%s" is not callable. %s',
66
                    $request->getMethod(),
67
                    $this->getControllerError($callable)
68
                )
69
            );
70
        }
71
72 6
        return $callable;
73
    }
74
75
    /**
76
     * Returns an instantiated controller.
77
     *
78
     * @param string $class A class name
79
     *
80
     * @return object
81
     */
82 6
    protected function instantiateController($class)
83
    {
84 6
        return new $class();
85
    }
86
87
    /**
88
     * Returns a callable for the given controller.
89
     *
90
     * @param string $controller A Controller string
91
     *
92
     * @return callable A PHP callable
93
     *
94
     * @throws \InvalidArgumentException
95
     */
96 6
    protected function createController($controller)
97
    {
98 6
        if (false === strpos($controller, '::')) {
99
            throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
100
        }
101
102 6
        list($class, $method) = explode('::', $controller, 2);
103
104 6
        if (!class_exists($class)) {
105
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
106
        }
107
108 6
        return [$this->instantiateController($class), $method];
109
    }
110
111
    private function getControllerError($callable)
112
    {
113
        if (is_string($callable)) {
114
            if (false !== strpos($callable, '::')) {
115
                $callable = explode('::', $callable);
116
            }
117
118
            if (class_exists($callable) && !method_exists($callable, '__invoke')) {
119
                return sprintf('Class "%s" does not have a method "__invoke".', $callable);
120
            }
121
122
            if (!function_exists($callable)) {
123
                return sprintf('Function "%s" does not exist.', $callable);
124
            }
125
        }
126
127
        if (!is_array($callable)) {
128
            return sprintf(
129
                'Invalid type for controller given, expected string or array, got "%s".',
130
                gettype($callable)
131
            );
132
        }
133
134
        if (2 !== count($callable)) {
135
            return sprintf('Invalid format for controller, expected array(controller, method) or controller::method.');
136
        }
137
138
        list($controller, $method) = $callable;
139
140
        if (is_string($controller) && !class_exists($controller)) {
141
            return sprintf('Class "%s" does not exist.', $controller);
142
        }
143
144
        $className = is_object($controller) ? get_class($controller) : $controller;
145
146
        if (method_exists($controller, $method)) {
147
            return sprintf('Method "%s" on class "%s" should be public and non-abstract.', $method, $className);
148
        }
149
150
        $collection = get_class_methods($controller);
151
152
        $alternatives = [];
153
154
        foreach ($collection as $item) {
155
            $lev = levenshtein($method, $item);
156
157
            if ($lev <= strlen($method) / 3 || false !== strpos($item, $method)) {
158
                $alternatives[] = $item;
159
            }
160
        }
161
162
        asort($alternatives);
163
164
        $message = sprintf('Expected method "%s" on class "%s"', $method, $className);
165
166
        if (count($alternatives) > 0) {
167
            $message .= sprintf(', did you mean "%s"?', implode('", "', $alternatives));
168
        } else {
169
            $message .= sprintf('. Available methods: "%s".', implode('", "', $collection));
170
        }
171
172
        return $message;
173
    }
174
175
    /** {@inheritdoc} */
176 6
    public function getArguments(RequestInterface $request, $controller)
177
    {
178 6
        if (is_array($controller)) {
179 6
            $r = new \ReflectionMethod($controller[0], $controller[1]);
180 6
        } elseif (is_object($controller) && !$controller instanceof \Closure) {
181
            $r = new \ReflectionObject($controller);
182
            $r = $r->getMethod('__invoke');
183
        } else {
184
            $r = new \ReflectionFunction($controller);
185
        }
186
187 6
        return $this->doGetArguments($request, $r->getParameters());
188
    }
189
190
    /**
191
     * @param RequestInterface       $request
192
     * @param \ReflectionParameter[] $parameters
193
     *
194
     * @return array
195
     * @throws \RuntimeException
196
     */
197 6
    protected function doGetArguments(RequestInterface $request, array $parameters)
198
    {
199 6
        $attributes = $request->getAttributes()->all();
200 6
        $arguments  = [];
201 6
        $missing    = [];
202 6
        foreach ($parameters as $param) {
203 6
            if (is_array($request->getParameters()) && array_key_exists($param->name, $request->getParameters())) {
204 5
                $arguments[] = $this->checkType($request->getParameters()[$param->name], $param, $request);
205 6
            } elseif (array_key_exists($param->name, $attributes)) {
206
                $arguments[] = $this->checkType($attributes[$param->name], $param->name, $request);
207 6
            } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
208 5
                $arguments[] = $request;
209 6
            } elseif ($param->isDefaultValueAvailable()) {
210 5
                $arguments[] = $param->getDefaultValue();
211 5
            } else {
212 2
                $missing[] = $param->name;
213
            }
214 6
        }
215
216 5
        if (count($missing) > 0) {
217 2
            throw InvalidMethodParametersException::missing($request->getMethod(), $missing);
218
        }
219
220 3
        return $arguments;
221
    }
222
223
    /**
224
     * Checks that argument matches parameter type
225
     *
226
     * @param mixed                $argument
227
     * @param \ReflectionParameter $param
228
     * @param RequestInterface     $request
229
     *
230
     * @return mixed
231
     */
232 5
    private function checkType($argument, \ReflectionParameter $param, RequestInterface $request)
233
    {
234 5
        $actual = is_object($argument) ? get_class($argument) : gettype($argument);
235 5
        if (null !== $param->getClass()) {
236
            $className = $param->getClass();
237
            if (!($argument instanceof $className)) {
238
                throw InvalidMethodParametersException::typeMismatch(
239
                    $request->getMethod(),
240
                    $param->name,
241
                    $className,
242
                    $actual
243
                );
244
            }
245 5
        } elseif ($param->isArray() && !is_array($argument)) {
246 1
            throw InvalidMethodParametersException::typeMismatch(
247 1
                $request->getMethod(),
248 1
                $param->name,
249 1
                'array',
250
                $actual
251 1
            );
252
        }
253
254 5
        return $argument;
255
    }
256
}
257