rector/rules/code-quality/src/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php

93 lines
2.4 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\Equal;
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\Equal;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BinaryOp\NotEqual;
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
2019-09-04 12:10:29 +00:00
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
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\Equal\UseIdenticalOverEqualWithSameTypeRector\UseIdenticalOverEqualWithSameTypeRectorTest
*/
final class UseIdenticalOverEqualWithSameTypeRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Use ===/!== over ==/!=, it values have the same type',
[
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function run(int $firstValue, int $secondValue)
{
$isSame = $firstValue == $secondValue;
$isDiffernt = $firstValue != $secondValue;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function run(int $firstValue, int $secondValue)
{
$isSame = $firstValue === $secondValue;
$isDiffernt = $firstValue !== $secondValue;
}
}
CODE_SAMPLE
2021-03-03 08:49:57 +00:00
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Equal::class, NotEqual::class];
}
/**
* @param Equal|NotEqual $node
*/
public function refactor(Node $node): ?Node
{
$leftStaticType = $this->getStaticType($node->left);
$rightStaticType = $this->getStaticType($node->right);
// objects can be different by content
if ($leftStaticType instanceof ObjectType) {
return null;
}
if ($leftStaticType instanceof MixedType) {
return null;
}
if ($rightStaticType instanceof MixedType) {
return null;
}
// different types
if (! $leftStaticType->equals($rightStaticType)) {
return null;
}
if ($node instanceof Equal) {
return new Identical($node->left, $node->right);
}
2019-03-27 16:46:25 +00:00
return new NotIdentical($node->left, $node->right);
}
}