| Total Complexity | 40 | 
| Total Lines | 266 | 
| 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  | 
            ||
| 33 | class RouteCompiler implements RouteCompilerInterface  | 
            ||
| 34 | { | 
            ||
| 35 | private const DEFAULT_SEGMENT = '[^\/]+';  | 
            ||
| 36 | |||
| 37 | /**  | 
            ||
| 38 | * This string defines the characters that are automatically considered separators in front of  | 
            ||
| 39 | * optional placeholders (with default and no static text following). Such a single separator  | 
            ||
| 40 | * can be left out together with the optional placeholder from matching and generating URLs.  | 
            ||
| 41 | */  | 
            ||
| 42 | private const PATTERN_REPLACES = ['/' => '\\/', '/[' => '\/?(?:', '[' => '(?:', ']' => ')?', '.' => '\.'];  | 
            ||
| 43 | |||
| 44 | private const SEGMENT_REPLACES = ['/' => '\\/', '.' => '\.'];  | 
            ||
| 45 | |||
| 46 | /**  | 
            ||
| 47 | * This regex is used to match a certain rule of pattern to be used for routing.  | 
            ||
| 48 | *  | 
            ||
| 49 | * List of string patterns that regex matches:  | 
            ||
| 50 |      * - /{var} - A required variable pattern | 
            ||
| 51 |      * - /[{var}] - An optional variable pattern | 
            ||
| 52 |      * - /foo[/{var}] - A path with an optional sub variable pattern | 
            ||
| 53 |      * - /foo[/{var}[.{format}]] - A path with optional nested variables | 
            ||
| 54 |      * - /{var:[a-z]+} - A required variable with lowercase rule | 
            ||
| 55 |      * - /{var=foo} - A required variable with default value | 
            ||
| 56 |      * - /{var}[.{format:(html|php)=html}] - A required variable with an optional variable, a rule & default | 
            ||
| 57 | */  | 
            ||
| 58 |     private const COMPILER_REGEX = '~\\{(\\w+)(?:\\:([^{}=]+(?:\\{[\\w,^{}]+)?))?(?:\\=((?2)))?\\}~i'; | 
            ||
| 59 | |||
| 60 | /**  | 
            ||
| 61 | * A matching requirement helper, to ease matching route pattern when found.  | 
            ||
| 62 | */  | 
            ||
| 63 | private const SEGMENT_TYPES = [  | 
            ||
| 64 | 'int' => '\d+',  | 
            ||
| 65 | 'lower' => '[a-z]+',  | 
            ||
| 66 | 'upper' => '[A-Z]+',  | 
            ||
| 67 | 'alpha' => '[A-Za-z]+',  | 
            ||
| 68 | 'alnum' => '[A-Za-z0-9]+',  | 
            ||
| 69 |         'year' => '[12][0-9]{3}', | 
            ||
| 70 | 'month' => '0[1-9]|1[012]+',  | 
            ||
| 71 | 'day' => '0[1-9]|[12][0-9]|3[01]+',  | 
            ||
| 72 |         '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}', | 
            ||
| 73 | ];  | 
            ||
| 74 | |||
| 75 | /**  | 
            ||
| 76 | * A helper in reversing route pattern to URI.  | 
            ||
| 77 | */  | 
            ||
| 78 | private const URI_FIXERS = [  | 
            ||
| 79 | '[]' => '',  | 
            ||
| 80 | '[/]' => '',  | 
            ||
| 81 | '[' => '',  | 
            ||
| 82 | ']' => '',  | 
            ||
| 83 | '://' => '://',  | 
            ||
| 84 | '//' => '/',  | 
            ||
| 85 | '/..' => '/%2E%2E',  | 
            ||
| 86 | '/.' => '/%2E',  | 
            ||
| 87 | ];  | 
            ||
| 88 | |||
| 89 | /**  | 
            ||
| 90 | * The maximum supported length of a PCRE subpattern name  | 
            ||
| 91 | * http://pcre.org/current/doc/html/pcre2pattern.html#SEC16.  | 
            ||
| 92 | *  | 
            ||
| 93 | * @internal  | 
            ||
| 94 | */  | 
            ||
| 95 | private const VARIABLE_MAXIMUM_LENGTH = 32;  | 
            ||
| 96 | |||
| 97 | /**  | 
            ||
| 98 |      * {@inheritdoc} | 
            ||
| 99 | */  | 
            ||
| 100 | public function compile(Route $route): array  | 
            ||
| 125 | }  | 
            ||
| 126 | |||
| 127 | /**  | 
            ||
| 128 |      * {@inheritdoc} | 
            ||
| 129 | */  | 
            ||
