rector/rules/CodeQuality/Rector/NotEqual/CommonNotEqualRector.php

75 lines
2.0 KiB
PHP
Raw Permalink Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
namespace Rector\CodeQuality\Rector\NotEqual;
2019-02-19 17:26:22 +00:00
use PhpParser\Node;
use PhpParser\Node\Expr\BinaryOp\NotEqual;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2019-02-19 17:26:22 +00:00
/**
2021-04-10 18:47:17 +00:00
* @changelog https://stackoverflow.com/a/4294663/1348344
* @see \Rector\Tests\CodeQuality\Rector\NotEqual\CommonNotEqualRector\CommonNotEqualRectorTest
2019-02-19 17:26:22 +00:00
*/
final class CommonNotEqualRector extends AbstractRector
2019-02-19 17:26:22 +00:00
{
public function getRuleDefinition() : RuleDefinition
2019-02-19 17:26:22 +00:00
{
return new RuleDefinition('Use common != instead of less known <> with same meaning', [new CodeSample(<<<'CODE_SAMPLE'
2019-02-19 17:26:22 +00:00
final class SomeClass
{
public function run($one, $two)
{
return $one <> $two;
}
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2019-02-19 17:26:22 +00:00
final class SomeClass
{
public function run($one, $two)
{
return $one != $two;
}
}
CODE_SAMPLE
)]);
2019-02-19 17:26:22 +00:00
}
/**
* @return array<class-string<Node>>
2019-02-19 17:26:22 +00:00
*/
public function getNodeTypes() : array
2019-02-19 17:26:22 +00:00
{
return [NotEqual::class];
2019-02-19 17:26:22 +00:00
}
/**
* @param NotEqual $node
2019-02-19 17:26:22 +00:00
*/
public function refactor(Node $node) : ?NotEqual
2019-02-19 17:26:22 +00:00
{
if (!$this->doesNotEqualContainsShipCompareToken($node)) {
return null;
}
2019-02-19 17:26:22 +00:00
// invoke override to default "!="
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
2019-02-19 17:26:22 +00:00
return $node;
}
private function doesNotEqualContainsShipCompareToken(NotEqual $notEqual) : bool
{
$tokenStartPos = $notEqual->getStartTokenPos();
$tokenEndPos = $notEqual->getEndTokenPos();
for ($i = $tokenStartPos; $i < $tokenEndPos; ++$i) {
$token = $this->file->getOldTokens()[$i];
if (!isset($token[1])) {
continue;
}
if ($token[1] === '<>') {
return \true;
}
}
return \false;
}
2019-02-19 17:26:22 +00:00
}