Test Failed
Pull Request — master (#16)
by Divine Niiquaye
02:47
created

CastingTrait::castHandler()   B

Complexity

Conditions 11
Paths 10

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 11

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 11
eloc 12
c 3
b 0
f 0
nc 10
nop 3
dl 0
loc 18
ccs 8
cts 8
cp 1
crap 11
rs 7.3166

How to fix   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
declare(strict_types=1);
4
5
/*
6
 * This file is part of Flight Routing.
7
 *
8
 * PHP version 7.1 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Flight\Routing\Traits;
19
20
use Flight\Routing\Exceptions\{InvalidControllerException};
21
use Flight\Routing\Handlers\ResourceHandler;
22
use Flight\Routing\Route;
23
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
24
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};
25
26
trait CastingTrait
27
{
28
    /** @var string|null */
29
    private $name = null;
30
31
    /** @var string */
32
    private $path;
33
34
    /** @var string[] */
35
    private $methods = [];
36
37
    /** @var string[] */
38
    private $domain = [];
39
40
    /** @var array<string,bool> */
41
    private $schemes = [];
42
43
    /** @var array<string,mixed> */
44
    private $defaults = [];
45
46
    /** @var array<string,string|string[]> */
47
    private $patterns = [];
48
49
    /** @var MiddlewareInterface[] */
50
    private $middlewares = [];
51
52
    /** @var mixed */
53
    private $controller;
54
55
    /**
56
     * Locates appropriate route by name. Support dynamic route allocation using following pattern:
57 144
     * Pattern route:   `pattern/*<controller@action>`
58
     * Default route: `*<controller@action>`
59 144
     * Only action:   `pattern/*<action>`.
60 144
     */
61
    private function castRoute(string $route): string
62
    {
63 144
        if (!(\strpbrk($route, ':*{') || 0 === \strpos($route, '//'))) {
64
            return $route ?: '/';
65 144
        }
66
67
        \preg_match(Route::RCA_PATTERN, $route, $matches, \PREG_UNMATCHED_AS_NULL);
68
69 144
        if (isset($matches[1])) {
70 5
            $this->schemes[$matches[1]] = true;
71 5
        }
72
73 144
        if (isset($matches[2])) {
74
            $this->domain[] = $matches[2];
75 144
        }
76 28
77
        if (isset($matches[5])) {
78
            // Match controller from route pattern.
79 144
            $handler = $matches[4] ?? $this->controller;
80
            $this->controller = !empty($handler) ? [$handler, $matches[5]] : $matches[5];
81
        }
82
83
        return $matches[3] ?? $route;
84
    }
85
86
    /**
87 28
     * @internal skip throwing an exception and return existing $controller
88
     *
89 28
     * @param callable|object|string|string[] $controller
90 28
     *
91
     * @return mixed
92 28
     */
93 9
    private function castNamespace(string $namespace, $controller)
94
    {
95 9
        if ($controller instanceof ResourceHandler) {
96
            return $controller->namespace($namespace);
97
        }
98
99 22
        if (\is_string($controller) && (!\str_starts_with($controller, $namespace) && '\\' === $controller[0])) {
100 22
            return $namespace . $controller;
101
        }
102 12
103
        if ((\is_array($controller) && \array_keys($controller) === [0, 1]) && \is_string($controller[0])) {
104
            $controller[0] = $this->castNamespace($namespace, $controller[0]);
105 10
        }
106 10
107 4
        return $controller;
108
    }
109
110 10
    /**
111
     * Resolves route handler to return a response.
112
     *
113 10
     * @param null|callable(mixed,array) $handlerResolver
114
     * @param mixed                      $handler
115
     *
116
     * @throws InvalidControllerException if invalid response stream contents
117
     *
118
     * @return ResponseInterface|string|false
119
     */
120 15
    private function castHandler(ServerRequestInterface $request, ?callable $handlerResolver, $handler)
121
    {
122
        \ob_start(); // Start buffering response output
123 15
124 4
        $arguments = $this->defaults['_arguments'] ?? [];
125
        $response = null !== $handlerResolver ? $handlerResolver($handler, $arguments) : $this->resolveHandler($handler, $arguments);
126
127 15
        if ($response instanceof ResponseInterface) {
128 1
            $responseStream = $response;
129 1
        } elseif ($response instanceof RequestHandlerInterface) {
130
            $responseStream = $response->handle($request);
131
        } elseif (\is_string($response) && (\is_int($response) || \is_float($response))) {
0 ignored issues
show
introduced by
The condition is_float($response) is always false.
Loading history...
132 1
            $responseStream = (string) $response;
133
        } elseif (\is_array($response) || $response instanceof \JsonSerializable || $response instanceof \Traversable) {
134
            $responseStream = \json_encode($response, \PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0);
135 14
        }
136
137
        return $responseStream ?? \ob_get_clean();
138
    }
139
140
    /**
141
     * Auto-configure route handler parameters.
142
     *
143
     * @param mixed               $handler
144
     * @param array<string,mixed> $arguments
145
     *
146
     * @return mixed
147
     */
148
    private function resolveHandler($handler, array $arguments)
149
    {
150
        if ((\is_array($handler) && [0, 1] === \array_keys($handler)) && \is_string($handler[0])) {
151
            $handler[0] = (new \ReflectionClass($handler[0]))->newInstanceArgs();
152
        }
153
154
        if (\is_callable($handler)) {
155
            $handlerRef = new \ReflectionFunction(\Closure::fromCallable($handler));
156
        } elseif (\is_object($handler) || (\is_string($handler) && \class_exists($handler))) {
157
            $handlerRef = new \ReflectionClass($handler);
158
159
            if ($handlerRef->hasMethod('__invoke')) {
160
                return $this->resolveHandler([$handlerRef->newInstance(), '__invoke'], $arguments);
161
            }
162
163
            if (null !== $constructor = $handlerRef->getConstructor()) {
164
                $constructorParameters = $constructor->getParameters();
165
            }
166
        }
167
168
        if (!isset($handlerRef)) {
169
            return $handler;
170
        }
171
172
        $parameters = [];
173
174
        foreach ($constructorParameters ?? $handlerRef->getParameters() as $index => $parameter) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $handlerRef does not seem to be defined for all execution paths leading up to this point.
Loading history...
175
            $typeHint = $parameter->getType();
176
177
            if ($typeHint instanceof \ReflectionUnionType) {
178
                foreach ($typeHint->getTypes() as $unionType) {
179
                    if (isset($arguments[$unionType->getName()])) {
180
                        $parameters[$index] = $arguments[$unionType->getName()];
181
182
                        break;
183
                    }
184
                }
185
            } elseif ($typeHint instanceof \ReflectionNamedType && isset($arguments[$typeHint->getName()])) {
186
                $parameters[$index] = $arguments[$typeHint->getName()];
187
            }
188
189
            if (isset($arguments[$parameter->getName()])) {
190
                $parameters[$index] = $arguments[$parameter->getName()];
191
            } elseif (\PHP_VERSION_ID < 80000) {
192
                if ($parameter->isOptional() && $parameter->isDefaultValueAvailable()) {
193
                    $parameters[$index] = $parameter->getDefaultValue();
194
                } elseif ($parameter->allowsNull()) {
195
                    $parameters[$index] = null;
196
                }
197
            }
198
        }
199
200
        if ($handlerRef instanceof \ReflectionFunction) {
201
            return $handlerRef->invokeArgs($parameters);
202
        }
203
204
        return $handlerRef->newInstanceArgs($parameters);
205
    }
206
207
    /**
208
     * Ensures that the right-most slash is trimmed for prefixes of more than
209
     * one character, and that the prefix begins with a slash.
210
     */
211
    private function castPrefix(string $uri, string $prefix): string
212
    {
213
        // This is not accepted, but we're just avoiding throwing an exception ...
214
        if (empty($prefix)) {
215
            return $uri;
216
        }
217
218
        if (isset(Route::URL_PREFIX_SLASHES[$prefix[-1]], Route::URL_PREFIX_SLASHES[$uri[0]])) {
219
            return $prefix . \ltrim($uri, \implode('', Route::URL_PREFIX_SLASHES));
220
        }
221
222
        // browser supported slashes ...
223
        $slashExist = Route::URL_PREFIX_SLASHES[$prefix[-1]] ?? Route::URL_PREFIX_SLASHES[$uri[0]] ?? null;
224
225
        if (null === $slashExist) {
226
            $prefix .= '/';
227
        }
228
229
        return $prefix . $uri;
230
    }
231
}
232