rector/rules/CodeQuality/Rector/Identical/SimplifyArraySearchRector.php

90 lines
2.6 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;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
use PhpParser\Node\Expr\BooleanNot;
use PhpParser\Node\Expr\FuncCall;
use Rector\Core\NodeManipulator\BinaryOpManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\Php71\ValueObject\TwoNodeMatch;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\CodeQuality\Rector\Identical\SimplifyArraySearchRector\SimplifyArraySearchRectorTest
2019-09-03 09:11:45 +00:00
*/
final class SimplifyArraySearchRector extends AbstractRector
{
2018-11-07 17:04:38 +00:00
/**
* @var BinaryOpManipulator
2018-11-07 17:04:38 +00:00
*/
private $binaryOpManipulator;
2018-11-07 17:04:38 +00:00
public function __construct(BinaryOpManipulator $binaryOpManipulator)
2018-11-07 17:04:38 +00:00
{
$this->binaryOpManipulator = $binaryOpManipulator;
2018-11-07 17:04:38 +00:00
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Simplify array_search to in_array',
[
new CodeSample('array_search("searching", $array) !== false;', 'in_array("searching", $array);'),
new CodeSample(
'array_search("searching", $array, true) !== false;',
'in_array("searching", $array, true);'
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Identical::class, NotIdentical::class];
}
/**
* @param Identical|NotIdentical $node
*/
public function refactor(Node $node): ?Node
{
$twoNodeMatch = $this->binaryOpManipulator->matchFirstAndSecondConditionNode(
2018-11-07 17:04:38 +00:00
$node,
function (Node $node): bool {
if (! $node instanceof FuncCall) {
return false;
}
return $this->nodeNameResolver->isName($node, 'array_search');
2018-11-07 17:04:38 +00:00
},
function (Node $node): bool {
2021-01-30 23:20:05 +00:00
return $this->valueResolver->isFalse($node);
2018-11-07 17:04:38 +00:00
}
);
if (! $twoNodeMatch instanceof TwoNodeMatch) {
return null;
}
2019-02-22 17:25:31 +00:00
/** @var FuncCall $arraySearchFuncCall */
$arraySearchFuncCall = $twoNodeMatch->getFirstExpr();
2021-01-30 21:41:25 +00:00
$inArrayFuncCall = $this->nodeFactory->createFuncCall('in_array', $arraySearchFuncCall->args);
if ($node instanceof Identical) {
return new BooleanNot($inArrayFuncCall);
}
return $inArrayFuncCall;
}
}