Test Failed
Pull Request — master (#16)
by Divine Niiquaye
02:37
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\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 string[] */
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 mixed */
50
    private $controller;
51
52
    /**
53
     * Locates appropriate route by name. Support dynamic route allocation using following pattern:
54
     * Pattern route:   `pattern/*<controller@action>`
55
     * Default route: `*<controller@action>`
56
     * Only action:   `pattern/*<action>`.
57 144
     */
58
    private function castRoute(string $route): string
59 144
    {
60 144
        if (!(\strpbrk($route, ':*{') || 0 === \strpos($route, '//'))) {
61
            return $route ?: '/';
62
        }
63 144
64
        \preg_match(Route::RCA_PATTERN, $route, $matches, \PREG_UNMATCHED_AS_NULL);
65 144
66
        if (isset($matches[1])) {
67
            $this->schemes[] = $matches[1];
68
        }
69 144
70 5
        if (isset($matches[2])) {
71 5
            $this->domain[] = $matches[2];
72
        }
73 144
74
        if (isset($matches[5])) {
75 144
            // Match controller from route pattern.
76 28
            $handler = $matches[4] ?? $this->controller;
77
            $this->controller = !empty($handler) ? [$handler, $matches[5]] : $matches[5];
78
        }
79 144
80
        return $matches[3] ?? $route;
81
    }
82
83
    /**
84
     * @internal skip throwing an exception and return existing $controller
85
     *
86
     * @param callable|object|string|string[] $controller
87 28
     *
88
     * @return mixed
89 28
     */
90 28
    private function castNamespace(string $namespace, $controller)
91
    {
92 28
        if ($controller instanceof ResourceHandler) {
93 9
            return $controller->namespace($namespace);
94
        }
95 9
96
        if (\is_string($controller) && (!\str_starts_with($controller, $namespace) && '\\' === $controller[0])) {
97
            return $namespace . $controller;
98
        }
99 22
100 22
        if ((\is_array($controller) && \array_keys($controller) === [0, 1]) && \is_string($controller[0])) {
101
            $controller[0] = $this->castNamespace($namespace, $controller[0]);
102 12
        }
103
104
        return $controller;
105 10
    }
106 10
107 4
    /**
108
     * Resolves route handler to return a response.
109
     *
110 10
     * @param null|callable(mixed,array) $handlerResolver
111
     * @param mixed                      $handler
112
     *
113 10
     * @throws InvalidControllerException if invalid response stream contents
114
     *
115
     * @return ResponseInterface|string|false
116
     */
117
    private function castHandler(ServerRequestInterface $request, ?callable $handlerResolver, $handler)
118
    {
119
        \ob_start(); // Start buffering response output
120 15
121
        $arguments = $this->defaults['_arguments'] ?? [];
122
        $response = null !== $handlerResolver ? $handlerResolver($handler, $arguments) : $this->resolveHandler($handler, $arguments);
123 15
124 4
        if ($response instanceof ResponseInterface) {
125
            $responseStream = $response;
126
        } elseif ($response instanceof RequestHandlerInterface) {
127 15
            $responseStream = $response->handle($request);
128 1
        } 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...
129 1
            $responseStream = (string) $response;
130
        } elseif (\is_array($response) || $response instanceof \JsonSerializable || $response instanceof \Traversable) {
131
            $responseStream = \json_encode($response, \PHP_VERSION_ID >= 70300 ? \JSON_THROW_ON_ERROR : 0);
132 1
        }
133
134
        return $responseStream ?? \ob_get_clean();
135 14
    }
136
137
    /**
138
     * Auto-configure route handler parameters.
139
     *
140
     * @param mixed               $handler
141
     * @param array<string,mixed> $arguments
142
     *
143
     * @return mixed
144
     */
145
    private function resolveHandler($handler, array $arguments)
146
    {
147
        if ((\is_array($handler) && [0, 1] === \array_keys($handler)) && \is_string($handler[0])) {
148
            $handler[0] = (new \ReflectionClass($handler[0]))->newInstanceArgs();
149
        }
150
151
        if (\is_callable($handler)) {
152
            $handlerRef = new \ReflectionFunction(\Closure::fromCallable($handler));
153
        } elseif (\is_object($handler) || (\is_string($handler) && \class_exists($handler))) {
154
            $handlerRef = new \ReflectionClass($handler);
155
156
            if ($handlerRef->hasMethod('__invoke')) {
157
                return $this->resolveHandler([$handlerRef->newInstance(), '__invoke'], $arguments);
158
            }
159
160
            if (null !== $constructor = $handlerRef->getConstructor()) {
161
                $constructorParameters = $constructor->getParameters();
162
            }
163
        }
164
165
        if (!isset($handlerRef)) {
166
            return $handler;
167
        }
168
169
        $parameters = [];
170
171
        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...
172
            $typeHint = $parameter->getType();
173
174
            if ($typeHint instanceof \ReflectionUnionType) {
175
                foreach ($typeHint->getTypes() as $unionType) {
176
                    if (isset($arguments[$unionType->getName()])) {
177
                        $parameters[$index] = $arguments[$unionType->getName()];
178
179
                        break;
180
                    }
181
                }
182
            } elseif ($typeHint instanceof \ReflectionNamedType && isset($arguments[$typeHint->getName()])) {
183
                $parameters[$index] = $arguments[$typeHint->getName()];
184
            }
185
186
            if (isset($arguments[$parameter->getName()])) {
187
                $parameters[$index] = $arguments[$parameter->getName()];
188
            } elseif (\PHP_VERSION_ID < 80000) {
189
                if ($parameter->isOptional() && $parameter->isDefaultValueAvailable()) {
190
                    $parameters[$index] = $parameter->getDefaultValue();
191
                } elseif ($parameter->allowsNull()) {
192
                    $parameters[$index] = null;
193
                }
194
            }
195
        }
196
197
        if ($handlerRef instanceof \ReflectionFunction) {
198
            return $handlerRef->invokeArgs($parameters);
199
        }
200
201
        return $handlerRef->newInstanceArgs($parameters);
202
    }
203
204
    /**
205
     * Ensures that the right-most slash is trimmed for prefixes of more than
206
     * one character, and that the prefix begins with a slash.
207
     */
208
    private function castPrefix(string $uri, string $prefix): string
209
    {
210
        // This is not accepted, but we're just avoiding throwing an exception ...
211
        if (empty($prefix)) {
212
            return $uri;
213
        }
214
215
        if (isset(Route::URL_PREFIX_SLASHES[$prefix[-1]], Route::URL_PREFIX_SLASHES[$uri[0]])) {
216
            return $prefix . \ltrim($uri, \implode('', Route::URL_PREFIX_SLASHES));
217
        }
218
219
        // browser supported slashes ...
220
        $slashExist = Route::URL_PREFIX_SLASHES[$prefix[-1]] ?? Route::URL_PREFIX_SLASHES[$uri[0]] ?? null;
221
222
        if (null === $slashExist) {
223
            $prefix .= '/';
224
        }
225
226
        return $prefix . $uri;
227
    }
228
}
229