Merge pull request #3662 from rectorphp/skip-null-on-costructor-assigned

[PHP 7.4] Make RestoreDefaultNullToNullableTypePropertyRector skip nullable defined in ctor
This commit is contained in:
Tomas Votruba 2020-07-06 21:59:45 +02:00 committed by GitHub
commit bd170a668c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 63 additions and 4 deletions

View File

@ -60,6 +60,4 @@ jobs:
- run: composer install --no-progress
-
name: ${{ matrix.actions.name }}
run: ${{ matrix.actions.run }}
- run: ${{ matrix.actions.run }}

View File

@ -5,12 +5,17 @@ declare(strict_types=1);
namespace Rector\Php74\Rector\Property;
use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\NullableType;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
use PhpParser\NodeTraverser;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample;
use Rector\Core\RectorDefinition\RectorDefinition;
use Rector\Core\ValueObject\PhpVersionFeature;
use Rector\NodeTypeResolver\Node\AttributeKey;
/**
* @see \Rector\Php74\Tests\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector\RestoreDefaultNullToNullableTypePropertyRectorTest
@ -77,7 +82,50 @@ PHP
}
$onlyProperty = $property->props[0];
if ($onlyProperty->default !== null) {
return true;
}
return $onlyProperty->default !== null;
// is variable assigned in constructor
$propertyName = $this->getName($property);
if ($this->isPropertyInitiatedInConstuctor($property, $propertyName)) {
return true;
}
return false;
}
private function isPropertyInitiatedInConstuctor(Property $property, string $propertyName): bool
{
$class = $property->getAttribute(AttributeKey::CLASS_NODE);
if (! $class instanceof Class_) {
return false;
}
$constructClassMethod = $class->getMethod('__construct');
if (! $constructClassMethod instanceof ClassMethod) {
return false;
}
$isPropertyInitiated = false;
$this->traverseNodesWithCallable((array) $constructClassMethod->stmts, function (Node $node) use (
$propertyName,
&$isPropertyInitiated
) {
if (! $node instanceof Assign) {
return null;
}
if (! $this->isLocalPropertyFetchNamed($node->var, $propertyName)) {
return null;
}
$isPropertyInitiated = true;
return NodeTraverser::STOP_TRAVERSAL;
});
return $isPropertyInitiated;
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Rector\Php74\Tests\Rector\Property\RestoreDefaultNullToNullableTypePropertyRector\Fixture;
class SkipAssignedInConstructor
{
public ?string $name;
public function __construct(?string $name = null)
{
$this->name = $name;
}
}