Skip to content

Commit

Permalink
fix: OrderedImportsFixer - handle non-grouped list of const/function …
Browse files Browse the repository at this point in the history
…imports (#7397)
  • Loading branch information
kubawerlos committed Oct 30, 2023
1 parent 3291e9a commit 10ef1b0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/Fixer/Import/OrderedImportsFixer.php
Original file line number Diff line number Diff line change
Expand Up @@ -569,8 +569,16 @@ private function setNewOrder(Tokens $tokens, array $usesOrder): void
$use['namespace']
);

$numberOfInitialTokensToClear = 3; // clear `<?php use `
if (self::IMPORT_TYPE_CLASS !== $use['importType']) {
$prevIndex = $tokens->getPrevMeaningfulToken($index);
if ($tokens[$prevIndex]->equals(',')) {
$numberOfInitialTokensToClear = 5; // clear `<?php use const ` or `<?php use function `
}
}

$declarationTokens = Tokens::fromCode($code);
$declarationTokens->clearRange(0, 2); // clear `<?php use `
$declarationTokens->clearRange(0, $numberOfInitialTokensToClear - 1);
$declarationTokens->clearAt(\count($declarationTokens) - 1); // clear `;`
$declarationTokens->clearEmptyTokens();

Expand Down
10 changes: 10 additions & 0 deletions tests/Fixer/Import/OrderedImportsFixerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1137,6 +1137,16 @@ public function doSomething($foo)
'imports_order' => [OrderedImportsFixer::IMPORT_TYPE_CLASS, OrderedImportsFixer::IMPORT_TYPE_CONST, OrderedImportsFixer::IMPORT_TYPE_FUNCTION],
],
];

yield [
'<?php use const CONST_A, CONST_B, CONST_C;',
'<?php use const CONST_C, CONST_B, CONST_A;',
];

yield [
'<?php use function Foo\A, Foo\B, Foo\C;',
'<?php use function Foo\B, Foo\C, Foo\A;',
];
}

public function testUnknownOrderTypes(): void
Expand Down

0 comments on commit 10ef1b0

Please sign in to comment.