Passed
Push — master ( 2e0bae...2a4a0f )
by Alexander
02:28
created

UrlGenerator::missingParameters()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 24
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
c 1
b 0
f 0
nc 9
nop 2
dl 0
loc 24
rs 9.6111
ccs 10
cts 10
cp 1
crap 5
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 46
    }
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 2
                '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->getUri()->getPath();
132
            }
133
134 2
            throw new RuntimeException('Current route is not detected.');
135
        }
136
137
        /** @psalm-suppress PossiblyNullArgument Checked route name on null above. */
138 1
        return $this->generate(
139 1
            $this->currentRoute->getName(),
140 1
            array_merge($this->currentRoute->getArguments(), $replacedArguments)
141
        );
142
    }
143
144
    /**
145
     * @psalm-param null|object|scalar $value
146
     */
147 11
    public function setDefaultArgument(string $name, $value): void
148
    {
149 11
        if (!is_scalar($value) && !$value instanceof Stringable) {
150
            throw new InvalidArgumentException('Default should be either scalar value or an instance of \Stringable.');
151
        }
152 11
        $this->defaultArguments[$name] = (string) $value;
153 11
    }
154
155 6
    private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
156
    {
157 6
        $port = '';
158 6
        $uriPort = $uri->getPort();
159 6
        if ($uriPort !== 80 && $uriPort !== null) {
160 1
            $port = ':' . $uriPort;
161
        }
162
163 6
        return $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $uri->getScheme());
164
    }
165
166
    /**
167
     * Normalize URL by ensuring that it use specified scheme.
168
     *
169
     * If URL is relative or scheme is null, normalization is skipped.
170
     *
171
     * @param string $url The URL to process.
172
     * @param string|null $scheme The URI scheme used in URL (e.g. `http` or `https`). Use empty string to
173
     * create protocol-relative URL (e.g. `//example.com/path`).
174
     *
175
     * @return string The processed URL.
176
     */
177 11
    private function ensureScheme(string $url, ?string $scheme): string
178
    {
179 11
        if ($scheme === null || $this->isRelative($url)) {
180 1
            return $url;
181
        }
182
183 11
        if (strpos($url, '//') === 0) {
184
            // e.g. //example.com/path/to/resource
185 3
            return $scheme === '' ? $url : "$scheme:$url";
186
        }
187
188 10
        if (($pos = strpos($url, '://')) !== false) {
189 10
            if ($scheme === '') {
190 3
                $url = substr($url, $pos + 1);
191
            } else {
192 7
                $url = $scheme . substr($url, $pos);
193
            }
194
        }
195
196 10
        return $url;
197
    }
198
199
    /**
200
     * Returns a value indicating whether a URL is relative.
201
     * A relative URL does not have host info part.
202
     *
203
     * @param string $url The URL to be checked.
204
     *
205
     * @return bool Whether the URL is relative.
206
     */
207 17
    private function isRelative(string $url): bool
208
    {
209 17
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
210
    }
211
212 39
    public function getUriPrefix(): string
213
    {
214 39
        return $this->uriPrefix;
215
    }
216
217 1
    public function setEncodeRaw(bool $encodeRaw): void
218
    {
219 1
        $this->encodeRaw = $encodeRaw;
220 1
    }
221
222 3
    public function setUriPrefix(string $name): void
223
    {
224 3
        $this->uriPrefix = $name;
225 3
    }
226
227
    /**
228
     * Checks for any missing route parameters.
229
     *
230
     * @param array $parts
231
     * @param array $substitutions
232
     *
233
     * @return string[] Either an array containing missing required parameters or an empty array if none are missing.
234
     *
235
     * @psalm-param list<string|list<string>> $parts
236
     */
237 40
    private function missingArguments(array $parts, array $substitutions): array
238
    {
239 40
        $missingArguments = [];
240
241
        // Gather required arguments.
242 40
        foreach ($parts as $part) {
243 40
            if (is_string($part)) {
244 40
                continue;
245
            }
246
247 21
            $missingArguments[] = $part[0];
248
        }
249
250
        // Check if all arguments exist.
251 40
        foreach ($missingArguments as $argument) {
252 21
            if (!array_key_exists($argument, $substitutions)) {
253
                // Return the arguments, so they can be used in an
254
                // exception if needed.
255 3
                return $missingArguments;
256
            }
257
        }
258
259
        // All required arguments are availgit logable.
260 38
        return [];
261
    }
262
263
    /**
264
     * @psalm-param array<string,string> $arguments
265
     * @psalm-param list<string|list<string>> $parts
266
     */
267 38
    private function generatePath(array $arguments, array $queryParameters, array $parts): string
268
    {
269 38
        $notSubstitutedArguments = $arguments;
270 38
        $path = $this->getUriPrefix();
271
272 38
        foreach ($parts as $part) {
273 38
            if (is_string($part)) {
274
                // Append the string.
275 38
                $path .= $part;
276 38
                continue;
277
            }
278
279
            // Check substitute value with regex.
280 18
            $pattern = str_replace('~', '\~', $part[1]);
281 18
            if (preg_match('~^' . $pattern . '$~', $arguments[$part[0]]) === 0) {
282 1
                throw new RuntimeException(
283 1
                    sprintf(
284 1
                        'Argument value for [%s] did not match the regex `%s`',
285 1
                        $part[0],
286 1
                        $part[1]
287
                    )
288
                );
289
            }
290
291
            // Append the substituted value.
292 17
            $path .= $this->encodeRaw
293 17
                ? rawurlencode($arguments[$part[0]])
294 1
                : urlencode($arguments[$part[0]]);
295 17
            unset($notSubstitutedArguments[$part[0]]);
296
        }
297
298
        return $path . (
299 37
            $notSubstitutedArguments !== [] || $queryParameters !== [] ?
300 5
                '?' . http_build_query(array_merge($notSubstitutedArguments, $queryParameters))
301 37
                : ''
302
            );
303
    }
304
}
305