| Total Complexity | 60 |
| Total Lines | 493 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Complex classes like OrderedImportsFixer 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 OrderedImportsFixer, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 42 | final class OrderedImportsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface |
||
| 43 | { |
||
| 44 | /** |
||
| 45 | * @internal |
||
| 46 | */ |
||
| 47 | public const IMPORT_TYPE_CLASS = 'class'; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @internal |
||
| 51 | */ |
||
| 52 | public const IMPORT_TYPE_CONST = 'const'; |
||
| 53 | |||
| 54 | /** |
||
| 55 | * @internal |
||
| 56 | */ |
||
| 57 | public const IMPORT_TYPE_FUNCTION = 'function'; |
||
| 58 | |||
| 59 | /** |
||
| 60 | * @internal |
||
| 61 | */ |
||
| 62 | public const SORT_ALPHA = 'alpha'; |
||
| 63 | |||
| 64 | /** |
||
| 65 | * @internal |
||
| 66 | */ |
||
| 67 | public const SORT_LENGTH = 'length'; |
||
| 68 | |||
| 69 | /** |
||
| 70 | * @internal |
||
| 71 | */ |
||
| 72 | public const SORT_NONE = 'none'; |
||
| 73 | |||
| 74 | /** |
||
| 75 | * Array of supported sort types in configuration. |
||
| 76 | * |
||
| 77 | * @var string[] |
||
| 78 | */ |
||
| 79 | private const SUPPORTED_SORT_TYPES = [self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_FUNCTION]; |
||
| 80 | |||
| 81 | /** |
||
| 82 | * Array of supported sort algorithms in configuration. |
||
| 83 | * |
||
| 84 | * @var string[] |
||
| 85 | */ |
||
| 86 | private const SUPPORTED_SORT_ALGORITHMS = [self::SORT_ALPHA, self::SORT_LENGTH, self::SORT_NONE]; |
||
| 87 | |||
| 88 | /** |
||
| 89 | * {@inheritdoc} |
||
| 90 | */ |
||
| 91 | public function getDefinition(): FixerDefinitionInterface |
||
| 92 | { |
||
| 93 | return new FixerDefinition( |
||
| 94 | 'Ordering `use` statements.', |
||
| 95 | [ |
||
| 96 | new CodeSample("<?php\nuse Z; use A;\n"), |
||
| 97 | new CodeSample( |
||
| 98 | '<?php |
||
| 99 | use Acme\Bar; |
||
| 100 | use Bar1; |
||
| 101 | use Acme; |
||
| 102 | use Bar; |
||
| 103 | ', |
||
| 104 | ['sort_algorithm' => self::SORT_LENGTH] |
||
| 105 | ), |
||
| 106 | new VersionSpecificCodeSample( |
||
| 107 | "<?php\nuse function AAC;\nuse const AAB;\nuse AAA;\n", |
||
| 108 | new VersionSpecification(70000) |
||
| 109 | ), |
||
| 110 | new VersionSpecificCodeSample( |
||
| 111 | '<?php |
||
| 112 | use const AAAA; |
||
| 113 | use const BBB; |
||
| 114 | |||
| 115 | use Bar; |
||
| 116 | use AAC; |
||
| 117 | use Acme; |
||
| 118 | |||
| 119 | use function CCC\AA; |
||
| 120 | use function DDD; |
||
| 121 | ', |
||
| 122 | new VersionSpecification(70000), |
||
| 123 | [ |
||
| 124 | 'sort_algorithm' => self::SORT_LENGTH, |
||
| 125 | 'imports_order' => [ |
||
| 126 | self::IMPORT_TYPE_CONST, |
||
| 127 | self::IMPORT_TYPE_CLASS, |
||
| 128 | self::IMPORT_TYPE_FUNCTION, |
||
| 129 | ], |
||
| 130 | ] |
||
| 131 | ), |
||
| 132 | new VersionSpecificCodeSample( |
||
| 133 | '<?php |
||
| 134 | use const BBB; |
||
| 135 | use const AAAA; |
||
| 136 | |||
| 137 | use Acme; |
||
| 138 | use AAC; |
||
| 139 | use Bar; |
||
| 140 | |||
| 141 | use function DDD; |
||
| 142 | use function CCC\AA; |
||
| 143 | ', |
||
| 144 | new VersionSpecification(70000), |
||
| 145 | [ |
||
| 146 | 'sort_algorithm' => self::SORT_ALPHA, |
||
| 147 | 'imports_order' => [ |
||
| 148 | self::IMPORT_TYPE_CONST, |
||
| 149 | self::IMPORT_TYPE_CLASS, |
||
| 150 | self::IMPORT_TYPE_FUNCTION, |
||
| 151 | ], |
||
| 152 | ] |
||
| 153 | ), |
||
| 154 | new VersionSpecificCodeSample( |
||
| 155 | '<?php |
||
| 156 | use const BBB; |
||
| 157 | use const AAAA; |
||
| 158 | |||
| 159 | use function DDD; |
||
| 160 | use function CCC\AA; |
||
| 161 | |||
| 162 | use Acme; |
||
| 163 | use AAC; |
||
| 164 | use Bar; |
||
| 165 | ', |
||
| 166 | new VersionSpecification(70000), |
||
| 167 | [ |
||
| 168 | 'sort_algorithm' => self::SORT_NONE, |
||
| 169 | 'imports_order' => [ |
||
| 170 | self::IMPORT_TYPE_CONST, |
||
| 171 | self::IMPORT_TYPE_CLASS, |
||
| 172 | self::IMPORT_TYPE_FUNCTION, |
||
| 173 | ], |
||
| 174 | ] |
||
| 175 | ), |
||
| 176 | ] |
||
| 177 | ); |
||
| 178 | } |
||
| 179 | |||
| 180 | /** |
||
| 181 | * {@inheritdoc} |
||
| 182 | * |
||
| 183 | * Must run after GlobalNamespaceImportFixer, NoLeadingImportSlashFixer. |
||
| 184 | */ |
||
| 185 | public function getPriority(): int |
||
| 188 | } |
||
| 189 | |||
| 190 | /** |
||
| 191 | * {@inheritdoc} |
||
| 192 | */ |
||
| 193 | public function isCandidate(Tokens $tokens): bool |
||
| 194 | { |
||
| 195 | return $tokens->isTokenKindFound(T_USE); |
||
| 196 | } |
||
| 197 | |||
| 198 | /** |
||
| 199 | * {@inheritdoc} |
||
| 200 | */ |
||
| 201 | protected function applyFix(\SplFileInfo $file, Tokens $tokens): void |
||
| 202 | { |
||
| 203 | $tokensAnalyzer = new TokensAnalyzer($tokens); |
||
| 204 | $namespacesImports = $tokensAnalyzer->getImportUseIndexes(true); |
||
| 205 | |||
| 206 | if (0 === \count($namespacesImports)) { |
||
| 207 | return; |
||
| 208 | } |
||
| 209 | |||
| 210 | $usesOrder = []; |
||
| 211 | foreach ($namespacesImports as $uses) { |
||
| 212 | $usesOrder[] = $this->getNewOrder(array_reverse($uses), $tokens); |
||
| 213 | } |
||
| 214 | $usesOrder = array_replace(...$usesOrder); |
||
| 215 | |||
| 216 | $usesOrder = array_reverse($usesOrder, true); |
||
| 217 | $mapStartToEnd = []; |
||
| 218 | |||
| 219 | foreach ($usesOrder as $use) { |
||
| 220 | $mapStartToEnd[$use['startIndex']] = $use['endIndex']; |
||
| 221 | } |
||
| 222 | |||
| 223 | // Now insert the new tokens, starting from the end |
||
| 224 | foreach ($usesOrder as $index => $use) { |
||
| 225 | $declarationTokens = Tokens::fromCode( |
||
| 226 | sprintf( |
||
| 227 | '<?php use %s%s;', |
||
| 228 | self::IMPORT_TYPE_CLASS === $use['importType'] ? '' : ' '.$use['importType'].' ', |
||
| 229 | $use['namespace'] |
||
| 230 | ) |
||
| 231 | ); |
||
| 232 | |||
| 233 | $declarationTokens->clearRange(0, 2); // clear `<?php use ` |
||
| 234 | $declarationTokens->clearAt(\count($declarationTokens) - 1); // clear `;` |
||
| 235 | $declarationTokens->clearEmptyTokens(); |
||
| 236 | |||
| 237 | $tokens->overrideRange($index, $mapStartToEnd[$index], $declarationTokens); |
||
| 238 | if ($use['group']) { |
||
| 239 | // a group import must start with `use` and cannot be part of comma separated import list |
||
| 240 | $prev = $tokens->getPrevMeaningfulToken($index); |
||
| 241 | if ($tokens[$prev]->equals(',')) { |
||
| 242 | $tokens[$prev] = new Token(';'); |
||
| 243 | $tokens->insertAt($prev + 1, new Token([T_USE, 'use'])); |
||
| 244 | |||
| 245 | if (!$tokens[$prev + 2]->isWhitespace()) { |
||
| 246 | $tokens->insertAt($prev + 2, new Token([T_WHITESPACE, ' '])); |
||
| 247 | } |
||
| 248 | } |
||
| 249 | } |
||
| 250 | } |
||
| 251 | } |
||
| 252 | |||
| 253 | /** |
||
| 254 | * {@inheritdoc} |
||
| 255 | */ |
||
| 256 | protected function createConfigurationDefinition(): FixerConfigurationResolverInterface |
||
| 257 | { |
||
| 258 | $supportedSortTypes = self::SUPPORTED_SORT_TYPES; |
||
| 259 | |||
| 260 | return new FixerConfigurationResolver([ |
||
| 261 | (new FixerOptionBuilder('sort_algorithm', 'whether the statements should be sorted alphabetically or by length, or not sorted')) |
||
| 262 | ->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS) |
||
| 263 | ->setDefault(self::SORT_ALPHA) |
||
| 264 | ->getOption(), |
||
| 265 | (new FixerOptionBuilder('imports_order', 'Defines the order of import types.')) |
||
| 266 | ->setAllowedTypes(['array', 'null']) |
||
| 267 | ->setAllowedValues([static function (?array $value) use ($supportedSortTypes) { |
||
| 268 | if (null !== $value) { |
||
|
|
|||
| 269 | $missing = array_diff($supportedSortTypes, $value); |
||
| 270 | if (\count($missing)) { |
||
| 271 | throw new InvalidOptionsException(sprintf( |
||
| 272 | 'Missing sort %s "%s".', |
||
| 273 | 1 === \count($missing) ? 'type' : 'types', |
||
| 274 | implode('", "', $missing) |
||
| 275 | )); |
||
| 276 | } |
||
| 277 | |||
| 278 | $unknown = array_diff($value, $supportedSortTypes); |
||
| 279 | if (\count($unknown)) { |
||
| 280 | throw new InvalidOptionsException(sprintf( |
||
| 281 | 'Unknown sort %s "%s".', |
||
| 282 | 1 === \count($unknown) ? 'type' : 'types', |
||
| 283 | implode('", "', $unknown) |
||
| 284 | )); |
||
| 285 | } |
||
| 286 | } |
||
| 287 | |||
| 288 | return true; |
||
| 289 | }]) |
||
| 290 | ->setDefault(null) |
||
| 291 | ->getOption(), |
||
| 292 | ]); |
||
| 293 | } |
||
| 294 | |||
| 295 | /** |
||
| 296 | * This method is used for sorting the uses in a namespace. |
||
| 297 | * |
||
| 298 | * @param array<string, bool|int|string> $first |
||
| 299 | * @param array<string, bool|int|string> $second |
||
| 300 | * |
||
| 301 | * @internal |
||
| 302 | */ |
||
| 303 | private function sortAlphabetically(array $first, array $second): int |
||
| 304 | { |
||
| 305 | // Replace backslashes by spaces before sorting for correct sort order |
||
| 306 | $firstNamespace = str_replace('\\', ' ', $this->prepareNamespace($first['namespace'])); |
||
| 307 | $secondNamespace = str_replace('\\', ' ', $this->prepareNamespace($second['namespace'])); |
||
| 308 | |||
| 309 | return strcasecmp($firstNamespace, $secondNamespace); |
||
| 310 | } |
||
| 311 | |||
| 312 | /** |
||
| 313 | * This method is used for sorting the uses statements in a namespace by length. |
||
| 314 | * |
||
| 315 | * @param array<string, bool|int|string> $first |
||
| 316 | * @param array<string, bool|int|string> $second |
||
| 317 | * |
||
| 318 | * @internal |
||
| 319 | */ |
||
| 320 | private function sortByLength(array $first, array $second): int |
||
| 321 | { |
||
| 322 | $firstNamespace = (self::IMPORT_TYPE_CLASS === $first['importType'] ? '' : $first['importType'].' ').$this->prepareNamespace($first['namespace']); |
||
| 323 | $secondNamespace = (self::IMPORT_TYPE_CLASS === $second['importType'] ? '' : $second['importType'].' ').$this->prepareNamespace($second['namespace']); |
||
| 324 | |||
| 325 | $firstNamespaceLength = \strlen($firstNamespace); |
||
| 326 | $secondNamespaceLength = \strlen($secondNamespace); |
||
| 327 | |||
| 328 | if ($firstNamespaceLength === $secondNamespaceLength) { |
||
| 329 | $sortResult = strcasecmp($firstNamespace, $secondNamespace); |
||
| 330 | } else { |
||
| 331 | $sortResult = $firstNamespaceLength > $secondNamespaceLength ? 1 : -1; |
||
| 332 | } |
||
| 333 | |||
| 334 | return $sortResult; |
||
| 335 | } |
||
| 336 | |||
| 337 | private function prepareNamespace(string $namespace): string |
||
| 338 | { |
||
| 339 | return trim(Preg::replace('%/\*(.*)\*/%s', '', $namespace)); |
||
| 340 | } |
||
| 341 | |||
| 342 | /** |
||
| 343 | * @param int[] $uses |
||
| 344 | */ |
||
| 345 | private function getNewOrder(array $uses, Tokens $tokens): array |
||
| 521 | } |
||
| 522 | |||
| 523 | /** |
||
| 524 | * @param array[] $indexes |
||
| 525 | */ |
||
| 526 | private function sortByAlgorithm(array $indexes): array |
||
| 535 | } |
||
| 536 | } |
||
| 537 |