Skip to content

Commit

Permalink
RemoveNonExistingVarAnnotationRector: Allow return annotations (#3534)
Browse files Browse the repository at this point in the history
  • Loading branch information
jlherren committed Mar 28, 2023
1 parent b3ea98f commit 8ff7747
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Rector\Tests\DeadCode\Rector\Node\RemoveNonExistingVarAnnotationRector\Fixture;

class ReturnAnnotationInvalid
{
public function getValue()
{
/** @var int */
return;
}
}

?>
-----
<?php

namespace Rector\Tests\DeadCode\Rector\Node\RemoveNonExistingVarAnnotationRector\Fixture;

class ReturnAnnotationInvalid
{
public function getValue()
{
return;
}
}

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

namespace Rector\Tests\DeadCode\Rector\Node\RemoveNonExistingVarAnnotationRector\Fixture;

class ReturnAnnotationUnwanted
{
public function getValue()
{
/** @var array<string, string> */
return new stdClass;
}
}

?>
-----
<?php

namespace Rector\Tests\DeadCode\Rector\Node\RemoveNonExistingVarAnnotationRector\Fixture;

class ReturnAnnotationUnwanted
{
public function getValue()
{
return new stdClass;
}
}

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

namespace Rector\Tests\DeadCode\Rector\Node\RemoveNonExistingVarAnnotationRector\Fixture;

class SkipDirectReturnFuncCall
{
public function getValue(): int|false|null
{
/** @var int|false|null */
return filter_input(INPUT_GET, 'value', FILTER_VALIDATE_INT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignRef;
use PhpParser\Node\Expr\CallLike;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\Echo_;
use PhpParser\Node\Stmt\Expression;
Expand Down Expand Up @@ -114,6 +116,11 @@ public function refactor(Node $node): ?Node
}

$variableName = ltrim($varTagValueNode->variableName, '$');

if ($variableName === '' && $this->isAnnotatableReturn($node)) {
return null;
}

if ($this->hasVariableName($node, $variableName)) {
return null;
}
Expand Down Expand Up @@ -197,4 +204,11 @@ private function isObjectShapePseudoType(VarTagValueNode $varTagValueNode): bool

return str_contains($varTagValueNode->description, '}');
}

private function isAnnotatableReturn(Node $node): bool
{
return $node instanceof Return_
&& $node->expr instanceof CallLike
&& ! $node->expr instanceof New_;
}
}

0 comments on commit 8ff7747

Please sign in to comment.