Passed
Pull Request — master (#60)
by Dmitriy
02:03
created

UrlGenerator::generatePath()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 1
b 0
f 0
nc 7
nop 2
dl 0
loc 30
rs 9.4222
ccs 17
cts 17
cp 1
crap 5
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 ($scheme === null && !$this->isRelative($host)) {
89 7
                return rtrim($host, '/') . $url;
90
            }
91
92 5
            if ((empty($scheme) || $lastRequestScheme === null) && $host !== '' && $this->isRelative($host)) {
93 3
                $host = '//' . $host;
94
            }
95
96 5
            return $this->ensureScheme(rtrim($host, '/') . $url, $scheme ?? $lastRequestScheme);
97
        }
98
99 5
        return $uri === null ? $url : $this->generateAbsoluteFromLastMatchedRequest($url, $uri, $scheme);
100
    }
101
102 4
    private function generateAbsoluteFromLastMatchedRequest(string $url, UriInterface $uri, ?string $scheme): string
103
    {
104 4
        $port = $uri->getPort() === 80 || $uri->getPort() === null ? '' : ':' . $uri->getPort();
105 4
        return  $this->ensureScheme('://' . $uri->getHost() . $port . $url, $scheme ?? $uri->getScheme());
106
    }
107
108
    /**
109
     * Normalize URL by ensuring that it use specified scheme.
110
     *
111
     * If URL is relative or scheme is null, normalization is skipped.
112
     *
113
     * @param string $url the URL to process
114
     * @param string|null $scheme the URI scheme used in URL (e.g. `http` or `https`). Use empty string to
115
     * create protocol-relative URL (e.g. `//example.com/path`)
116
     *
117
     * @return string the processed URL
118
     */
119 9
    private function ensureScheme(string $url, ?string $scheme): string
120
    {
121 9
        if ($scheme === null || $this->isRelative($url)) {
122 1
            return $url;
123
        }
124
125 9
        if (strpos($url, '//') === 0) {
126
            // e.g. //example.com/path/to/resource
127 3
            return $scheme === '' ? $url : "$scheme:$url";
128
        }
129
130 8
        if (($pos = strpos($url, '://')) !== false) {
131 8
            if ($scheme === '') {
132 3
                $url = substr($url, $pos + 1);
133
            } else {
134 5
                $url = $scheme . substr($url, $pos);
135
            }
136
        }
137
138 8
        return $url;
139
    }
140
141
    /**
142
     * Returns a value indicating whether a URL is relative.
143
     * A relative URL does not have host info part.
144
     *
145
     * @param string $url the URL to be checked
146
     *
147
     * @return bool whether the URL is relative
148
     */
149 15
    private function isRelative(string $url): bool
150
    {
151 15
        return strncmp($url, '//', 2) && strpos($url, '://') === false;
152
    }
153
154 24
    public function getUriPrefix(): string
155
    {
156 24
        return $this->uriPrefix;
157
    }
158
159
    public function setUriPrefix(string $prefix): void
160
    {
161
        $this->uriPrefix = $prefix;
162
    }
163
164
    /**
165
     * Checks for any missing route parameters
166
     *
167
     * @param array $parts
168
     * @param array $substitutions
169
     *
170
     * @return array with minimum required parameters if any are missing or an empty array if none are missing
171
     */
172 26
    private function missingParameters(array $parts, array $substitutions): array
173
    {
174 26
        $missingParameters = [];
175
176
        // Gather required parameters
177 26
        foreach ($parts as $part) {
178 26
            if (is_string($part)) {
179 26
                continue;
180
            }
181
182 9
            $missingParameters[] = $part[0];
183
        }
184
185
        // Check if all parameters exist
186 26
        foreach ($missingParameters as $parameter) {
187 9
            if (!array_key_exists($parameter, $substitutions)) {
188
                // Return the parameters so they can be used in an
189
                // exception if needed
190 3
                return $missingParameters;
191
            }
192
        }
193
194
        // All required parameters are available
195 24
        return [];
196
    }
197
198 24
    private function generatePath(array $parameters, array $parts): string
199
    {
200 24
        $notSubstitutedParams = $parameters;
201 24
        $path = $this->getUriPrefix();
202
203 24
        foreach ($parts as $part) {
204 24
            if (is_string($part)) {
205
                // Append the string
206 24
                $path .= $part;
207 24
                continue;
208
            }
209
210
            // Check substitute value with regex
211 6
            $pattern = str_replace('~', '\~', $part[1]);
212 6
            if (preg_match('~^' . $pattern . '$~', (string)$parameters[$part[0]]) === 0) {
213 1
                throw new \RuntimeException(
214 1
                    sprintf(
215 1
                        'Parameter value for [%s] did not match the regex `%s`',
216 1
                        $part[0],
217 1
                        $part[1]
218
                    )
219
                );
220
            }
221
222
            // Append the substituted value
223 5
            $path .= $parameters[$part[0]];
224 5
            unset($notSubstitutedParams[$part[0]]);
225
        }
226
227 23
        return $path . ($notSubstitutedParams !== [] ? '?' . http_build_query($notSubstitutedParams) : '');
228
    }
229
}
230