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

UrlGenerator::generate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 17
c 3
b 0
f 0
nc 4
nop 2
dl 0
loc 33
ccs 17
cts 17
cp 1
crap 4
rs 9.7
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 generateCurrent(array $replacedParams, string $fallbackRouteName = null): string
115
    {
116
        if ($this->currentRoute === null || $this->currentRoute->getName() === null) {
117 5
            if ($fallbackRouteName !== null) {
118 3
                $fallbackRoute = $this->routeCollection->getRoute($fallbackRouteName);
0 ignored issues
show
Unused Code introduced by
The assignment to $fallbackRoute is dead and can be removed.
Loading history...
119
                return $this->generate($fallbackRouteName, $replacedParams);
120
            }
121 5
122
            if ($this->currentRoute->getUri() !== null) {
0 ignored issues
show
Bug introduced by
The method getUri() does not exist on null. ( Ignorable by Annotation )

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

122
            if ($this->currentRoute->/** @scrutinizer ignore-call */ getUri() !== null) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
123
                return $this->currentRoute->getUri()->getPath();
124 6
            }
125
126
            throw new RuntimeException('Current route is not detected.');
127 5
        }
128
129 5
        return $this->generate(
130 5
            $this->currentRoute->getName(),
131 5
            array_merge($this->currentRoute->getArguments(), $replacedParams)
132 1
        );
133
    }
134
135 5
    public function setDefault(string $name, $value): void
136
    {
137
        $this->defaults[$name] = $value;
138
    }
139
140
    private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
141
    {
142
        $port = '';
143
        $uriPort = $uri->getPort();
144
        if ($uriPort !== 80 && $uriPort !== null) {
145
            $port = ':' . $uriPort;
146
        }
147
148
        return $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $uri->getScheme());
149 10
    }
150
151 10
    /**
152 1
     * Normalize URL by ensuring that it use specified scheme.
153
     *
154
     * If URL is relative or scheme is null, normalization is skipped.
155 10
     *
156
     * @param string $url The URL to process.
157 3
     * @param string|null $scheme The URI scheme used in URL (e.g. `http` or `https`). Use empty string to
158
     * create protocol-relative URL (e.g. `//example.com/path`).
159
     *
160 9
     * @return string The processed URL.
161 9
     */
162 3
    private function ensureScheme(string $url, ?string $scheme): string
163
    {
164 6
        if ($scheme === null || $this->isRelative($url)) {
165
            return $url;
166
        }
167
168 9
        if (strpos($url, '//') === 0) {
169
            // e.g. //example.com/path/to/resource
170
            return $scheme === '' ? $url : "$scheme:$url";
171
        }
172
173
        if (($pos = strpos($url, '://')) !== false) {
174
            if ($scheme === '') {
175
                $url = substr($url, $pos + 1);
176
            } else {
177
                $url = $scheme . substr($url, $pos);
178
            }
179 16
        }
180
181 16
        return $url;
182
    }
183
184 31
    /**
185
     * Returns a value indicating whether a URL is relative.
186 31
     * A relative URL does not have host info part.
187
     *
188
     * @param string $url The URL to be checked.
189 1
     *
190
     * @return bool Whether the URL is relative.
191 1
     */
192 1
    private function isRelative(string $url): bool
193
    {
194 3
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
195
    }
196 3
197 3
    public function getUriPrefix(): string
198
    {
199 1
        return $this->uriPrefix;
200
    }
201 1
202
    public function setEncodeRaw(bool $encodeRaw): void
203
    {
204 4
        $this->encodeRaw = $encodeRaw;
205
    }
206 4
207 4
    public function setUriPrefix(string $name): void
208
    {
209 3
        $this->uriPrefix = $name;
210
    }
211 3
212 3
    /**
213
     * Checks for any missing route parameters.
214
     *
215
     * @param array $parts
216
     * @param array $substitutions
217
     *
218
     * @return string[] Either an array containing missing required parameters or an empty array if none are missing.
219
     *
220
     * @psalm-param list<string|list<string>> $parts
221
     */
222
    private function missingParameters(array $parts, array $substitutions): array
223
    {
224 32
        $missingParameters = [];
225
226 32
        // Gather required parameters.
227
        foreach ($parts as $part) {
228
            if (is_string($part)) {
229 32
                continue;
230 32
            }
231 32
232
            $missingParameters[] = $part[0];
233
        }
234 10
235
        // Check if all parameters exist.
236
        foreach ($missingParameters as $parameter) {
237
            if (!array_key_exists($parameter, $substitutions)) {
238 32
                // Return the parameters, so they can be used in an
239 10
                // exception if needed.
240
                return $missingParameters;
241
            }
242 3
        }
243
244
        // All required parameters are available.
245
        return [];
246
    }
247 30
248
    /**
249
     * @psalm-param array<string,string> $parameters
250
     * @psalm-param list<string|list<string>> $parts
251
     */
252
    private function generatePath(array $parameters, array $parts): string
253
    {
254 30
        $notSubstitutedParams = $parameters;
255
        $path = $this->getUriPrefix();
256 30
257 30
        foreach ($parts as $part) {
258
            if (is_string($part)) {
259 30
                // Append the string.
260 30
                $path .= $part;
261
                continue;
262 30
            }
263 30
264
            // Check substitute value with regex.
265
            $pattern = str_replace('~', '\~', $part[1]);
266
            if (preg_match('~^' . $pattern . '$~', $parameters[$part[0]]) === 0) {
267 7
                throw new RuntimeException(
268 7
                    sprintf(
269 1
                        'Parameter value for [%s] did not match the regex `%s`',
270 1
                        $part[0],
271 1
                        $part[1]
272 1
                    )
273 1
                );
274
            }
275
276
            // Append the substituted value.
277
            $path .= $this->encodeRaw
278
                ? rawurlencode($parameters[$part[0]])
279 6
                : urlencode($parameters[$part[0]]);
280 6
            unset($notSubstitutedParams[$part[0]]);
281 1
        }
282 6
283
        return $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
284
    }
285
}
286