Skip to content

Commit cacd03a

Browse files
[DeadCode] Keep empty __construct() in anonymous class that extends parent on RemoveEmptyClassMethodRector (#8219)
Co-authored-by: GitHub Action <actions@github.com>
1 parent 7c4ef12 commit cacd03a

4 files changed

Lines changed: 54 additions & 1 deletion

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector\Fixture;
4+
5+
function createPlain()
6+
{
7+
return new class {
8+
public function __construct()
9+
{
10+
}
11+
};
12+
}
13+
14+
?>
15+
-----
16+
<?php
17+
18+
namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector\Fixture;
19+
20+
function createPlain()
21+
{
22+
return new class
23+
{
24+
};
25+
}
26+
27+
?>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?php
2+
3+
namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector\Fixture;
4+
5+
use Rector\Tests\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector\Source\ParentWithoutConstructor;
6+
7+
function createStub()
8+
{
9+
return new class extends ParentWithoutConstructor {
10+
public function __construct()
11+
{
12+
}
13+
};
14+
}
15+
16+
?>

‎rules/DeadCode/Rector/ClassMethod/RemoveEmptyClassMethodRector.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use PhpParser\Comment\Doc;
88
use PhpParser\Node;
9+
use PhpParser\Node\Name;
910
use PhpParser\Node\Stmt\Class_;
1011
use PhpParser\Node\Stmt\ClassMethod;
1112
use PHPStan\PhpDocParser\Ast\PhpDoc\DeprecatedTagValueNode;
@@ -142,6 +143,15 @@ private function shouldSkipClassMethod(Class_ $class, ClassMethod $classMethod):
142143
return true;
143144
}
144145

146+
// anonymous class extending a parent uses empty constructor on purpose,
147+
// to avoid parent constructor being invoked
148+
if ($class->isAnonymous() && $class->extends instanceof Name && $this->isName(
149+
$classMethod,
150+
MethodName::CONSTRUCT
151+
)) {
152+
return true;
153+
}
154+
145155
if ($this->classMethodManipulator->hasParentMethodOrInterfaceMethod($class, $classMethod->name->toString())) {
146156
return true;
147157
}

‎src/FileSystem/FilePathHelper.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ public function normalizePathAndSchema(string $originalPath): string
5656
$path = $originalPath;
5757
}
5858

59-
$normalizedPath = PathNormalizer::normalize((string) $path);
59+
$normalizedPath = PathNormalizer::normalize($path);
6060
$path = Strings::replace($normalizedPath, self::TWO_AND_MORE_SLASHES_REGEX, '/');
6161

6262
$pathRoot = str_starts_with($path, '/') ? $directorySeparator : '';

0 commit comments

Comments
 (0)