Passed
Pull Request — master (#92)
by Rustam
02:07
created

UrlGenerator::addLocaleToPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
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 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 string $locale = '';
25
    private bool $encodeRaw = true;
26
    private array $locales = [];
27
    private ?string $localeParameterName = null;
28
    private RouteCollectionInterface $routeCollection;
29
    private ?CurrentRoute $currentRoute;
30
    private RouteParser $routeParser;
31
32 39
    public function __construct(
33
        RouteCollectionInterface $routeCollection,
34
        CurrentRoute $currentRoute = null,
35
        RouteParser $parser = null
36
    ) {
37 39
        $this->currentRoute = $currentRoute;
38 39
        $this->routeCollection = $routeCollection;
39 39
        $this->routeParser = $parser ?? new RouteParser\Std();
40 39
    }
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 an uri.
48
     *
49
     * @throws RuntimeException if parameter value does not match its regex.
50
     */
51 36
    public function generate(string $name, array $parameters = []): string
52
    {
53
        if (
54 36
            $this->localeParameterName !== null
55 36
            && isset($parameters[$this->localeParameterName])
56 36
            && $this->locales !== []
57
        ) {
58 3
            $locale = $parameters[$this->localeParameterName];
59 3
            if (isset($this->locales[$locale])) {
60 3
                $this->locale = $locale;
61 3
                unset($parameters[$this->localeParameterName]);
62
            }
63
        }
64 36
        $route = $this->routeCollection->getRoute($name);
65 35
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getData('pattern')));
66 35
        if ($parsedRoutes === []) {
67 1
            throw new RouteNotFoundException($name);
68
        }
69
70 34
        $missingParameters = [];
71
72
        // One route pattern can correspond to multiple routes if it has optional parts
73 34
        foreach ($parsedRoutes as $parsedRouteParts) {
74
            // Check if all parameters can be substituted
75 34
            $missingParameters = $this->missingParameters($parsedRouteParts, $parameters);
76
77
            // If not all parameters can be substituted, try the next route
78 34
            if (!empty($missingParameters)) {
79 3
                continue;
80
            }
81
82 32
            return $this->generatePath($parameters, $parsedRouteParts);
83
        }
84
85
        // No valid route was found: list minimal required parameters
86 2
        throw new RuntimeException(
87 2
            sprintf(
88 2
                'Route `%s` expects at least parameter values for [%s], but received [%s]',
89
                $name,
90 2
                implode(',', $missingParameters),
91 2
                implode(',', array_keys($parameters))
92
            )
93
        );
94
    }
95
96 17
    public function generateAbsolute(
97
        string $name,
98
        array $parameters = [],
99
        string $scheme = null,
100
        string $host = null
101
    ): string {
102 17
        $url = $this->generate($name, $parameters);
103 17
        $route = $this->routeCollection->getRoute($name);
104
        /** @var UriInterface $uri */
105 17
        $uri = $this->currentRoute && $this->currentRoute->getUri() !== null ? $this->currentRoute->getUri() : null;
106 17
        $lastRequestScheme = $uri !== null ? $uri->getScheme() : null;
107
108 17
        if ($host !== null || ($host = $route->getData('host')) !== null) {
109 11
            if ($scheme === null && !$this->isRelative($host)) {
110 7
                return rtrim($host, '/') . $url;
111
            }
112
113 5
            if ((empty($scheme) || $lastRequestScheme === null) && $host !== '' && $this->isRelative($host)) {
114 3
                $host = '//' . $host;
115
            }
116
117 5
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme ?? $lastRequestScheme);
118
        }
119
120 6
        return $uri === null ? $url : $this->generateAbsoluteFromLastMatchedRequest($url, $uri, $scheme);
121
    }
122
123 5
    private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
124
    {
125 5
        $port = $uri->getPort() === 80 || $uri->getPort() === null ? '' : ':' . $uri->getPort();
126 5
        return $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $uri->getScheme());
127
    }
128
129
    /**
130
     * Normalize URL by ensuring that it use specified scheme.
131
     *
132
     * If URL is relative or scheme is null, normalization is skipped.
133
     *
134
     * @param string $url the URL to process
135
     * @param string|null $scheme the URI scheme used in URL (e.g. `http` or `https`). Use empty string to
136
     * create protocol-relative URL (e.g. `//example.com/path`)
137
     *
138
     * @return string the processed URL
139
     */
