Test Failed
Pull Request — master (#94)
by Dmitriy
02:20
created

generateAbsoluteFromLastMatchedRequest()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
nc 2
nop 3
dl 0
loc 9
ccs 0
cts 0
cp 0
crap 12
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router\FastRoute;
6
7
use FastRoute\RouteParser;
8
use Psr\Http\Message\UriInterface;
9
use RuntimeException;
10
use Yiisoft\Router\RouteCollectionInterface;
11
use Yiisoft\Router\RouteNotFoundException;
12
use Yiisoft\Router\CurrentRoute;
13
use Yiisoft\Router\UrlGeneratorInterface;
14
15
use function array_key_exists;
16
use function array_keys;
17
use function implode;
18
use function is_string;
19
use function preg_match;
20
21
final class UrlGenerator implements UrlGeneratorInterface
22
{
23
    private string $uriPrefix = '';
24
    private array $defaults = [];
25
    private bool $encodeRaw = true;
26
    private RouteCollectionInterface $routeCollection;
27
    private ?CurrentRoute $currentRoute;
28
    private RouteParser $routeParser;
29
30
    public function __construct(
31
        RouteCollectionInterface $routeCollection,
32 36
        CurrentRoute $currentRoute = null,
33
        RouteParser $parser = null
34
    ) {
35
        $this->currentRoute = $currentRoute;
36
        $this->routeCollection = $routeCollection;
37 36
        $this->routeParser = $parser ?? new RouteParser\Std();
38 36
    }
39 36
40 36
    /**
41
     * {@inheritDoc}
42
     *
43
     * Replacements in FastRoute are written as `{name}` or `{name:<pattern>}`;
44
     * this method uses {@see RouteParser\Std} to search for the best route
45
     * match based on the available substitutions and generates a URI.
46
     *
47
     * @throws RuntimeException If parameter value does not match its regex.
48
     */
49
    public function generate(string $name, array $parameters = []): string
50
    {
51 34
        $parameters = array_map('\strval', array_merge($this->defaults, $parameters));
52
53 34
        $route = $this->routeCollection->getRoute($name);
54
        /** @psalm-var list<list<string|list<string>>> $parsedRoutes */
55
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getData('pattern')));
56 34
        if ($parsedRoutes === []) {
57 34
            throw new RouteNotFoundException($name);
58 34
        }
59
60 3
        $missingParameters = [];
61 3
62 3
        // One route pattern can correspond to multiple routes if it has optional parts.
63 3
        foreach ($parsedRoutes as $parsedRouteParts) {
64
            // Check if all parameters can be substituted
65
            $missingParameters = $this->missingParameters($parsedRouteParts, $parameters);
66 34
67
            // If not all parameters can be substituted, try the next route.
68 33
            if (!empty($missingParameters)) {
69 33
                continue;
70 1
            }
71
72
            return $this->generatePath($parameters, $parsedRouteParts);
73 32
        }
74
75
        // No valid route was found: list minimal required parameters.
76 32
        throw new RuntimeException(
77
            sprintf(
78 32
                'Route `%s` expects at least parameter values for [%s], but received [%s]',
79
                $name,
80
                implode(',', $missingParameters),
81 32
                implode(',', array_keys($parameters))
82 3
            )
83
        );
84
    }
85 30
86
    public function generateAbsolute(
87
        string $name,
88
        array $parameters = [],
89 2
        string $scheme = null,
90 2
        string $host = null
91 2
    ): string {
92
        $parameters = array_map('\strval', $parameters);
93 2
94 2
        $url = $this->generate($name, $parameters);
95
        $route = $this->routeCollection->getRoute($name);
96
        $uri = $this->currentRoute && $this->currentRoute->getUri() !== null ? $this->currentRoute->getUri() : null;
97
        $lastRequestScheme = $uri !== null ? $uri->getScheme() : null;
98
99 17
        if ($host !== null || ($host = $route->getData('host')) !== null) {
100
            if ($scheme === null && !$this->isRelative($host)) {
101
                return rtrim($host, '/') . $url;
102
            }
103
104
            if ((empty($scheme) || $lastRequestScheme === null) && $host !== '' && $this->isRelative($host)) {
105 17
                $host = '//' . $host;
106
            }
107 17
108 17
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme ?? $lastRequestScheme);
109 17
        }
110 17
111
        return $uri === null ? $url : $this->generateAbsoluteFromLastMatchedRequest($url, $uri, $scheme);
112 17
    }
113 11
114 7
    public function generateFromCurrent(array $replacedParams, string $fallbackRouteName = null): string
115
    {
116
        if ($this->currentRoute === null || $this->currentRoute->getName() === null) {
117 5
            if ($fallbackRouteName !== null) {
118 3
                return $this->generate($fallbackRouteName, $replacedParams);
119
            }
120
121 5
            if ($this->currentRoute !== null && $this->currentRoute->getUri() !== null) {
122
                return $this->currentRoute->getUri()->getPath();
123
            }
124 6
125
            throw new RuntimeException('Current route is not detected.');
126
        }
127 5
128
        return $this->generate(
129 5
            $this->currentRoute->getName(),
130 5
            array_merge($this->currentRoute->getArguments(), $replacedParams)
131 5
        );
132 1
    }