| 130 | public function generateUri(Route $route, array $parameters, array $defaults = []): GeneratedUri  | 
            ||
| 131 |     { | 
            ||
| 132 |         [$pathRegex, $pathVariables] = self::compilePattern(\ltrim($route->get('path'), '/'), true); | 
            ||
| 133 | |||
| 134 |         $pathRegex = '/' . \stripslashes(\str_replace('?', '', $pathRegex)); | 
            ||
| 135 | $createUri = new GeneratedUri(self::interpolate($pathRegex, $parameters, $defaults, $pathVariables));  | 
            ||
| 136 | |||
| 137 |         foreach ($route->get('domain') as $host) { | 
            ||
| 138 | $compiledHost = self::compilePattern($host, true);  | 
            ||
| 139 | |||
| 140 |             if (!empty($compiledHost)) { | 
            ||
| 141 | [$hostRegex, $hostVariables] = $compiledHost;  | 
            ||
| 142 | |||
| 143 | break;  | 
            ||
| 144 | }  | 
            ||
| 145 | }  | 
            ||
| 146 | |||
| 147 |         if (!empty($schemes = $route->get('schemes'))) { | 
            ||
| 148 |             $createUri->withScheme(\in_array('https', $schemes, true) ? 'https' : \end($schemes) ?? 'http'); | 
            ||
| 149 | |||
| 150 |             if (!isset($hostRegex)) { | 
            ||
| 151 | $createUri->withHost($_SERVER['HTTP_HOST'] ?? '');  | 
            ||
| 152 | }  | 
            ||
| 153 | }  | 
            ||
| 154 | |||
| 155 |         if (isset($hostRegex)) { | 
            ||
| 156 | $createUri->withHost(self::interpolate($hostRegex, $parameters, $defaults, $hostVariables));  | 
            ||
| 157 | }  | 
            ||
| 158 | |||
| 159 | return $createUri;  | 
            ||
| 160 | }  | 
            ||
| 161 | |||
| 162 | /**  | 
            ||
| 163 | * Check for mandatory parameters then interpolate $uriRoute with given $parameters.  | 
            ||
| 164 | *  | 
            ||
| 165 | * @param array<int|string,mixed> $parameters  | 
            ||
| 166 | */  | 
            ||
| 167 | private static function interpolate(string $uriRoute, array $parameters, array $defaults, array $allowed): string  | 
            ||
