Passed
Push — master ( ca57da...32979e )
by Rustam
03:12 queued 50s
created

UrlGenerator::setDefaultArgument()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 4.25

Importance

Changes 0
Metric Value
cc 4
eloc 3
nc 2
nop 2
dl 0
loc 6
ccs 3
cts 4
cp 0.75
crap 4.25
rs 10
c 0
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
     * @var array<string,string>
29
     */
30
    private array $defaultArguments = [];
31
    private bool $encodeRaw = true;
32
    private RouteParser $routeParser;
33
34 51
    public function __construct(
35
        private RouteCollectionInterface $routeCollection,
36
        private ?CurrentRoute $currentRoute = null,
37
        RouteParser $parser = null
38
    ) {
39 51
        $this->routeParser = $parser ?? new RouteParser\Std();
40
    }
41
42
    /**
43
     * {@inheritDoc}
44
     *
45
     * Replacements in FastRoute are written as `{name}` or `{name:<pattern>}`;
46
     * this method uses {@see RouteParser\Std} to search for the best route
47
     * match based on the available substitutions and generates a URI.
48
     *
49
     * @throws RuntimeException If parameter value does not match its regex.
50
     */
51 47
    public function generate(string $name, array $arguments = [], array $queryParameters = []): string
52
    {
53 47
        $arguments = array_map('\strval', array_merge($this->defaultArguments, $arguments));
54 47
        $route = $this->routeCollection->getRoute($name);
55
        /** @var list<list<list<string>|string>> $parsedRoutes */
56 46
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getData('pattern')));
57 46
        if ($parsedRoutes === []) {
0 ignored issues
show
introduced by
The condition $parsedRoutes === array() is always false.
Loading history...
58 1
            throw new RouteNotFoundException($name);
59
        }
60
61 45
        $missingArguments = [];
62
63
        // One route pattern can correspond to multiple routes if it has optional parts.
64 45
        foreach ($parsedRoutes as $parsedRouteParts) {
65
            // Check if all arguments can be substituted
66 45
            $missingArguments = $this->missingArguments($parsedRouteParts, $arguments);
67
68
            // If not all arguments can be substituted, try the next route.
69 45
            if (!empty($missingArguments)) {
70 3
                continue;
71
            }
72
73 43
            return $this->generatePath($arguments, $queryParameters, $parsedRouteParts);
74
        }
75
76
        // No valid route was found: list minimal required parameters.
77 2
        throw new RuntimeException(
78 2
            sprintf(
79
                'Route `%s` expects at least argument values for [%s], but received [%s]',
80
                $name,
81 2
                implode(',', $missingArguments),
82 2
                implode(',', array_keys($arguments))
83
            )
84
        );
85
    }
86
87 18
    public function generateAbsolute(
88
        string $name,
89
        array $arguments = [],
90
        array $queryParameters = [],
91
        string $scheme = null,
92
        string $host = null
93
    ): string {
94 18
        $url = $this->generate($name, $arguments, $queryParameters);
95 18
        $route = $this->routeCollection->getRoute($name);
96 18
        $uri = $this->currentRoute && $this->currentRoute->getUri() !== null ? $this->currentRoute->getUri() : null;
97 18
        $lastRequestScheme = $uri?->getScheme();
98
99 18
        if ($host !== null || ($host = $route->getData('host')) !== null) {
100 11
            if ($scheme === null && !$this->isRelative($host)) {
101 7
                return rtrim($host, '/') . $url;
102
            }
103
104 5
            if ((empty($scheme) || $lastRequestScheme === null) && $host !== '' && $this->isRelative($host)) {
105 3
                $host = '//' . $host;
106
            }
107
108 5
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme ?? $lastRequestScheme);
109
        }
110
111 7
        return $uri === null ? $url : $this->generateAbsoluteFromLastMatchedRequest($url, $uri, $scheme);
112
    }
113
114
    /**
115
     * {@inheritdoc}
116
     */
117 12
    public function generateFromCurrent(array $replacedArguments, string $fallbackRouteName = null): string
