Skip to content

Commit

Permalink
PSR2/ClassDeclaration: prevent fixer conflict with itself [1]
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 extended, it did not take _namespace relative_ interface name into account.

This led to a fixer conflict within the sniff, where the sniff would first add a space between the `namespace` keyword and the namespace separator (`SpaceBeforeName` fixer) and in a subsequent loop would remove that same space 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 `extends` checks.

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 c5e1807 commit 6262237
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Standards/PSR2/Sniffs/Classes/ClassDeclarationSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -397,9 +397,10 @@ public function processOpen(File $phpcsFile, $stackPtr)
}
}//end if
} else if ($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)
) {
// Not part of a longer fully qualified class name.
// Not part of a longer fully qualified or namespace relative class name.
if ($tokens[($className - 1)]['code'] === T_COMMA
|| ($tokens[($className - 1)]['code'] === T_NS_SEPARATOR
&& $tokens[($className - 2)]['code'] === T_COMMA)
Expand Down
5 changes: 5 additions & 0 deletions src/Standards/PSR2/Tests/Classes/ClassDeclarationUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,8 @@ readonly
class ReadonlyClassWithComment
{
}

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

// Safeguard against fixer conflict when there are namespace relative interface names in extends.
interface FooBar extends namespace\BarFoo
{
}

0 comments on commit 6262237

Please sign in to comment.