Skip to content

Commit 3dd91e2

Browse files
committed
Generic/DuplicateClassName: bug fix - namespace is reset on PHP open tag
As things were, the sniff listens to the `T_OPEN_TAG` token, processes the file until the first `T_CLOSE_TAG` and then waits again for a new `T_OPEN_TAG`. However, every time the sniff is called, the namespace is reset, even when still processing the same file, i.e. when the namespace is still in effect. This led to both false positives as well as false negatives. Fixed now, by always processing the complete file in one go and not returning on a `T_CLOSE_TAG`. Includes unit tests.
1 parent 9c7cffe commit 3dd91e2

File tree

4 files changed

+24
-7
lines changed

4 files changed

+24
-7
lines changed

src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -56,17 +56,10 @@ public function process(File $phpcsFile, $stackPtr)
5656
T_TRAIT,
5757
T_ENUM,
5858
T_NAMESPACE,
59-
T_CLOSE_TAG,
6059
];
6160

6261
$stackPtr = $phpcsFile->findNext($findTokens, ($stackPtr + 1));
6362
while ($stackPtr !== false) {
64-
if ($tokens[$stackPtr]['code'] === T_CLOSE_TAG) {
65-
// We can stop here. The sniff will continue from the next open
66-
// tag when PHPCS reaches that token, if there is one.
67-
return;
68-
}
69-
7063
// Keep track of what namespace we are in.
7164
if ($tokens[$stackPtr]['code'] === T_NAMESPACE) {
7265
$nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
@@ -120,6 +113,8 @@ public function process(File $phpcsFile, $stackPtr)
120113
$stackPtr = $phpcsFile->findNext($findTokens, ($stackPtr + 1));
121114
}//end while
122115

116+
return $phpcsFile->numTokens;
117+
123118
}//end process()
124119

125120

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?php
2+
namespace Code\IsNamespaced ?>
3+
4+
<?php
5+
class MyClass {}
6+
interface MyInterface {}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
namespace Code\IsNamespaced;
3+
class FooBar {}
4+
5+
namespace Code\AnotherNamespace;
6+
7+
namespace Code\IsNamespaced ?>
8+
9+
<?php
10+
echo '123';
11+
?>
12+
<?php
13+
class FooBar {}

src/Standards/Generic/Tests/Classes/DuplicateClassNameUnitTest.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,9 @@ public function getWarningList($testFile='')
8585
4 => 1,
8686
];
8787

88+
case 'DuplicateClassNameUnitTest.11.inc':
89+
return [13 => 1];
90+
8891
default:
8992
return [];
9093
}//end switch

0 commit comments

Comments
 (0)