Passed
Push — master ( e5c5f8...191de7 )
by Alexander
08:41 queued 06:07
created

UrlGenerator::setUriPrefix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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