|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\Utils\Rector; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\PropertyFetch; |
| 9 | +use PhpParser\Node\Stmt\Class_; |
| 10 | +use PhpParser\Node\Stmt\If_; |
| 11 | +use PhpParser\Node\Stmt\Property; |
| 12 | +use PHPStan\Type\ObjectType; |
| 13 | +use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory; |
| 14 | +use Rector\NodeManipulator\ClassDependencyManipulator; |
| 15 | +use Rector\PhpParser\Node\BetterNodeFinder; |
| 16 | +use Rector\PhpParser\Node\Value\ValueResolver; |
| 17 | +use Rector\PostRector\ValueObject\PropertyMetadata; |
| 18 | +use Rector\Rector\AbstractRector; |
| 19 | +use Rector\StaticTypeMapper\StaticTypeMapper; |
| 20 | +use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; |
| 21 | + |
| 22 | +final class RemoveRefactorDuplicatedNodeInstanceCheckRector extends AbstractRector |
| 23 | +{ |
| 24 | + public function getRuleDefinition(): RuleDefinition |
| 25 | + { |
| 26 | + return new RuleDefinition('Remove refactor() method of Rector rule double check of $node instance, if already defined in @param type', []); |
| 27 | + } |
| 28 | + |
| 29 | + public function getNodeTypes(): array |
| 30 | + { |
| 31 | + return [Node\Stmt\ClassMethod::class]; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @param Node\Stmt\ClassMethod $node |
| 36 | + */ |
| 37 | + public function refactor(Node $node): ?Node |
| 38 | + { |
| 39 | + if (! $this->isName($node->name, 'refactor')) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + if (! $node->isPublic()) { |
| 44 | + return null; |
| 45 | + } |
| 46 | + |
| 47 | + $firstStmt = $node->stmts[0] ?? null; |
| 48 | + if (! $firstStmt instanceof If_) { |
| 49 | + return null; |
| 50 | + } |
| 51 | + |
| 52 | + // remove already added properties |
| 53 | + |
| 54 | + if ($typesToAdd === []) { |
| 55 | + return null; |
| 56 | + } |
| 57 | + |
| 58 | + $hasChanged = false; |
| 59 | + |
| 60 | + foreach ($typesToAdd as $propertyNameToAdd => $propertyTypeToAdd) { |
| 61 | + // skip if property already exists |
| 62 | + if ($node->getProperty($propertyNameToAdd) instanceof Property) { |
| 63 | + continue; |
| 64 | + } |
| 65 | + |
| 66 | + $this->classDependencyManipulator->addConstructorDependency( |
| 67 | + $node, |
| 68 | + new PropertyMetadata($propertyNameToAdd, new ObjectType($propertyTypeToAdd)) |
| 69 | + ); |
| 70 | + |
| 71 | + $hasChanged = true; |
| 72 | + } |
| 73 | + |
| 74 | + if (! $hasChanged) { |
| 75 | + return null; |
| 76 | + } |
| 77 | + |
| 78 | + return $node; |
| 79 | + } |
| 80 | +} |
0 commit comments