Test Failed
Pull Request — master (#16)
by Divine Niiquaye
03:21
created

CastingTrait::castDomain()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 27
ccs 14
cts 14
cp 1
rs 8.4444
cc 8
nc 5
nop 1
crap 8

1 Method

Rating   Name   Duplication   Size   Complexity  
B CastingTrait::castNamespace() 0 15 8
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;
30
31
    /** @var string */
32
    private $path;
33
34
    /** @var array<string,bool> */
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
        $pattern = \preg_replace_callback(Route::RCA_PATTERN, function (array $matches): string {
68
            if (isset($matches[1])) {
69 144
                $this->schemes[$matches[1]] = true;
70 5
            }
71 5
72
            if (isset($matches[2])) {
73 144
                $this->domain[] = $matches[2];
74
            }
75 144
76 28
            // Match controller from route pattern.
77
            $handler = $matches[4] ?? $this->controller;
78
79 144
            if (isset($matches[5])) {
80
                $this->controller = !empty($handler) ? [$handler, $matches[5]] : $matches[5];
81
            }
82
83
            return $matches[3];
84
        }, $route, -1, $count, \PREG_UNMATCHED_AS_NULL);
0 ignored issues
show
Unused Code introduced by
The call to preg_replace_callback() has too many arguments starting with PREG_UNMATCHED_AS_NULL. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

84
        $pattern = /** @scrutinizer ignore-call */ \preg_replace_callback(Route::RCA_PATTERN, function (array $matches): string {

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. Please note the @ignore annotation hint above.

Loading history...
85
86
        return $pattern ?? $route;
87 28
    }
88
89 28
    /**
90 28
     * @internal skip throwing an exception and return exisitng $controller
91
     *
92 28
     * @param callable|object|string|string[] $controller
93 9
     *
94
     * @return mixed
95 9
     */
96
    private function castNamespace(string $namespace, $controller)
97
    {
98
        if ($controller instanceof ResourceHandler) {
99 22
            return $controller->namespace($namespace);
100 22
        }
101
102 12
        if (\is_string($controller) && (!\str_starts_with($controller, $namespace) && '\\' === $controller[0])) {
103
            return $namespace . $controller;
104
        }
105 10
106 10
        if ((\is_array($controller) && \array_keys($controller) === [0, 1]) && \is_string($controller[0])) {
107 4
            $controller[0] = $this->castNamespace($namespace, $controller[0]);
108
        }
109
110 10
        return $controller;
111
    }
112
113 10
    /**
114
     * Resolves route handler to return a response.
115
     *
116
     * @param null|callable(mixed,array) $handlerResolver
117
     * @param mixed                      $handler
118
     *
119
     * @throws InvalidControllerException if invalid response stream contents
120 15
     *
121
     * @return ResponseInterface|string
122
     */
123 15
    private function castHandler(ServerRequestInterface $request, ?callable $handlerResolver, $handler)
124 4
    {
125
        \ob_start(); // Start buffering response output
126
127 15
        $response = null !== $handlerResolver ? $handlerResolver($handler, $this->arguments) : $this->resolveHandler($handler);
128 1
129 1
        // If response was returned using an echo expression ...
130
        $echoedResponse = \ob_get_clean();
131
132 1
        if (!$response instanceof ResponseInterface) {
133
            switch (true) {
134
                case $response instanceof RequestHandlerInterface:
135 14
                    return $response->handle($request);
136
137
                case (null === $response || true === $response) && false !== $echoedResponse:
138
                    $response = $echoedResponse;
139
140
                    break;
141
142
                case \is_string($response) || \is_int($response):
143
                    $response = (string) $response;
144
145
                    break;
146
147
                case \is_array($response) || $response instanceof \JsonSerializable || $response instanceof \Traversable:
148
                    $response = \json_encode($response);
149
150
                    break;
151
152
                default:
153
                    throw new InvalidControllerException(\sprintf('Response type for route "%s" is not allowed in PSR7 response body stream.', $this->name));
154
            }
155
        }
156
157
        return $result ?? $response;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $result seems to never exist and therefore isset should always be false.
Loading history...
158
    }
159
160
    /**
161
     * Auto-configure route handler parameters.
162
     *
163
     * @param mixed $handler
164
     *
165
     * @return mixed
166
     */
167
    private function resolveHandler($handler)
168
    {
169
        if ((\is_array($handler) && [0, 1] === \array_keys($handler)) && \is_string($handler[0])) {
170
            $handler[0] = (new \ReflectionClass($handler[0]))->newInstanceArgs();
171
        }
172
173
        if (\is_callable($handler)) {
174
            $handlerRef = new \ReflectionFunction(\Closure::fromCallable($handler));
175
        } elseif (\is_object($handler) || (\is_string($handler) && \class_exists($handler))) {
176
            $handlerRef = new \ReflectionClass($handler);
177
178
            if ($handlerRef->hasMethod('__invoke')) {
179
                return $this->resolveHandler([$handlerRef->newInstance(), '__invoke']);
180
            }
181
182
            if (null !== $constructor = $handlerRef->getConstructor()) {
183
                $constructorParameters = $constructor->getParameters();
184
            }
185
        }
186
187
        if (!isset($handlerRef)) {
188
            return $handler;
189
        }
190
191
        $parameters = [];
192
        $arguments = $this->defaults['_arguments'] ?? [];
193
194
        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...
195
            $typeHint = $parameter->getType();
196
197
            if ($typeHint instanceof \ReflectionUnionType) {
198
                foreach ($typeHint->getTypes() as $unionType) {
199
                    if (isset($arguments[$unionType->getName()])) {
200
                        $parameters[$index] = $arguments[$unionType->getName()];
201
202
                        break;
203
                    }
204
                }
205
            } elseif ($typeHint instanceof \ReflectionNamedType && isset($arguments[$typeHint->getName()])) {
206
                $parameters[$index] = $arguments[$typeHint->getName()];
207
            }
208
209
            if (isset($arguments[$parameter->getName()])) {
210
                $parameters[$index] = $arguments[$parameter->getName()];
211
            } elseif (\PHP_VERSION_ID < 80000) {
212
                if ($parameter->isOptional() && $parameter->isDefaultValueAvailable()) {
213
                    $parameters[$index] = $parameter->getDefaultValue();
214
                } elseif ($parameter->allowsNull()) {
215
                    $parameters[$index] = null;
216
                }
217
            }
218
        }
219
220
        if ($handlerRef instanceof \ReflectionFunction) {
221
            return $handlerRef->invokeArgs($parameters);
222
        }
223
224
        return $handlerRef->newInstanceArgs($parameters);
225
    }
226
227
    /**
228
     * Ensures that the right-most slash is trimmed for prefixes of more than
229
     * one character, and that the prefix begins with a slash.
230
     */
231
    private function castPrefix(string $uri, string $prefix): string
232
    {
233
        // This is not accepted, but we're just avoiding throwing an exception ...
234
        if (empty($prefix)) {
235
            return $uri;
236
        }
237
238
        if (isset(Route::URL_PREFIX_SLASHES[$prefix[-1]], Route::URL_PREFIX_SLASHES[$uri[0]])) {
239
            return $prefix . \ltrim($uri, implode('', Route::URL_PREFIX_SLASHES));
240
        }
241
242
        // browser supported slashes ...
243
        $slashExist = Route::URL_PREFIX_SLASHES[$prefix[-1]] ?? Route::URL_PREFIX_SLASHES[$uri[0]] ?? null;
244
245
        if (null === $slashExist) {
246
            $prefix .= '/';
247
        }
248
249
        return $prefix . $uri;
250
    }
251
}
252