118
    {
119 12
        if ($this->currentRoute === null || $this->currentRoute->getName() === null) {
120 6
            if ($fallbackRouteName !== null) {
121 3
                return $this->generate($fallbackRouteName, $replacedArguments);
122
            }
123
124 3
            if ($this->currentRoute !== null && $this->currentRoute->getUri() !== null) {
125 1
                return $this->currentRoute->getUri()->getPath();
126
            }
127
128 2
            throw new RuntimeException('Current route is not detected.');
129
        }
130
131 6
        $queryParameters = [];
132 6
        if ($this->currentRoute->getUri() !== null) {
133 6
            parse_str($this->currentRoute->getUri()->getQuery(), $queryParameters);
134
        }
135
136
        /** @psalm-suppress PossiblyNullArgument Checked route name on null above. */
137 6
        return $this->generate(
138 6
            $this->currentRoute->getName(),
139 6
            array_merge($this->currentRoute->getArguments(), $replacedArguments),
140
            $queryParameters,
141
        );
142
    }
143
144
    /**
145
     * @psalm-param null|object|scalar $value
146
     */
147 14
    public function setDefaultArgument(string $name, $value): void
148
    {
149 14
        if (!is_scalar($value) && !$value instanceof Stringable && $value !== null) {
150
            throw new InvalidArgumentException('Default should be either scalar value or an instance of \Stringable.');
151
        }
152 14
        $this->defaultArguments[$name] = (string) $value;
153
    }
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 (str_starts_with($url, '//')) {
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) && !str_contains($url, '://');
210
    }
211
212 44
    public function getUriPrefix(): string
213
    {
214 44
        return $this->uriPrefix;
215
    }
216
217 1
    public function setEncodeRaw(bool $encodeRaw): void
218
    {
219 1
        $this->encodeRaw = $encodeRaw;
220
    }
221
222 3
    public function setUriPrefix(string $name): void
223
    {
224 3
        $this->uriPrefix = $name;
225
    }
226
227
    /**
228
     * Checks for any missing route parameters.
229
     *
230
     * @param list<list<string>|string> $parts
0 ignored issues
show
Bug introduced by
The type Yiisoft\Router\FastRoute\list was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
231
     *
232
     * @return string[] Either an array containing missing required parameters or an empty array if none are missing.
233
     */
234 45
    private function missingArguments(array $parts, array $substitutions): array
235
    {
236 45
        $missingArguments = [];
237
238
        // Gather required arguments.
239 45
        foreach ($parts as $part) {
240 45
            if (is_string($part)) {
241 45
                continue;
242
            }
243
244 25
            $missingArguments[] = $part[0];
245
        }
246
247
        // Check if all arguments exist.
248 45
        foreach ($missingArguments as $argument) {
249 25
            if (!array_key_exists($argument, $substitutions)) {
250
                // Return the arguments, so they can be used in an
251
                // exception if needed.
252 3
                return $missingArguments;
253
            }
254
        }
255
256
        // All required arguments are availgit logable.
257 43
        return [];
258
    }
259
260
    /**
261
     * @param array<string,string> $arguments
262
     * @param list<list<string>|string> $parts
263
     */
264 43
    private function generatePath(array $arguments, array $queryParameters, array $parts): string
265
    {
266 43
        $notSubstitutedArguments = $arguments;
267 43
        $path = $this->getUriPrefix();
268
269 43
        foreach ($parts as $part) {
270 43
            if (is_string($part)) {
271
                // Append the string.
272 43
                $path .= $part;
273 43
                continue;
274
            }
275
276 22
            if ($arguments[$part[0]] !== '') {
277
                // Check substitute value with regex.
278 22
                $pattern = str_replace('~', '\~', $part[1]);
279 22
                if (preg_match('~^' . $pattern . '$~', $arguments[$part[0]]) === 0) {
280 1
                    throw new RuntimeException(
281 1
                        sprintf(
282
                            'Argument value for [%s] did not match the regex `%s`',
283 1
                            $part[0],
284 1
                            $part[1]
285
                        )
286
                    );
287
                }
288
289
                // Append the substituted value.
290 21
                $path .= $this->encodeRaw
291 21
                    ? rawurlencode($arguments[$part[0]])
292 1
                    : urlencode($arguments[$part[0]]);
293
            }
294 21
            unset($notSubstitutedArguments[$part[0]]);
295
        }
296
297 42
        $path = str_replace('//', '/', $path);
298
299
        return $path . (
300 42
            $notSubstitutedArguments !== [] || $queryParameters !== [] ?
301 6
                '?' . http_build_query(array_merge($notSubstitutedArguments, $queryParameters))
302 42
                : ''
303
        );
304
    }
305
}
306