Skip to content

Commit

Permalink
[Php81] Apply constructor promotion on NewInInitializerRector (#1288)
Browse files Browse the repository at this point in the history
Co-authored-by: GitHub Action <action@github.com>
  • Loading branch information
samsonasik and actions-user committed Nov 22, 2021
1 parent 62f5b15 commit f5d4f9d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ namespace Rector\Tests\Php81\Rector\ClassMethod\NewInInitializerRector\Fixture;

class SomeClass
{
private Logger $logger;

public function __construct(Logger $logger = new NullLogger)
public function __construct(private Logger $logger = new NullLogger)
{
}
}
Expand Down
24 changes: 21 additions & 3 deletions rules/Php81/Rector/ClassMethod/NewInInitializerRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\MethodName;
use Rector\Core\ValueObject\PhpVersionFeature;
Expand Down Expand Up @@ -43,10 +46,8 @@ public function __construct(
<<<'CODE_SAMPLE'
class SomeClass
{
private Logger $logger;
public function __construct(
Logger $logger = new NullLogger,
private Logger $logger = new NullLogger,
) {
}
}
Expand Down Expand Up @@ -103,6 +104,7 @@ public function refactor(Node $node): ?Node
$param->default = $coalesce->right;

$this->removeNode($toPropertyAssign);
$this->processPropertyPromotion($node, $param, $paramName);
}
}

Expand All @@ -113,4 +115,20 @@ public function provideMinPhpVersion(): int
{
return PhpVersionFeature::NEW_INITIALIZERS;
}

private function processPropertyPromotion(ClassMethod $classMethod, Param $param, string $paramName): void
{
$classLike = $this->betterNodeFinder->findParentType($classMethod, ClassLike::class);
if (! $classLike instanceof ClassLike) {
return;
}

$property = $classLike->getProperty($paramName);
if (! $property instanceof Property) {
return;
}

$param->flags = $property->flags;
$this->removeNode($property);
}
}

0 comments on commit f5d4f9d

Please sign in to comment.