140 10
    private function ensureScheme(string $url, ?string $scheme): string
141
    {
142 10
        if ($scheme === null || $this->isRelative($url)) {
143 1
            return $url;
144
        }
145
146 10
        if (strpos($url, '//') === 0) {
147
            // e.g. //example.com/path/to/resource
148 3
            return $scheme === '' ? $url : "$scheme:$url";
149
        }
150
151 9
        if (($pos = strpos($url, '://')) !== false) {
152 9
            if ($scheme === '') {
153 3
                $url = substr($url, $pos + 1);
154
            } else {
155 6
                $url = $scheme . substr($url, $pos);
156
            }
157
        }
158
159 9
        return $url;
160
    }
161
162
    /**
163
     * Returns a value indicating whether a URL is relative.
164
     * A relative URL does not have host info part.
165
     *
166
     * @param string $url the URL to be checked
167
     *
168
     * @return bool whether the URL is relative
169
     */
170 16
    private function isRelative(string $url): bool
171
    {
172 16
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
173
    }
174
175 33
    public function getUriPrefix(): string
176
    {
177 33
        return $this->uriPrefix;
178
    }
179
180 1
    public function setEncodeRaw(bool $encodeRaw): void
181
    {
182 1
        $this->encodeRaw = $encodeRaw;
183 1
    }
184
185 5
    public function setUriPrefix(string $name): void
186
    {
187 5
        $this->uriPrefix = $name;
188 5
    }
189
190 2
    public function getLocales(): array
191
    {
192 2
        return $this->locales;
193
    }
194
195 1
    public function setLocale(string $locale): void
196
    {
197 1
        $this->locale = $locale;
198 1
    }
199
200 6
    public function setLocales(array $locales): void
201
    {
202 6
        $this->locales = $locales;
203 6
    }
204
205 3
    public function setLocaleParameterName(string $localeParameterName): void
206
    {
207 3
        $this->localeParameterName = $localeParameterName;
208 3
    }
209
210
    /**
211
     * Checks for any missing route parameters
212
     *
213
     * @param array $parts
214
     * @param array $substitutions
215
     *
216
     * @return array with minimum required parameters if any are missing or an empty array if none are missing
217
     */
218 34
    private function missingParameters(array $parts, array $substitutions): array
219
    {
220 34
        $missingParameters = [];
221
222
        // Gather required parameters
223 34
        foreach ($parts as $part) {
224 34
            if (is_string($part)) {
225 34
                continue;
226
            }
227
228 10
            $missingParameters[] = $part[0];
229
        }
230
231
        // Check if all parameters exist
232 34
        foreach ($missingParameters as $parameter) {
233 10
            if (!array_key_exists($parameter, $substitutions)) {
234
                // Return the parameters so they can be used in an
235
                // exception if needed
236 3
                return $missingParameters;
237
            }
238
        }
239
240
        // All required parameters are available
241 32
        return [];
242
    }
243
244 32
    private function generatePath(array $parameters, array $parts): string
245
    {
246 32
        $notSubstitutedParams = $parameters;
247 32
        $uriPrefix = $this->getUriPrefix();
248 32
        $path = '';
249
250 32
        foreach ($parts as $part) {
251 32
            if (is_string($part)) {
252
                // Append the string
253 32
                $path .= $part;
254 32
                continue;
255
            }
256
257
            // Check substitute value with regex
258 7
            $pattern = str_replace('~', '\~', $part[1]);
259 7
            if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
260 1
                throw new RuntimeException(
261 1
                    sprintf(
262 1
                        'Parameter value for [%s] did not match the regex `%s`',
263 1
                        $part[0],
264 1
                        $part[1]
265
                    )
266
                );
267
            }
268
269
            // Append the substituted value
270 6
            $path .= $this->encodeRaw
271 6
                ? rawurlencode((string)$parameters[$part[0]])
272 1
                : urlencode((string)$parameters[$part[0]]);
273 6
            unset($notSubstitutedParams[$part[0]]);
274
        }
275
276 31
        $pathStartsWithSlash = strpos($path, '/') === 0;
277 31
        if ($this->locale !== '') {
278 4
            $uriPrefix = ($pathStartsWithSlash ? '/' : '') . $this->locale . $uriPrefix;
279
        }
280
281 31
        return $uriPrefix . $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
282
    }
283
}
284