rector/rules/Php72/Rector/Unset_/UnsetCastRector.php

76 lines
2.1 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
namespace Rector\Php72\Rector\Unset_;
2018-10-17 03:21:02 +00:00
use PhpParser\Node;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Cast\Unset_;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Stmt\Expression;
use PhpParser\NodeTraverser;
use Rector\Rector\AbstractRector;
use Rector\ValueObject\PhpVersionFeature;
use Rector\VersionBonding\Contract\MinPhpVersionInterface;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\Php72\Rector\Unset_\UnsetCastRector\UnsetCastRectorTest
2019-09-03 09:11:45 +00:00
*/
final class UnsetCastRector extends AbstractRector implements MinPhpVersionInterface
2018-10-17 03:21:02 +00:00
{
public function provideMinPhpVersion() : int
{
return PhpVersionFeature::NO_UNSET_CAST;
}
public function getRuleDefinition() : RuleDefinition
2018-10-17 03:21:02 +00:00
{
return new RuleDefinition('Removes (unset) cast', [new CodeSample(<<<'CODE_SAMPLE'
2019-09-25 23:38:52 +00:00
$different = (unset) $value;
2018-10-17 03:21:02 +00:00
$value = (unset) $value;
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2019-09-25 23:38:52 +00:00
$different = null;
unset($value);
CODE_SAMPLE
)]);
2018-10-17 03:21:02 +00:00
}
/**
* @return array<class-string<Node>>
2018-10-17 03:21:02 +00:00
*/
public function getNodeTypes() : array
2018-10-17 03:21:02 +00:00
{
return [Unset_::class, Assign::class, Expression::class];
2018-10-17 03:21:02 +00:00
}
/**
* @param Unset_|Assign|Expression $node
* @return int|null|\PhpParser\Node
2018-10-17 03:21:02 +00:00
*/
public function refactor(Node $node)
2018-10-17 03:21:02 +00:00
{
if ($node instanceof Assign) {
return $this->refactorAssign($node);
2019-09-25 23:38:52 +00:00
}
if ($node instanceof Expression) {
if (!$node->expr instanceof Unset_) {
return null;
}
return NodeTraverser::REMOVE_NODE;
2019-09-25 23:38:52 +00:00
}
2021-01-30 21:41:25 +00:00
return $this->nodeFactory->createNull();
2018-10-17 03:21:02 +00:00
}
private function refactorAssign(Assign $assign) : ?FuncCall
{
if (!$assign->expr instanceof Unset_) {
return null;
}
$unset = $assign->expr;
if (!$this->nodeComparator->areNodesEqual($assign->var, $unset->expr)) {
return null;
}
return $this->nodeFactory->createFuncCall('unset', [$assign->var]);
}
2018-10-17 03:21:02 +00:00
}