Skip to content

Commit

Permalink
CodeAnalysis/ConstructorDestructorReturn: correctly ignore PHP-4-styl…
Browse files Browse the repository at this point in the history
…e 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.
  • Loading branch information
jrfnl committed Sep 17, 2023
1 parent f8b1620 commit 1f7fb8a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Universal/Sniffs/CodeAnalysis/ConstructorDestructorReturnSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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';
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

/*
* The PHP4-style constructors are not constructors in namespaced files.
* No errors should be thrown for it, nor any auto-fixes made.
*/
namespace Some\Name;

class ReturnsAValue {
function returnsAValue(): string
{
return 'php4style';
}
}

0 comments on commit 1f7fb8a

Please sign in to comment.