Skip to content

Commit

Permalink
Fix conflict within PSR12.ControlStructures.ControlStructureSpacing
Browse files Browse the repository at this point in the history
For multi-line control structures, the first line of code must be on the next
line after the control structure. This sniff correctly identified such cases.
When the first line of code was on the same line as the control structure, the
sniff correctly fixed this by adding a newline between these. However, when
there were multiple blank lines between these, the fixer would continue adding
new newlines. This change fixes this bug by first removing all white-space
before adding the one expected newline. Includes test.
  • Loading branch information
fredden committed Jul 29, 2024
1 parent a3d11a9 commit e67fe56
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,15 @@ public function process(File $phpcsFile, $stackPtr)
$error = 'The first expression of a multi-line control structure must be on the line after the opening parenthesis';
$fix = $phpcsFile->addFixableError($error, $next, 'FirstExpressionLine');
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
if ($tokens[$next]['line'] > ($tokens[$parenOpener]['line'] + 1)) {
for ($i = ($parenOpener + 1); $i < $next; $i++) {
$phpcsFile->fixer->replaceToken($i, '');
}
}

$phpcsFile->fixer->addNewline($parenOpener);
$phpcsFile->fixer->endChangeset();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,24 @@ $expr2 &&
$expr3) {
// structure body
};

// Ensure the sniff handles too many newlines (not just too few). This was copied from src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.1.inc
for (


$i = 0


;


$i < 10


;


$i++


) {}
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,20 @@ match (
) {
// structure body
};

// Ensure the sniff handles too many newlines (not just too few). This was copied from src/Standards/Squiz/Tests/ControlStructures/ForLoopDeclarationUnitTest.1.inc
for (
$i = 0


;


$i < 10


;


$i++
) {}
Original file line number Diff line number Diff line change
Expand Up @@ -31,25 +31,27 @@ final class ControlStructureSpacingUnitTest extends AbstractSniffUnitTest
public function getErrorList()
{
return [
2 => 2,
16 => 1,
17 => 1,
18 => 1,
22 => 1,
23 => 1,
32 => 1,
33 => 1,
34 => 1,
37 => 1,
38 => 1,
39 => 1,
48 => 2,
58 => 1,
59 => 1,
92 => 1,
96 => 1,
97 => 1,
98 => 2,
2 => 2,
16 => 1,
17 => 1,
18 => 1,
22 => 1,
23 => 1,
32 => 1,
33 => 1,
34 => 1,
37 => 1,
38 => 1,
39 => 1,
48 => 2,
58 => 1,
59 => 1,
92 => 1,
96 => 1,
97 => 1,
98 => 2,
106 => 1,
121 => 1,
];

}//end getErrorList()
Expand Down

0 comments on commit e67fe56

Please sign in to comment.