Passed
Pull Request — master (#107)
by Rustam
03:23 queued 01:14
created

UrlGenerator::ensureScheme()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7

Importance

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