Passed
Pull Request — master (#58)
by Mr.
02:17
created

UrlGenerator   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 204
Duplicated Lines 0 %

Test Coverage

Coverage 94.81%

Importance

Changes 10
Bugs 0 Features 0
Metric Value
eloc 71
c 10
b 0
f 0
dl 0
loc 204
ccs 73
cts 77
cp 0.9481
rs 9.28
wmc 39

10 Methods

Rating   Name   Duplication   Size   Complexity  
A isRelative() 0 3 2
A __construct() 0 8 1
A missingParameters() 0 24 5
A generatePath() 0 30 5
A generate() 0 30 4
A getUriPrefix() 0 3 1
A generateAbsoluteFromLastMatchedRequest() 0 4 3
B generateAbsolute() 0 17 10
B ensureScheme() 0 20 7
A setUriPrefix() 0 3 1
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 Yiisoft\Router\RouteCollectionInterface;
10
use Yiisoft\Router\RouteNotFoundException;
11
use Yiisoft\Router\UrlGeneratorInterface;
12
use Yiisoft\Router\UrlMatcherInterface;
13
14
use function array_key_exists;
15
use function array_keys;
16
use function implode;
17
use function is_string;
18
use function preg_match;
19
20
final class UrlGenerator implements UrlGeneratorInterface
21
{
22
    private string $uriPrefix = '';
23
    private RouteCollectionInterface $routeCollection;
24
    private ?UrlMatcherInterface $matcher;
25
    private RouteParser $routeParser;
26
27 27
    public function __construct(
28
        RouteCollectionInterface $routeCollection,
29
        UrlMatcherInterface $matcher = null,
30
        RouteParser $parser = null
31
    ) {
32 27
        $this->matcher = $matcher;
33 27
        $this->routeCollection = $routeCollection;
34 27
        $this->routeParser = $parser ?? new RouteParser\Std();
35 27
    }
36
37
    /**
38
     * {@inheritDoc}
39
     *
40
     * Replacements in FastRoute are written as `{name}` or `{name:<pattern>}`;
41
     * this method uses `FastRoute\RouteParser\Std` to search for the best route
42
     * match based on the available substitutions and generates a uri.
43
     *
44
     * @throws \RuntimeException if parameter value does not match its regex.
45
     */
46 27
    public function generate(string $name, array $parameters = []): string
47
    {
48 27
        $route = $this->routeCollection->getRoute($name);
49
50 26
        $parsedRoutes = array_reverse($this->routeParser->parse($route->getPattern()));
51 26
        if ($parsedRoutes === []) {
52
            throw new RouteNotFoundException($name);
53
        }
54
55 26
        $missingParameters = [];
56
57
        // One route pattern can correspond to multiple routes if it has optional parts
58 26
        foreach ($parsedRoutes as $parsedRouteParts) {
59
            // Check if all parameters can be substituted
60 26
            $missingParameters = $this->missingParameters($parsedRouteParts, $parameters);
61
62
            // If not all parameters can be substituted, try the next route
63 26
            if (!empty($missingParameters)) {
64 3
                continue;
65
            }
66
67 24
            return $this->generatePath($parameters, $parsedRouteParts);
68
        }
69
70
        // No valid route was found: list minimal required parameters
71 2
        throw new \RuntimeException(sprintf(
72 2
            'Route `%s` expects at least parameter values for [%s], but received [%s]',
73
            $name,
74 2
            implode(',', $missingParameters),
75 2
            implode(',', array_keys($parameters))
76
        ));
77
    }
78
79 16
    public function generateAbsolute(string $name, array $parameters = [], string $scheme = null, string $host = null): string
80
    {
81 16
        $url = $this->generate($name, $parameters);
82 16
        $route = $this->routeCollection->getRoute($name);
83
        /** @var UriInterface $uri */
84 16
        $uri = $this->matcher && $this->matcher->getCurrentUri() !== null ? $this->matcher->getCurrentUri() : null;
85 16
        $lastRequestScheme = $uri !== null ? $uri->getScheme() : null;
86
87 16
        if ($host !== null || ($host = $route->getHost()) !== null) {
88 11
            if (empty($scheme) && $host !== '' && $this->isRelative($host)) {
89 3
                $host = '//' . $host;
90
            }
91
92 11
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme ?? $lastRequestScheme);
93
        }
94
95 5
        return $uri === null ? $url : $this->generateAbsoluteFromLastMatchedRequest($url, $uri, $scheme);
96
    }
97
98 4
    private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
99
    {
100 4
        $port = $uri->getPort() === 80 || $uri->getPort() === null ? '' : ':' . $uri->getPort();
101 4
        return  $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $uri->getScheme());
102
    }
