Skip to content

Commit

Permalink
[PHP 8.1] Add NewInInitializerRector
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba committed Nov 13, 2021
1 parent 096817b commit 2efc3bd
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 4 deletions.
2 changes: 2 additions & 0 deletions config/set/php81.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Rector\Php81\Rector\Class_\MyCLabsClassToEnumRector;
use Rector\Php81\Rector\Class_\SpatieEnumClassToEnumRector;
use Rector\Php81\Rector\ClassConst\FinalizePublicClassConstantRector;
use Rector\Php81\Rector\ClassMethod\NewInInitializerRector;
use Rector\Php81\Rector\FuncCall\Php81ResourceReturnToObjectRector;
use Rector\Php81\Rector\MethodCall\MyCLabsMethodCallToEnumConstRector;
use Rector\Php81\Rector\Property\ReadOnlyPropertyRector;
Expand All @@ -20,4 +21,5 @@
$services->set(ReadOnlyPropertyRector::class);
$services->set(SpatieEnumClassToEnumRector::class);
$services->set(Php81ResourceReturnToObjectRector::class);
$services->set(NewInInitializerRector::class);
};
10 changes: 6 additions & 4 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,9 @@ parameters:
-
message: '#Array (with keys|destruct) is not allowed\. Use value object to pass data instead#'
path: rules/Php70/EregToPcreTransformer.php

# 3rd party code
-
message: '#Use explicit return value over magic &reference#'
path: rules/Php70/EregToPcreTransformer.php

# 3rd party code
-
message: '#Use value object over return of values#'
path: rules/Php70/EregToPcreTransformer.php
Expand Down Expand Up @@ -431,6 +427,12 @@ parameters:
- src/Application/FileProcessor.php
- src/PhpParser/Node/BetterNodeFinder.php

# find everything class, better then 10 different finders
-
message: '#Class cognitive complexity is \d+, keep it under 50#'
paths:
- src/PhpParser/Node/BetterNodeFinder.php

-
message: '#Parameter \#2 \$length of function str_split expects int<1, max\>, int given#'
paths:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Rector\Tests\Php81\Rector\ClassMethod\NewInInitializerRector\Fixture;

class SomeClass
{
private Logger $logger;

public function __construct(
?Logger $logger = null,
) {
$this->logger = $logger ?? new NullLogger;
}
}

?>
-----
<?php

namespace Rector\Tests\Php81\Rector\ClassMethod\NewInInitializerRector\Fixture;

class SomeClass
{
private Logger $logger;

public function __construct(Logger $logger = new NullLogger)
{
}
}

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

declare(strict_types=1);

namespace Rector\Tests\Php81\Rector\ClassMethod\NewInInitializerRector;

use Iterator;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;
use Symplify\SmartFileSystem\SmartFileInfo;

final class NewInInitializerRectorTest extends AbstractRectorTestCase
{
/**
* @dataProvider provideData()
*/
public function test(SmartFileInfo $fileInfo): void
{
$this->doTestFileInfo($fileInfo);
}

/**
* @return Iterator<SmartFileInfo>
*/
public function provideData(): Iterator
{
return $this->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,12 @@
<?php

declare(strict_types=1);

use Rector\Php81\Rector\ClassMethod\NewInInitializerRector;

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
$services = $containerConfigurator->services();
$services->set(NewInInitializerRector::class);
};
112 changes: 112 additions & 0 deletions rules/Php81/Rector/ClassMethod/NewInInitializerRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

declare(strict_types=1);

namespace Rector\Php81\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Coalesce;
use PhpParser\Node\NullableType;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\MethodName;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\Php81\Rector\ClassMethod\NewInInitializerRector\NewInInitializerRectorTest
*/
final class NewInInitializerRector extends AbstractRector implements MinPhpVersionInterface
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Replace property declaration of new state with direct new', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
private Logger $logger;
public function __construct(
?Logger $logger = null,
) {
$this->logger = $logger ?? new NullLogger;
}
}
CODE_SAMPLE

,
<<<'CODE_SAMPLE'
class SomeClass
{
public function __construct(
private Logger $logger = new NullLogger,
) {
}
}
CODE_SAMPLE
),
]);
}

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

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

if ($node->params === []) {
return null;
}

if ($node->stmts === []) {
return null;
}

foreach ($node->params as $param) {
if (! $param->type instanceof NullableType) {
continue;
}

/** @var string $paramName */
$paramName = $this->getName($param->var);

$toPropertyAssigns = $this->betterNodeFinder->findClassMethodAssignsToLocalProperty($node, $paramName);

foreach ($toPropertyAssigns as $toPropertyAssign) {
if (! $toPropertyAssign->expr instanceof Coalesce) {
continue;
}

/** @var NullableType $currentParamType */
$currentParamType = $param->type;
$param->type = $currentParamType->type;

$coalesce = $toPropertyAssign->expr;
$param->default = $coalesce->right;

$this->removeNode($toPropertyAssign);
}
}

return $node;
}

public function provideMinPhpVersion(): int
{
return PhpVersionFeature::NEW_INITIALIZERS;
}
}
22 changes: 22 additions & 0 deletions src/PhpParser/Node/BetterNodeFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,28 @@ public function findFirst(Node | array $nodes, callable $filter): ?Node
return $this->nodeFinder->findFirst($nodes, $filter);
}

/**
* @return Assign[]
*/
public function findClassMethodAssignsToLocalProperty(ClassMethod $classMethod, string $propertyName): array
{
return $this->find((array) $classMethod->stmts, function (Node $node) use ($propertyName): bool {
if (! $node instanceof Assign) {
return false;
}

if (! $node->var instanceof PropertyFetch) {
return false;
}

$propertyFetch = $node->var;
if (! $this->nodeNameResolver->isName($propertyFetch->var, 'this')) {
return false;
}
return $this->nodeNameResolver->isName($propertyFetch->name, $propertyName);
});
}

/**
* @return Assign|null
*/
Expand Down
6 changes: 6 additions & 0 deletions src/ValueObject/PhpVersionFeature.php
Original file line number Diff line number Diff line change
Expand Up @@ -530,4 +530,10 @@ final class PhpVersionFeature
* @var int
*/
public const PHP81_RESOURCE_TO_OBJECT = PhpVersion::PHP_81;

/**
* @see https://wiki.php.net/rfc/new_in_initializers
* @var int
*/
public const NEW_INITIALIZERS = PhpVersion::PHP_81;
}

0 comments on commit 2efc3bd

Please sign in to comment.