rector/rules/code-quality/src/Rector/Identical/StrlenZeroToIdenticalEmptyStringRector.php

92 lines
2.2 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\Identical;
use PhpParser\Node;
2019-07-05 15:06:28 +00:00
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\FuncCall;
2019-07-05 15:06:28 +00:00
use PhpParser\Node\Scalar\String_;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\CodeQuality\Tests\Rector\Identical\StrlenZeroToIdenticalEmptyStringRector\StrlenZeroToIdenticalEmptyStringRectorTest
2019-09-03 09:11:45 +00:00
*/
final class StrlenZeroToIdenticalEmptyStringRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Changes strlen comparison to 0 to direct empty string compare',
[
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function run($value)
{
$empty = strlen($value) === 0;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function run($value)
{
$empty = $value === '';
}
}
CODE_SAMPLE
2021-03-03 08:49:57 +00:00
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Identical::class];
}
/**
* @param Identical $node
*/
public function refactor(Node $node): ?Node
{
$variable = null;
if ($node->left instanceof FuncCall) {
if (! $this->isName($node->left, 'strlen')) {
return null;
}
2021-01-30 23:20:05 +00:00
if (! $this->valueResolver->isValue($node->right, 0)) {
return null;
}
$variable = $node->left->args[0]->value;
} elseif ($node->right instanceof FuncCall) {
if (! $this->isName($node->right, 'strlen')) {
return null;
}
2021-01-30 23:20:05 +00:00
if (! $this->valueResolver->isValue($node->left, 0)) {
return null;
}
$variable = $node->right->args[0]->value;
} else {
return null;
}
2019-07-05 15:06:28 +00:00
/** @var Expr $variable */
return new Identical($variable, new String_(''));
}
}