Skip to content

Commit

Permalink
PSR2/ClassDeclaration: prevent fixer conflict with itself [2]
Browse files Browse the repository at this point in the history
While the `PSR2.Classes.ClassDeclaration` sniff did take partially/fully qualified names into account for interfaces being implemented, it did not take _namespace relative_ interface names into account.

This led to a fixer conflict within the sniff, where the sniff would first add a newline between the `namespace` keyword and the namespace separator (`InterfaceSameLine` fixer) and in a subsequent loop would remove that same new line again as it would think it was a space before a comma (`SpaceBeforeComma` fixer).

Fixed now by adding support for namespace relative interface names in the `implements` check.

Includes unit test.

Related to 152

Note: at a glance, this sniff could probably do with a more thorough review and more defensive token walking/more precise checking, but that's outside the scope of this PR.
  • Loading branch information
jrfnl committed Mar 29, 2024
1 parent 6262237 commit ce1322f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Standards/PSR2/Sniffs/Classes/ClassDeclarationSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -314,12 +314,14 @@ public function processOpen(File $phpcsFile, $stackPtr)
if ($checkingImplements === true
&& $multiLineImplements === true
&& ($tokens[($className - 1)]['code'] !== T_NS_SEPARATOR
|| $tokens[($className - 2)]['code'] !== T_STRING)
|| ($tokens[($className - 2)]['code'] !== T_STRING
&& $tokens[($className - 2)]['code'] !== T_NAMESPACE))
) {
$prev = $phpcsFile->findPrevious(
[
T_NS_SEPARATOR,
T_WHITESPACE,
T_NAMESPACE,
],
($className - 1),
$implements,
Expand Down
6 changes: 6 additions & 0 deletions src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,9 @@ readonly
interface FooBar extends namespace\BarFoo
{
}

// Safeguard against fixer conflict when there are namespace relative interface names in a multi-line implements.
class BarFoo implements
namespace\BarFoo
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,9 @@ readonly
interface FooBar extends namespace\BarFoo
{
}

// Safeguard against fixer conflict when there are namespace relative interface names in a multi-line implements.
class BarFoo implements
namespace\BarFoo
{
}

0 comments on commit ce1322f

Please sign in to comment.