Passed
Pull Request — master (#81)
by Rustam
21:57 queued 10:53
created

UrlGenerator::getLocales()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
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\CurrentRoute;
11
use Yiisoft\Router\RouteCollectionInterface;
12
use Yiisoft\Router\RouteNotFoundException;
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 bool $encodeRaw = true;
25
    private array $locales = [];
26
    private string $localeParameterName = '_locale';
27
    private RouteCollectionInterface $routeCollection;
28
    private ?CurrentRoute $currentRoute;
29
    private RouteParser $routeParser;
30
31 28
    public function __construct(
32
        RouteCollectionInterface $routeCollection,
33
        CurrentRoute $currentRoute = null,
34
        RouteParser $parser = null
35
    ) {
36 28
        $this->currentRoute = $currentRoute;
37 28
        $this->routeCollection = $routeCollection;
38 28
        $this->routeParser = $parser ?? new RouteParser\Std();
39 28
    }
40
41
    /**
42
     * {@inheritDoc}
43
     *
44
     * Replacements in FastRoute are written as `{name}` or `{name:<pattern>}`;
45
     * this method uses {@see RouteParser\Std} to search for the best route
46
     * match based on the available substitutions and generates a uri.
47
     *
48
     * @throws RuntimeException if parameter value does not match its regex.
49
     */
50 28
    public function generate(string $name, array $parameters = []): string
51
    {
52
        if (
53 28
            isset($parameters[$this->localeParameterName])
54 28
            && $this->locales !== []
55
        ) {
56
            $locale = $parameters[$this->localeParameterName];
57
            $path = ($this->currentRoute !== null && $this->currentRoute->getUri() !== null)
58
                ? $this->currentRoute->getUri()->getPath()
59
                : '';
60
            if (isset($this->locales[$locale])) {
61
                return '/' . $locale . $path;
62
            }
63
        }
64 28
        $route = $this->routeCollection->getRoute($name);
65 27
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getPattern()));
66 27
        if ($parsedRoutes === []) {
67
            throw new RouteNotFoundException($name);
68
        }
69
70 27
        $missingParameters = [];
71
72
        // One route pattern can correspond to multiple routes if it has optional parts
73 27
        foreach ($parsedRoutes as $parsedRouteParts) {
74
            // Check if all parameters can be substituted
75 27
            $missingParameters = $this->missingParameters($parsedRouteParts, $parameters);
76
77
            // If not all parameters can be substituted, try the next route
78 27
            if (!empty($missingParameters)) {
79 3
                continue;
80
            }
81
82 25
            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 16
    public function generateAbsolute(
97
        string $name,
98
        array $parameters = [],
99
        string $scheme = null,
100
        string $host = null
101
    ): string {
102 16
        $url = $this->generate($name, $parameters);
103 16
        $route = $this->routeCollection->getRoute($name);
104
        /** @var UriInterface $uri */
105 16
        $uri = $this->currentRoute && $this->currentRoute->getUri() !== null ? $this->currentRoute->getUri() : null;
106 16
        $lastRequestScheme = $uri !== null ? $uri->getScheme() : null;
107
108 16
        if ($host !== null || ($host = $route->getHost()) !== 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 5
        return $uri === null ? $url : $this->generateAbsoluteFromLastMatchedRequest($url, $uri, $scheme);
121
    }
122
123 4
    private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
124
    {
125 4
        $port = $uri->getPort() === 80 || $uri->getPort() === null ? '' : ':' . $uri->getPort();
126 4
        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 9
    private function ensureScheme(string $url, ?string $scheme): string
141
    {
142 9
        if ($scheme === null || $this->isRelative($url)) {
143 1
            return $url;
144
        }
145
146 9
        if (strpos($url, '//') === 0) {
147
            // e.g. //example.com/path/to/resource
148 3
            return $scheme === '' ? $url : "$scheme:$url";
149
        }
150
151 8
        if (($pos = strpos($url, '://')) !== false) {
152 8
            if ($scheme === '') {
153 3
                $url = substr($url, $pos + 1);
154
            } else {
155 5
                $url = $scheme . substr($url, $pos);
156
            }
157
        }
158
159 8
        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 15
    private function isRelative(string $url): bool
171
    {
172 15
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
173
    }
174
175 25
    public function getUriPrefix(): string
176
    {
177 25
        return $this->uriPrefix;
178
    }
179
180 1
    public function setEncodeRaw(bool $encodeRaw): void
181
    {
182 1
        $this->encodeRaw = $encodeRaw;
183 1
    }
184
185
    public function setUriPrefix(string $name): void
186
    {
187
        $this->uriPrefix = $name;
188
    }
189
190
    public function getLocales(): array
191
    {
192
        return $this->locales;
193
    }
194
195
    public function setLocales(array $locales): void
196
    {
197
        $this->locales = $locales;
198
    }
199
200
    public function setLocaleParameterName(string $localeParameterName): void
201
    {
202
        $this->localeParameterName = $localeParameterName;
203
    }
204
205
    /**
206
     * Checks for any missing route parameters
207
     *
208
     * @param array $parts
209
     * @param array $substitutions
210
     *
211
     * @return array with minimum required parameters if any are missing or an empty array if none are missing
212
     */
213 27
    private function missingParameters(array $parts, array $substitutions): array
214
    {
215 27
        $missingParameters = [];
216
217
        // Gather required parameters
218 27
        foreach ($parts as $part) {
219 27
            if (is_string($part)) {
220 27
                continue;
221
            }
222
223 10
            $missingParameters[] = $part[0];
224
        }
225
226
        // Check if all parameters exist
227 27
        foreach ($missingParameters as $parameter) {
228 10
            if (!array_key_exists($parameter, $substitutions)) {
229
                // Return the parameters so they can be used in an
230
                // exception if needed
231 3
                return $missingParameters;
232
            }
233
        }
234
235
        // All required parameters are available
236 25
        return [];
237
    }
238
239 25
    private function generatePath(array $parameters, array $parts): string
240
    {
241 25
        $notSubstitutedParams = $parameters;
242 25
        $path = $this->getUriPrefix();
243
244 25
        foreach ($parts as $part) {
245 25
            if (is_string($part)) {
246
                // Append the string
247 25
                $path .= $part;
248 25
                continue;
249
            }
250
251
            // Check substitute value with regex
252 7
            $pattern = str_replace('~', '\~', $part[1]);
253 7
            if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
254 1
                throw new RuntimeException(
255 1
                    sprintf(
256 1
                        'Parameter value for [%s] did not match the regex `%s`',
257 1
                        $part[0],
258 1
                        $part[1]
259
                    )
260
                );
261
            }
262
263
            // Append the substituted value
264 6
            $path .= $this->encodeRaw
265 6
                ? rawurlencode((string)$parameters[$part[0]])
266 1
                : urlencode((string)$parameters[$part[0]]);
267 6
            unset($notSubstitutedParams[$part[0]]);
268
        }
269
270 24
        return $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
271
    }
272
}
273