|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace MLL\PhpCsFixerConfig\Fixer; |
| 4 | + |
| 5 | +use PhpCsFixer\AbstractPhpdocTypesFixer; |
| 6 | +use PhpCsFixer\FixerDefinition\CodeSample; |
| 7 | +use PhpCsFixer\FixerDefinition\FixerDefinition; |
| 8 | +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; |
| 9 | +use PhpCsFixer\Preg; |
| 10 | +use PhpCsFixer\Tokenizer\Tokens; |
| 11 | + |
| 12 | +/** |
| 13 | + * Simplifies PHPDoc definitions to array<T>, omitting explicit array-key defaults. |
| 14 | + */ |
| 15 | +final class PhpdocSimplifyArrayKeyFixer extends AbstractPhpdocTypesFixer |
| 16 | +{ |
| 17 | + public const NAME = 'MLL/phpdoc_simplify_array_key'; |
| 18 | + |
| 19 | + public function getName(): string |
| 20 | + { |
| 21 | + return self::NAME; |
| 22 | + } |
| 23 | + |
| 24 | + public function getDefinition(): FixerDefinitionInterface |
| 25 | + { |
| 26 | + return new FixerDefinition( |
| 27 | + 'PHPDoc `array<T>` should be used instead of `array<array-key, T>`.', |
| 28 | + [ |
| 29 | + new CodeSample( |
| 30 | + <<<'PHP' |
| 31 | + <?php |
| 32 | + /** |
| 33 | + * @param array<array-key, string> $x |
| 34 | + * @param array<string|int, Foo> $y |
| 35 | + * @return array<int|string, Foo> |
| 36 | + */ |
| 37 | + |
| 38 | + PHP |
| 39 | + ), |
| 40 | + ] |
| 41 | + ); |
| 42 | + } |
| 43 | + |
| 44 | + public function isCandidate(Tokens $tokens): bool |
| 45 | + { |
| 46 | + return $tokens->isTokenKindFound(T_DOC_COMMENT); |
| 47 | + } |
| 48 | + |
| 49 | + protected function normalize(string $type): string |
| 50 | + { |
| 51 | + // Match: array<array-key, T> or array<int|string, T> or array<string|int, T> |
| 52 | + // Uses [^\S\n]* (whitespace except newlines) to avoid matching multiline types, |
| 53 | + // which are not supported due to AbstractPhpdocTypesFixer requiring line count preservation. |
| 54 | + $ws = '[^\S\n]*'; // Whitespace except newlines |
| 55 | + |
| 56 | + return Preg::replace( |
| 57 | + "/\\barray<{$ws}(?:array-key|int{$ws}\\|{$ws}string|string{$ws}\\|{$ws}int){$ws},{$ws}/", |
| 58 | + 'array<', |
| 59 | + $type |
| 60 | + ); |
| 61 | + } |
| 62 | +} |
0 commit comments