Total Complexity | 42 |
Total Lines | 298 |
Duplicated Lines | 0 % |
Changes | 4 | ||
Bugs | 0 | Features | 0 |
Complex classes like RouteCompiler 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 RouteCompiler, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
34 | final class RouteCompiler implements RouteCompilerInterface |
||
35 | { |
||
36 | private const DEFAULT_SEGMENT = '[^\/]+'; |
||
37 | |||
38 | /** |
||
39 | * This string defines the characters that are automatically considered separators in front of |
||
40 | * optional placeholders (with default and no static text following). Such a single separator |
||
41 | * can be left out together with the optional placeholder from matching and generating URLs. |
||
42 | */ |
||
43 | private const PATTERN_REPLACES = ['/' => '\\/', '/[' => '\/?(?:', '[' => '(?:', ']' => ')?', '.' => '\.']; |
||
44 | |||
45 | private const SEGMENT_REPLACES = ['/' => '\\/', '.' => '\.']; |
||
46 | |||
47 | /** |
||
48 | * This regex is used to match a certain rule of pattern to be used for routing. |
||
49 | * |
||
50 | * List of string patterns that regex matches: |
||
51 | * - /{var} - A required variable pattern |
||
52 | * - /[{var}] - An optional variable pattern |
||
53 | * - /foo[/{var}] - A path with an optional sub variable pattern |
||
54 | * - /foo[/{var}[.{format}]] - A path with optional nested variables |
||
55 | * - /{var:[a-z]+} - A required variable with lowercase rule |
||
56 | * - /{var=foo} - A required variable with default value |
||
57 | * - /{var}[.{format:(html|php)=html}] - A required variable with an optional variable, a rule & default |
||
58 | */ |
||
59 | private const COMPILER_REGEX = '~\{(\w+)(?:\:(.*?\}?))?(?:\=(\w+))?\}~iu'; |
||
60 | |||
61 | /** |
||
62 | * This regex is used to reverse a pattern path, matching required and options vars. |
||
63 | */ |
||
64 | private const REVERSED_REGEX = '#(?|\<(\w+)\>|(\[(.*)]))#'; |
||
65 | |||
66 | /** |
||
67 | * A matching requirement helper, to ease matching route pattern when found. |
||
68 | */ |
||
69 | private const SEGMENT_TYPES = [ |
||
70 | 'int' => '\d+', |
||
71 | 'lower' => '[a-z]+', |
||
72 | 'upper' => '[A-Z]+', |
||
73 | 'alpha' => '[A-Za-z]+', |
||
74 | 'alnum' => '[A-Za-z0-9]+', |
||
75 | 'year' => '[12][0-9]{3}', |
||
76 | 'month' => '0[1-9]|1[012]+', |
||
77 | 'day' => '0[1-9]|[12][0-9]|3[01]+', |
||
78 | 'uuid' => '0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}', |
||
79 | ]; |
||
80 | |||
81 | /** |
||
82 | * A helper in reversing route pattern to URI. |
||
83 | */ |
||
84 | private const URI_FIXERS = [ |
||
85 | '[]' => '', |
||
86 | '[/]' => '', |
||
87 | '[' => '', |
||
88 | ']' => '', |
||
89 | '://' => '://', |
||
90 | '//' => '/', |
||
91 | '/..' => '/%2E%2E', |
||
92 | '/.' => '/%2E', |
||
93 | ]; |
||
94 | |||
95 | /** |
||
96 | * The maximum supported length of a PCRE subpattern name |
||
97 | * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16. |
||
98 | * |
||
99 | * @internal |
||
100 | */ |
||
101 | private const VARIABLE_MAXIMUM_LENGTH = 32; |
||
102 | |||
103 | /** |
||
104 | * {@inheritdoc} |
||
105 | */ |
||
106 | public function compile(Route $route): array |
||
133 | } |
||
134 | |||
135 | /** |
||
136 | * {@inheritdoc} |
||
137 | */ |
||
138 | public function generateUri(Route $route, array $parameters): GeneratedUri |
||
139 | { |
||
140 | [$pathRegex, $pathVariables] = self::compilePattern('/' . \ltrim($route->get('path'), '/'), true); |
||
141 | |||
142 | $defaults = $route->get('defaults'); |
||
143 | $createUri = new GeneratedUri(self::interpolate($pathRegex, $parameters, $defaults + $pathVariables)); |
||
144 | |||
145 | foreach ($route->get('hosts') as $host) { |
||
146 | $compiledHost = self::compilePattern($host, true); |
||
147 | |||
148 | if (!empty($compiledHost)) { |
||
149 | [$hostRegex, $hostVariables] = $compiledHost; |
||
150 | |||
151 | break; |
||
152 | } |
||
153 | } |
||
154 | |||
155 | if (!empty($schemes = $route->get('schemes'))) { |
||
156 | $createUri->withScheme(\in_array('https', $schemes, true) ? 'https' : \end($schemes) ?? 'http'); |
||
157 | |||
158 | if (!isset($hostRegex)) { |
||
159 | $createUri->withHost($_SERVER['HTTP_HOST'] ?? ''); |
||
160 | } |
||
161 | } |
||
162 | |||
163 | if (isset($hostRegex)) { |
||
164 | $createUri->withHost(self::interpolate($hostRegex, $parameters, $defaults + $hostVariables)); |
||
165 | } |
||
166 | |||
167 | return $createUri; |
||
168 | } |
||
169 | |||
170 | /** |
||
171 | * Check for mandatory parameters then interpolate $uriRoute with given $parameters. |
||
172 | * |
||
173 | * @param array<string,mixed> $parameters |
||
174 | * @param array<string,mixed> $defaults |
||
175 | */ |
||
176 | private static function interpolate(string $uriRoute, array $parameters, array $defaults): string |
||
177 | { |
||
178 | $required = []; // Parameters required which are missing. |
||
179 | $replaces = self::URI_FIXERS; |
||
180 | |||
181 | // Fetch and merge all possible parameters + route defaults ... |
||
182 | \preg_match_all(self::REVERSED_REGEX, $uriRoute, $matches, \PREG_SET_ORDER | \PREG_UNMATCHED_AS_NULL); |
||
183 | |||
184 | foreach ($matches as $matched) { |
||
185 | if (3 === \count($matched) && isset($matched[2])) { |
||
186 | \preg_match_all('#\<(\w+)\>#', $matched[2], $optionalVars, \PREG_SET_ORDER); |
||
187 | |||
188 | foreach ($optionalVars as [$type, $var]) { |
||
189 | $replaces[$type] = $parameters[$var] ?? $defaults[$var] ?? null; |
||
190 | } |
||
191 | |||
192 | continue; |
||
193 | } |
||
194 | |||
195 | $replaces[$matched[0]] = $parameters[$matched[1]] ?? $defaults[$matched[1]] ?? null; |
||
196 | |||
197 | if (null === $replaces[$matched[0]]) { |
||
198 | $required[] = $matched[1]; |
||
199 | } |
||
200 | } |
||
201 | |||
202 | if (!empty($required)) { |
||
203 | throw new UrlGenerationException(\sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route path "%s".', \implode('", "', $required), $uriRoute)); |
||
204 | } |
||
205 | |||
206 | return \strtr($uriRoute, $replaces); |
||
207 | } |
||
208 | |||
209 | private static function sanitizeRequirement(string $key, ?string $regex): string |
||
210 | { |
||
211 | if ('' !== $regex) { |
||
212 | if ('^' === $regex[0]) { |
||
213 | $regex = \substr($regex, 1); |
||
214 | } elseif (0 === \strpos($regex, '\\A')) { |
||
215 | $regex = \substr($regex, 2); |
||
216 | } |
||
217 | } |
||
218 | |||
219 | if (\str_ends_with($regex, '$')) { |
||
220 | $regex = \substr($regex, 0, -1); |
||
221 | } elseif (\strlen($regex) - 2 === \strpos($regex, '\\z')) { |
||
222 | $regex = \substr($regex, 0, -2); |
||
223 | } |
||
224 | |||
225 | if ('' === $regex) { |
||
226 | throw new \InvalidArgumentException(\sprintf('Routing requirement for "%s" cannot be empty.', $key)); |
||
227 | } |
||
228 | |||
229 | return null !== $regex ? \strtr($regex, self::SEGMENT_REPLACES) : self::DEFAULT_SEGMENT; |
||
230 | } |
||
231 | |||
232 | /** |
||
233 | * @param array<string,string|string[]> $requirements |
||
234 | * |
||
235 | * @throws UriHandlerException if a variable name starts with a digit or |
||
236 | * if it is too long to be successfully used as a PCRE subpattern or |
||
237 | * if a variable is referenced more than once |
||
238 | * |
||
239 | * @return array<string,mixed> |
||
240 | */ |
||
241 | private static function compilePattern(string $uriPattern, bool $reversed = false, array $requirements = []): array |
||
242 | { |
||
243 | $variables = []; // VarNames mapping to values use by route's handler. |
||
244 | $replaces = $reversed ? ['?' => ''] : self::PATTERN_REPLACES; |
||
245 | |||
246 | // correct [/ first occurrence] |
||
247 | if (1 === \strpos($uriPattern, '[/')) { |
||
248 | $uriPattern = '/[' . \substr($uriPattern, 3); |
||
249 | } |
||
250 | |||
251 | // Match all variables enclosed in "{}" and iterate over them... |
||
252 | \preg_match_all(self::COMPILER_REGEX, $uriPattern, $matches, \PREG_SET_ORDER | \PREG_UNMATCHED_AS_NULL); |
||
253 | |||
254 | foreach ($matches as [$placeholder, $varName, $segment, $default]) { |
||
255 | // Filter variable name to meet requirement |
||
256 | self::filterVariableName($varName, $uriPattern); |
||
257 | |||
258 | if (\array_key_exists($varName, $variables)) { |
||
259 | throw new UriHandlerException(\sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $uriPattern, $varName)); |
||
260 | } |
||
261 | |||
262 | $variables[$varName] = $default; |
||
263 | $replaces[$placeholder] = !$reversed ? '(?P<' . $varName . '>' . (self::SEGMENT_TYPES[$segment] ?? $segment ?? self::prepareSegment($varName, $requirements)) . ')' : "<$varName>"; |
||
264 | } |
||
265 | |||
266 | return [\strtr($uriPattern, $replaces), $variables]; |
||
267 | } |
||
268 | |||
269 | /** |
||
270 | * @param string[] $hosts |
||
271 | * @param array<string,string|string[]> $requirements |
||
272 | */ |
||
273 | private static function compileHosts(array $hosts, array $requirements, array &$variables): ?string |
||
274 | { |
||
275 | $hostsRegex = []; |
||
276 | |||
277 | foreach ($hosts as $host) { |
||
278 | [$hostRegex, $hostVars] = self::compilePattern($host, false, $requirements); |
||
279 | |||
280 | $variables += $hostVars; |
||
281 | $hostsRegex[] = $hostRegex; |
||
282 | } |
||
283 | |||
284 | return 1 === \count($hostsRegex) ? $hostsRegex[0] : '(?|' . \implode('|', $hostsRegex) . ')'; |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * Filter variable name to meet requirements. |
||
289 | * |
||
290 | * @param array<string,string|null> $varNames |
||
291 | */ |
||
292 | private static function filterVariableName(string $varName, string $pattern): void |
||
307 | ) |
||
308 | ); |
||
309 | } |
||
310 | } |
||
311 | |||
312 | /** |
||
313 | * Prepares segment pattern with given constrains. |
||
314 | * |
||
315 | * @param array<string,mixed> $requirements |
||
316 | */ |
||
317 | private static function prepareSegment(string $name, array $requirements): string |
||
332 | )); |
||
333 | } |
||
334 | } |
||
335 |