Test Failed
Pull Request — master (#94)
by Dmitriy
01:42
created

UrlGenerator::generateCurrent()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 12
ccs 5
cts 5
cp 1
crap 4
rs 10
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
115
    {
116
        if ($this->currentRoute === null || $this->currentRoute->getName() === null) {
117 5
            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

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