Repository navigation
Expand file tree
/
Copy pathInArrayFromRepeatedCompareFactory.php
More file actions
56 lines (46 loc) · 1.8 KB
/
Copy pathInArrayFromRepeatedCompareFactory.php
File metadata and controls
56 lines (46 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\NodeFactory;
use PhpParser\Node\Arg;
use Rector\CodeQuality\ValueObject\ComparedExprAndValueExpr;
use Rector\PhpParser\Comparing\NodeComparator;
use Rector\PhpParser\Node\NodeFactory;
final readonly class InArrayFromRepeatedCompareFactory
{
public function __construct(
private NodeComparator $nodeComparator,
private NodeFactory $nodeFactory
) {
}
/**
* Builds the "$value, [...]" args of an in_array() call from a repeated compare chain,
* once all compared expressions are confirmed equal. Returns null when the chain is too
* short or the compared expressions differ.
*
* @param ComparedExprAndValueExpr[] $comparedExprAndValueExprs
* @return Arg[]|null
*/
public function createInArrayArgs(array $comparedExprAndValueExprs): ?array
{
if (count($comparedExprAndValueExprs) < 3) {
return null;
}
$valueExprs = [];
foreach ($comparedExprAndValueExprs as $comparedExprAndValueExpr) {
$valueExprs[] = $comparedExprAndValueExpr->getValueExpr();
}
/** @var ComparedExprAndValueExpr $firstComparedExprAndValue */
$firstComparedExprAndValue = array_pop($comparedExprAndValueExprs);
// all compared expr must be equal
foreach ($comparedExprAndValueExprs as $comparedExprAndValueExpr) {
if (! $this->nodeComparator->areNodesEqual(
$firstComparedExprAndValue->getComparedExpr(),
$comparedExprAndValueExpr->getComparedExpr()
)) {
return null;
}
}
$array = $this->nodeFactory->createArray($valueExprs);
return $this->nodeFactory->createArgs([$firstComparedExprAndValue->getComparedExpr(), $array]);
}
}