Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,11 @@ parameters:
- '#expects array<PhpParser\\Node\\Stmt>, array<PhpParser\\Node> given#'
- '#should return non\-empty\-string but returns string#'

# known non-empty class method
-
message: '#Offset 0 might not exist on array<PhpParser\\Node\\Stmt>\|null#'
path: rules/DeadCode/Rector/ClassMethod/RemoveParentDelegatingConstructorRector.php

# false positive, can accept non-class string
- '#Parameter \#1 \$name of method PHPStan\\BetterReflection\\Reflection\\Adapter\\ReflectionClass\:\:getAttributes\(\) expects class\-string\|null, string given#'

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

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector\Fixture;

use PhpParser\Node\Scalar\String_;

final class SomeDifferentArgs extends String_
{
public function __construct($value, $attributes)
{
parent::__construct($value, []);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector\Fixture;

use PhpParser\Node\Scalar\String_;

final class SkipDifferentCount extends String_
{
public function __construct($value)
{
parent::__construct($value, []);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector\Fixture;

use PhpParser\NodeTraverser;
use Rector\Comments\NodeVisitor\CommentRemovingNodeVisitor;

final class SkipDifferentType extends NodeTraverser
{
public function __construct(CommentRemovingNodeVisitor $commentRemovingNodeVisitor)
{
parent::__construct($commentRemovingNodeVisitor);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector\Fixture;

use PhpParser\Node\Scalar\String_;

final class SkipFirstClassCallable extends String_
{
public function __construct($value, $attributes)
{
parent::__construct(...);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector\Fixture;

use PhpParser\Node\Scalar\String_;

final class SomeClass extends String_
{
public function __construct($value, $attributes)
{
parent::__construct($value, $attributes);
}
}

?>
-----
<?php

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector\Fixture;

use PhpParser\Node\Scalar\String_;

final class SomeClass extends String_
{
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class RemoveParentDelegatingConstructorRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector;

return RectorConfig::configure()
->withRules([RemoveParentDelegatingConstructorRector::class]);
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
<?php

declare(strict_types=1);

namespace Rector\DeadCode\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\NodeVisitor;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ExtendedMethodReflection;
use Rector\Enum\ObjectReference;
use Rector\PHPStan\ScopeFetcher;
use Rector\PHPStanStaticTypeMapper\Enum\TypeKind;
use Rector\Rector\AbstractRector;
use Rector\StaticTypeMapper\StaticTypeMapper;
use Rector\ValueObject\MethodName;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector\RemoveParentDelegatingConstructorRectorTest
*/
final class RemoveParentDelegatingConstructorRector extends AbstractRector
{
public function __construct(
private readonly StaticTypeMapper $staticTypeMapper,
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Remove constructor that only delegates call to parent class with same values',
[
new CodeSample(
<<<'CODE_SAMPLE'
class Node
{
public function __construct(array $attributes)
{
}
}

class SomeParent extends Node
{
public function __construct(array $attributes)
{
parent::__construct($attributes);
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class Node
{
public function __construct(array $attributes)
{
}
}

class SomeParent extends Node
{
}
CODE_SAMPLE
),
]
);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}

/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?int
{
if (! $this->isName($node, MethodName::CONSTRUCT)) {
return null;
}

if ($node->stmts === null || count($node->stmts) !== 1) {
return null;
}

$parentMethodReflection = $this->matchParentConstructorReflection($node);
if (! $parentMethodReflection instanceof ExtendedMethodReflection) {
return null;
}

$soleStmt = $node->stmts[0];
$parentCallArgs = $this->matchParentConstructorCallArgs($soleStmt);
if ($parentCallArgs === null) {
return null;
}

// match count and order
if (! $this->isParameterAndArgCountAndOrderIdentical($node)) {
return null;
}

// match parameter types and parent constructor types
if (! $this->areConstructorAndParentParameterTypesMatching($node, $parentMethodReflection)) {
return null;
}

return NodeVisitor::REMOVE_NODE;
}

private function matchParentConstructorReflection(ClassMethod $classMethod): ?ExtendedMethodReflection
{
$scope = ScopeFetcher::fetch($classMethod);

$classReflection = $scope->getClassReflection();
if (! $classReflection instanceof ClassReflection) {
return null;
}

$parentClassReflection = $classReflection->getParentClass();
if (! $parentClassReflection instanceof ClassReflection) {
return null;
}

if (! $parentClassReflection->hasConstructor()) {
return null;
}

return $parentClassReflection->getConstructor();
}

/**
* Looking for parent::__construct()
*
* @return Arg[]|null
*/
private function matchParentConstructorCallArgs(Stmt $stmt): ?array
{
if (! $stmt instanceof Expression) {
return null;
}

if (! $stmt->expr instanceof StaticCall) {
return null;
}

$staticCall = $stmt->expr;
if ($staticCall->isFirstClassCallable()) {
return null;
}

if (! $this->isName($staticCall->class, ObjectReference::PARENT)) {
return null;
}

if (! $this->isName($staticCall->name, MethodName::CONSTRUCT)) {
return null;
}

return $staticCall->getArgs();
}

private function isParameterAndArgCountAndOrderIdentical(ClassMethod $classMethod): bool
{
$soleStmt = $classMethod->stmts[0];

$parentCallArgs = $this->matchParentConstructorCallArgs($soleStmt);
if ($parentCallArgs === null) {
return false;
}

$constructorParams = $classMethod->getParams();
if (count($constructorParams) !== count($parentCallArgs)) {
return false;
}

// match passed names in the same order
$paramNames = [];
foreach ($constructorParams as $constructorParam) {
$paramNames[] = $this->getName($constructorParam->var);
}

$argNames = [];
foreach ($parentCallArgs as $parentCallArg) {
$argValue = $parentCallArg->value;
if (! $argValue instanceof Variable) {
return false;
}

$argNames[] = $this->getName($argValue);
}

return $paramNames === $argNames;
}

private function areConstructorAndParentParameterTypesMatching(
ClassMethod $classMethod,
ExtendedMethodReflection $extendedMethodReflection
): bool {
foreach ($classMethod->getParams() as $position => $param) {
$parameterType = $param->type;

// no type override
if ($parameterType === null) {
continue;
}

$parametersSelector = $extendedMethodReflection->getOnlyVariant();

foreach ($parametersSelector->getParameters() as $index => $parameterReflection) {
if ($index !== $position) {
continue;
}

$parentParameterType = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode(
$parameterReflection->getType(),
TypeKind::PARAM
);

if (! $this->nodeComparator->areNodesEqual($parameterType, $parentParameterType)) {
return false;
}
}
}

return true;
}
}
4 changes: 4 additions & 0 deletions src/Config/Level/DeadCodeLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Rector\DeadCode\Rector\ClassMethod\RemoveArgumentFromDefaultParentCallRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveNullTagValueNodeRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveParentDelegatingConstructorRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedConstructorParamRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodParameterRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPrivateMethodRector;
Expand Down Expand Up @@ -132,7 +133,10 @@ final class DeadCodeLevel
RemoveConditionExactReturnRector::class,
RemoveDeadStmtRector::class,
UnwrapFutureCompatibleIfPhpVersionRector::class,

RemoveParentCallWithoutParentRector::class,
RemoveParentDelegatingConstructorRector::class,

RemoveDeadConditionAboveReturnRector::class,
RemoveDeadLoopRector::class,

Expand Down
Loading