| 168 |     { | 
            ||
| 169 |         \preg_match_all('#(?:\[)?\<(\w+).*?\>(?:\])?#', $uriRoute, $paramVars, \PREG_SET_ORDER); | 
            ||
| 170 | |||
| 171 |         foreach ($paramVars as $offset => [$type, $var]) { | 
            ||
| 172 |             if ('[' === $type[0]) { | 
            ||
| 173 | $defaults[$var] = null;  | 
            ||
| 174 | |||
| 175 | continue;  | 
            ||
| 176 | }  | 
            ||
| 177 | |||
| 178 |             if (isset($parameters[$offset])) { | 
            ||
| 179 | $defaults[$var] = $parameters[$offset];  | 
            ||
| 180 | unset($parameters[$offset]);  | 
            ||
| 181 | }  | 
            ||
| 182 | }  | 
            ||
| 183 | |||
| 184 | // Fetch and merge all possible parameters + route defaults ...  | 
            ||
| 185 | $parameters += $defaults;  | 
            ||
| 186 | |||
| 187 | // all params must be given  | 
            ||
| 188 |         if ($diff = \array_diff_key($allowed, $parameters)) { | 
            ||
| 189 |             throw new UrlGenerationException(\sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route path "%s".', \implode('", "', \array_keys($diff)), $uriRoute)); | 
            ||
| 190 | }  | 
            ||
| 191 | |||
| 192 | $replaces = self::URI_FIXERS;  | 
            ||
| 193 | |||
| 194 |         foreach ($parameters as $key => $value) { | 
            ||
| 195 |             $replaces["<{$key}>"] = (\is_array($value) || $value instanceof \Closure) ? '' : $value; | 
            ||
| 196 | }  | 
            ||
| 197 | |||
| 198 | return \strtr($uriRoute, $replaces);  | 
            ||
| 199 | }  | 
            ||
| 200 | |||
| 201 | private static function sanitizeRequirement(string $key, ?string $regex): string  | 
            ||
| 202 |     { | 
            ||
| 203 |         if (!empty($regex)) { | 
            ||
| 204 |             if ('^' === $regex[0]) { | 
            ||
| 205 | $regex = \substr($regex, 1);  | 
            ||
| 206 |             } elseif (0 === \strpos($regex, '\\A')) { | 
            ||
| 207 | $regex = \substr($regex, 2);  | 
            ||
| 208 | }  | 
            ||
| 209 | |||
| 210 |             if ('$' === $regex[-1]) { | 
            ||
| 211 | $regex = \substr($regex, 0, -1);  | 
            ||
| 212 |             } elseif (\strlen($regex) - 2 === \strpos($regex, '\\z')) { | 
            ||
| 213 | $regex = \substr($regex, 0, -2);  | 
            ||
| 214 | }  | 
            ||
| 215 | }  | 
            ||
| 216 | |||
| 217 |         if ('' === $regex) { | 
            ||
| 218 |             throw new \InvalidArgumentException(\sprintf('Routing requirement for "%s" cannot be empty.', $key)); | 
            ||
| 219 | }  | 
            ||
| 220 | |||
| 221 | return null !== $regex ? \strtr($regex, self::SEGMENT_REPLACES) : self::DEFAULT_SEGMENT;  | 
            ||
| 222 | }  | 
            ||
| 223 | |||
| 224 | /**  | 
            ||
| 225 | * @param array<string,string|string[]> $requirements  | 
            ||
| 226 | *  | 
            ||
| 227 | * @throws UriHandlerException if a variable name starts with a digit or  | 
            ||
| 228 | * if it is too long to be successfully used as a PCRE subpattern or  | 
            ||
| 229 | * if a variable is referenced more than once  | 
            ||
| 230 | *  | 
            ||
| 231 | * @return array<string,mixed>  | 
            ||
| 232 | */  | 
            ||
| 233 | private static function compilePattern(string $uriPattern, bool $reversed = false, array $requirements = []): array  | 
            ||
| 234 |     { | 
            ||
| 235 | $variables = $replaces = [];  | 
            ||
| 236 | |||
| 237 | // correct [/ first occurrence]  | 
            ||
| 238 |         if (0 === \strpos($uriPattern, '[/')) { | 
            ||
| 239 | $uriPattern = '[' . \substr($uriPattern, 3);  | 
            ||
| 240 | }  | 
            ||
| 241 | |||
| 242 |         // Match all variables enclosed in "{}" and iterate over them... | 
            ||
| 243 | \preg_match_all(self::COMPILER_REGEX, $uriPattern, $matches, \PREG_SET_ORDER | \PREG_UNMATCHED_AS_NULL);  | 
            ||
| 244 | |||
| 245 |         foreach ($matches as [$placeholder, $varName, $segment, $default]) { | 
            ||
| 246 | // Filter variable name to meet requirement  | 
            ||
| 247 | self::filterVariableName($varName, $uriPattern);  | 
            ||
| 248 | |||
| 249 |             if (\array_key_exists($varName, $variables)) { | 
            ||
| 250 |                 throw new UriHandlerException(\sprintf('Route pattern "%s" cannot reference variable name "%s" more than once.', $uriPattern, $varName)); | 
            ||
| 251 | }  | 
            ||
| 252 | |||
| 253 | $variables[$varName] = $default;  | 
            ||
| 254 | $replaces[$placeholder] = !$reversed ? '(?P<' . $varName . '>' . (self::SEGMENT_TYPES[$segment] ?? $segment ?? self::prepareSegment($varName, $requirements)) . ')' : "<$varName>";  | 
            ||
| 255 | }  | 
            ||
| 256 | |||
| 257 | return [\strtr($uriPattern, !$reversed ? self::PATTERN_REPLACES + $replaces : $replaces), $variables];  | 
            ||
| 258 | }  | 
            ||
| 259 | |||
| 260 | /**  | 
            ||
| 261 | * Prevent variables with same name used more than once.  | 
            ||
| 262 | */  | 
            ||
| 263 | private static function filterVariableName(string $varName, string $pattern): void  | 
            ||
| 280 | )  | 
            ||
| 281 | );  | 
            ||
| 282 | }  | 
            ||
| 283 | }  | 
            ||
| 284 | |||
| 285 | /**  | 
            ||
| 286 | * Prepares segment pattern with given constrains.  | 
            ||
| 287 | *  | 
            ||
| 288 | * @param array<string,mixed> $requirements  | 
            ||
| 289 | */  | 
            ||
| 290 | private static function prepareSegment(string $name, array $requirements): string  | 
            ||
| 299 | }  | 
            ||
| 300 | }  | 
            ||
| 301 | 
Let?s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let?s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: