Skip to content

Commit

Permalink
[TypeDeclaratoin] Skip type if changed (#6261)
Browse files Browse the repository at this point in the history
  • Loading branch information
TomasVotruba authored Apr 28, 2021
1 parent ca4d1fb commit 60da899
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\Param\ParamTypeFromStrictTypedPropertyRector\Fixture;

final class ChangedAfterAssignType
{
private array $kind;

public function setAge($kind)
{
$this->kind = $kind;

if (!is_array($kind)) {
$kind = [$kind];
}
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\Param\ParamTypeFromStrictTypedPropertyRector\Fixture;

final class ChangedAfterAssignType
{
private array $kind;

public function setAge(array $kind)
{
$this->kind = $kind;

if (!is_array($kind)) {
$kind = [$kind];
}
}
}

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

namespace Rector\Tests\TypeDeclaration\Rector\Param\ParamTypeFromStrictTypedPropertyRector\Fixture;

final class SkipChangedType
{
private array $kind;

public function setAge($kind)
{
if (!is_array($kind)) {
$kind = [$kind];
}

$this->kind = $kind;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\UnionType;
use PHPStan\Analyser\Scope;
use PHPStan\Type\Type;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\PhpVersionFeature;
Expand Down Expand Up @@ -99,6 +100,11 @@ public function decorateParamWithType(FunctionLike $functionLike, Param $param):
return null;
}

$scope = $param->getAttribute(AttributeKey::SCOPE);

$paramName = $this->getName($param);
$originalParamType = $scope->getVariableType($paramName);

/** @var Assign[] $assigns */
$assigns = $this->betterNodeFinder->findInstanceOf((array) $functionLike->getStmts(), Assign::class);
foreach ($assigns as $assign) {
Expand All @@ -110,6 +116,10 @@ public function decorateParamWithType(FunctionLike $functionLike, Param $param):
continue;
}

if ($this->hasTypeChangedBeforeAssign($assign, $paramName, $originalParamType)) {
return null;
}

$singlePropertyTypeNode = $this->matchPropertySingleTypeNode($assign->var);
if (! $singlePropertyTypeNode instanceof Node) {
return null;
Expand Down Expand Up @@ -157,4 +167,14 @@ private function matchPropertySingleTypeNode(PropertyFetch $propertyFetch): ?Nod

return $typeNode;
}

private function hasTypeChangedBeforeAssign(Assign $assign, string $paramName, Type $originalType): bool
{
$scope = $assign->getAttribute(AttributeKey::SCOPE);
if (! $scope instanceof Scope) {
return false;
}
$currentParamType = $scope->getVariableType($paramName);
return ! $currentParamType->equals($originalType);
}
}

0 comments on commit 60da899

Please sign in to comment.