103
104
    /**
105
     * Normalize URL by ensuring that it use specified scheme.
106
     *
107
     * If URL is relative or scheme is null, normalization is skipped.
108
     *
109
     * @param string $url the URL to process
110
     * @param string|null $scheme the URI scheme used in URL (e.g. `http` or `https`). Use empty string to
111
     * create protocol-relative URL (e.g. `//example.com/path`)
112
     *
113
     * @return string the processed URL
114
     */
115 15
    private function ensureScheme(string $url, ?string $scheme): string
116
    {
117 15
        if ($scheme === null || $this->isRelative($url)) {
118 5
            return $url;
119
        }
120
121 10
        if (strpos($url, '//') === 0) {
122
            // e.g. //example.com/path/to/resource
123 4
            return $scheme === '' ? $url : "$scheme:$url";
124
        }
125
126 8
        if (($pos = strpos($url, '://')) !== false) {
127 8
            if ($scheme === '') {
128 3
                $url = substr($url, $pos + 1);
129
            } else {
130 6
                $url = $scheme . substr($url, $pos);
131
            }
132
        }
133
134 8
        return $url;
135
    }
136
137
    /**
138
     * Returns a value indicating whether a URL is relative.
139
     * A relative URL does not have host info part.
140
     *
141
     * @param string $url the URL to be checked
142
     *
143
     * @return bool whether the URL is relative
144
     */
145 15
    private function isRelative(string $url): bool
146
    {
147 15
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
148
    }
149
150 24
    public function getUriPrefix(): string
151
    {
152 24
        return $this->uriPrefix;
153
    }
154
155
    public function setUriPrefix(string $prefix): void
156
    {
157
        $this->uriPrefix = $prefix;
158
    }
159
160
    /**
161
     * Checks for any missing route parameters
162
     *
163
     * @param array $parts
164
     * @param array $substitutions
165
     *
166
     * @return array with minimum required parameters if any are missing or an empty array if none are missing
167
     */
168 26
    private function missingParameters(array $parts, array $substitutions): array
169
    {
170 26
        $missingParameters = [];
171
172
        // Gather required parameters
173 26
        foreach ($parts as $part) {
174 26
            if (is_string($part)) {
175 26
                continue;
176
            }
177
178 9
            $missingParameters[] = $part[0];
179
        }
180
181
        // Check if all parameters exist
182 26
        foreach ($missingParameters as $parameter) {
183 9
            if (!array_key_exists($parameter, $substitutions)) {
184
                // Return the parameters so they can be used in an
185
                // exception if needed
186 3
                return $missingParameters;
187
            }
188
        }
189
190
        // All required parameters are available
191 24
        return [];
192
    }
193
194 24
    private function generatePath(array $parameters, array $parts): string
195
    {
196 24
        $notSubstitutedParams = $parameters;
197 24
        $path = $this->getUriPrefix();
198
199 24
        foreach ($parts as $part) {
200 24
            if (is_string($part)) {
201
                // Append the string
202 24
                $path .= $part;
203 24
                continue;
204
            }
205
206
            // Check substitute value with regex
207 6
            $pattern = str_replace('~', '\~', $part[1]);
208 6
            if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
209 1
                throw new \RuntimeException(
210 1
                    sprintf(
211 1
                        'Parameter value for [%s] did not match the regex `%s`',
212 1
                        $part[0],
213 1
                        $part[1]
214
                    )
215
                );
216
            }
217
218
            // Append the substituted value
219 5
            $path .= $parameters[$part[0]];
220 5
            unset($notSubstitutedParams[$part[0]]);
221
        }
222
223 23
        return $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
224
    }
225
}
226