Passed
Push — master ( abb543...1af822 )
by Alexander
02:36 queued 28s
created

UrlGenerator   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 218
Duplicated Lines 0 %

Test Coverage

Coverage 95.29%

Importance

Changes 11
Bugs 0 Features 0
Metric Value
eloc 78
c 11
b 0
f 0
dl 0
loc 218
ccs 81
cts 85
cp 0.9529
rs 8.8798
wmc 44

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A setEncodeRaw() 0 3 1
A setUriPrefix() 0 3 1
A getUriPrefix() 0 3 1
A generateAbsoluteFromLastMatchedRequest() 0 4 3
C generateAbsolute() 0 21 13
B ensureScheme() 0 20 7
A missingParameters() 0 24 5
A isRelative() 0 3 2
A generatePath() 0 32 6
A generate() 0 31 4

How to fix   Complexity   

Complex Class

Complex classes like UrlGenerator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UrlGenerator, and based on these observations, apply Extract Interface, too.

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