133
134
    public function setDefault(string $name, $value): void
135 5
    {
136
        $this->defaults[$name] = $value;
137
    }
138
139
    private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
140
    {
141
        $port = '';
142
        $uriPort = $uri->getPort();
143
        if ($uriPort !== 80 && $uriPort !== null) {
144
            $port = ':' . $uriPort;
145
        }
146
147
        return $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $uri->getScheme());
148
    }
149 10
150
    /**
151 10
     * Normalize URL by ensuring that it use specified scheme.
152 1
     *
153
     * If URL is relative or scheme is null, normalization is skipped.
154
     *
155 10
     * @param string $url The URL to process.
156
     * @param string|null $scheme The URI scheme used in URL (e.g. `http` or `https`). Use empty string to
157 3
     * create protocol-relative URL (e.g. `//example.com/path`).
158
     *
159
     * @return string The processed URL.
160 9
     */
161 9
    private function ensureScheme(string $url, ?string $scheme): string
162 3
    {
163
        if ($scheme === null || $this->isRelative($url)) {
164 6
            return $url;
165
        }
166
167
        if (strpos($url, '//') === 0) {
168 9
            // e.g. //example.com/path/to/resource
169
            return $scheme === '' ? $url : "$scheme:$url";
170
        }
171
172
        if (($pos = strpos($url, '://')) !== false) {
173
            if ($scheme === '') {
174
                $url = substr($url, $pos + 1);
175
            } else {
176
                $url = $scheme . substr($url, $pos);
177
            }
178
        }
179 16
180
        return $url;
181 16
    }
182
183
    /**
184 31
     * Returns a value indicating whether a URL is relative.
185
     * A relative URL does not have host info part.
186 31
     *
187
     * @param string $url The URL to be checked.
188
     *
189 1
     * @return bool Whether the URL is relative.
190
     */
191 1
    private function isRelative(string $url): bool
192 1
    {
193
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
194 3
    }
195
196 3
    public function getUriPrefix(): string
197 3
    {
198
        return $this->uriPrefix;
199 1
    }
200
201 1
    public function setEncodeRaw(bool $encodeRaw): void
202
    {
203
        $this->encodeRaw = $encodeRaw;
204 4
    }
205
206 4
    public function setUriPrefix(string $name): void
207 4
    {
208
        $this->uriPrefix = $name;
209 3
    }
210
211 3
    /**
212 3
     * Checks for any missing route parameters.
213
     *
214
     * @param array $parts
215
     * @param array $substitutions
216
     *
217
     * @return string[] Either an array containing missing required parameters or an empty array if none are missing.
218
     *
219
     * @psalm-param list<string|list<string>> $parts
220
     */
221
    private function missingParameters(array $parts, array $substitutions): array
222
    {
223
        $missingParameters = [];
224 32
225
        // Gather required parameters.
226 32
        foreach ($parts as $part) {
227
            if (is_string($part)) {
228
                continue;
229 32
            }
230 32
231 32
            $missingParameters[] = $part[0];
232
        }
233
234 10
        // Check if all parameters exist.
235
        foreach ($missingParameters as $parameter) {
236
            if (!array_key_exists($parameter, $substitutions)) {
237
                // Return the parameters, so they can be used in an
238 32
                // exception if needed.
239 10
                return $missingParameters;
240
            }
241
        }
242 3
243
        // All required parameters are available.
244
        return [];
245
    }
246
247 30
    /**
248
     * @psalm-param array<string,string> $parameters
249
     * @psalm-param list<string|list<string>> $parts
250
     */
251
    private function generatePath(array $parameters, array $parts): string
252
    {
253
        $notSubstitutedParams = $parameters;
254 30
        $path = $this->getUriPrefix();
255
256 30
        foreach ($parts as $part) {
257 30
            if (is_string($part)) {
258
                // Append the string.
259 30
                $path .= $part;
260 30
                continue;
261
            }
262 30
263 30
            // Check substitute value with regex.
264
            $pattern = str_replace('~', '\~', $part[1]);
265
            if (preg_match('~^' . $pattern . '$~', $parameters[$part[0]]) === 0) {
266
                throw new RuntimeException(
267 7
                    sprintf(
268 7
                        'Parameter value for [%s] did not match the regex `%s`',
269 1
                        $part[0],
270 1
                        $part[1]
271 1
                    )
272 1
                );
273 1
            }
274
275
            // Append the substituted value.
276
            $path .= $this->encodeRaw
277
                ? rawurlencode($parameters[$part[0]])
278
                : urlencode($parameters[$part[0]]);
279 6
            unset($notSubstitutedParams[$part[0]]);
280 6
        }
281 1
282 6
        return $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
283
    }
284
}
285