From 1f7fb8a061061aae53e1ccdce0498e5e586baf28 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Sun, 17 Sep 2023 06:03:16 +0200 Subject: [PATCH] CodeAnalysis/ConstructorDestructorReturn: correctly ignore PHP-4-style constructors in namespaced classes Methods with the same name as a class are not recognized as PHP4-style constructors in namespaced classes. This was so far not taken into account in this sniff, leading to false positives. A better solution, with a lower performance impact is expected at a later point in time (namespace tracker), however, as my time is limited, it may still be a while before that solution is available. In the mean time, let's just fix it. Includes test. --- .../ConstructorDestructorReturnSniff.php | 12 ++++++++++++ .../ConstructorDestructorReturnUnitTest.5.inc | 14 ++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 Universal/Tests/CodeAnalysis/ConstructorDestructorReturnUnitTest.5.inc diff --git a/Universal/Sniffs/CodeAnalysis/ConstructorDestructorReturnSniff.php b/Universal/Sniffs/CodeAnalysis/ConstructorDestructorReturnSniff.php index 4c57788..6f78cb6 100644 --- a/Universal/Sniffs/CodeAnalysis/ConstructorDestructorReturnSniff.php +++ b/Universal/Sniffs/CodeAnalysis/ConstructorDestructorReturnSniff.php @@ -18,6 +18,7 @@ use PHPCSUtils\Tokens\Collections; use PHPCSUtils\Utils\FunctionDeclarations; use PHPCSUtils\Utils\GetTokensAsString; +use PHPCSUtils\Utils\Namespaces; use PHPCSUtils\Utils\NamingConventions; use PHPCSUtils\Utils\ObjectDeclarations; use PHPCSUtils\Utils\Scopes; @@ -105,6 +106,17 @@ public function process(File $phpcsFile, $stackPtr) return; } + if (Namespaces::determineNamespace($phpcsFile, $stackPtr) !== '') { + /* + * Namespaced methods with the same name as the class are treated as + * regular methods, so we can bow out if we're in a namespace. + * + * Note: the exception to this is PHP 5.3.0-5.3.2. This is currently + * not dealt with. + */ + return; + } + $functionType = 'A PHP 4-style constructor'; } diff --git a/Universal/Tests/CodeAnalysis/ConstructorDestructorReturnUnitTest.5.inc b/Universal/Tests/CodeAnalysis/ConstructorDestructorReturnUnitTest.5.inc new file mode 100644 index 0000000..92c29fc --- /dev/null +++ b/Universal/Tests/CodeAnalysis/ConstructorDestructorReturnUnitTest.5.inc @@ -0,0 +1,14 @@ +