[PHP 8.1] Skip abstract class in NewInInitializerRector (#1581)

This commit is contained in:
Tomas Votruba 2021-12-27 19:54:40 +01:00 committed by GitHub
parent ac90adcc32
commit cb8fe8474c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 54 additions and 7 deletions

View File

@ -0,0 +1,14 @@
<?php
namespace Rector\Tests\Php81\Rector\ClassMethod\NewInInitializerRector\Fixture;
abstract class SkipAbstract
{
private Logger $logger;
public function __construct(
?Logger $logger = null,
) {
$this->logger = $logger ?? new NullLogger;
}
}

View File

@ -8,8 +8,10 @@ use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\NullableType;
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\Node\Stmt\Property;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\MethodName;
@ -69,19 +71,16 @@ CODE_SAMPLE
*/
public function refactor(Node $node): ?Node
{
if (! $this->isName($node, MethodName::CONSTRUCT)) {
if (! $this->isLegalClass($node)) {
return null;
}
if ($node->params === []) {
$params = $this->matchConstructorParams($node);
if ($params === null) {
return null;
}
if ($node->stmts === []) {
return null;
}
foreach ($node->params as $param) {
foreach ($params as $param) {
if (! $param->type instanceof NullableType) {
continue;
}
@ -131,4 +130,38 @@ CODE_SAMPLE
$param->flags = $property->flags;
$this->removeNode($property);
}
private function isLegalClass(ClassMethod $classMethod): bool
{
$classLike = $this->betterNodeFinder->findParentType($classMethod, ClassLike::class);
if ($classLike instanceof Interface_) {
return false;
}
if ($classLike instanceof Class_) {
return ! $classLike->isAbstract();
}
return true;
}
/**
* @return Param[]|null
*/
private function matchConstructorParams(ClassMethod $classMethod): array|null
{
if (! $this->isName($classMethod, MethodName::CONSTRUCT)) {
return null;
}
if ($classMethod->params === []) {
return null;
}
if ($classMethod->stmts === []) {
return null;
}
return $classMethod->params;
}
}