Skip to content

Commit

Permalink
[PHP 8.1] Skip abstract class in NewInInitializerRector (#1581)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Dec 27, 2021
1 parent ac90adc commit cb8fe84
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 7 deletions.
Original file line number Diff line number Diff line change
@@ -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;
}
}
47 changes: 40 additions & 7 deletions rules/Php81/Rector/ClassMethod/NewInInitializerRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
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;
Expand Down Expand Up @@ -69,19 +71,16 @@ public function getNodeTypes(): array
*/
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;
}
Expand Down Expand Up @@ -131,4 +130,38 @@ private function processPropertyPromotion(ClassMethod $classMethod, Param $param
$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;
}
}

0 comments on commit cb8fe84

Please sign in to comment.