2021-12-24 20:47:54 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare (strict_types=1);
|
2022-06-06 17:12:56 +00:00
|
|
|
namespace Rector\NodeCollector;
|
2021-12-24 20:47:54 +00:00
|
|
|
|
2022-06-06 17:12:56 +00:00
|
|
|
use PhpParser\Node\Expr;
|
|
|
|
use PhpParser\Node\Expr\BinaryOp;
|
2022-01-03 23:48:04 +00:00
|
|
|
/**
|
|
|
|
* @see \Rector\Tests\NodeCollector\BinaryOpConditionsCollectorTest
|
|
|
|
*/
|
2021-12-24 20:47:54 +00:00
|
|
|
final class BinaryOpConditionsCollector
|
|
|
|
{
|
|
|
|
/**
|
2022-01-01 22:41:46 +00:00
|
|
|
* Collects operands of a sequence of applications of a given left-associative binary operation.
|
|
|
|
*
|
|
|
|
* For example, for `a + b + c`, which is parsed as `(Plus (Plus a b) c)`, it will return `[a, b, c]`.
|
|
|
|
* Note that parenthesization not matching the associativity (e.g. `a + (b + c)`) will return the parenthesized
|
|
|
|
* nodes as standalone operands (`[a, b + c]`) even for associative operations.
|
|
|
|
* Similarly, for right-associative operations (e.g. `a ?? b ?? c`), the result produced by
|
|
|
|
* the implicit parenthesization (`[a, b ?? c]`) might not match the expectations.
|
|
|
|
*
|
2022-07-17 12:27:00 +00:00
|
|
|
* @api
|
2021-12-24 20:47:54 +00:00
|
|
|
* @param class-string<BinaryOp> $binaryOpClass
|
2022-01-04 09:29:33 +00:00
|
|
|
* @return array<int, Expr>
|
2021-12-24 20:47:54 +00:00
|
|
|
*/
|
2022-06-07 08:22:29 +00:00
|
|
|
public function findConditions(Expr $expr, string $binaryOpClass) : array
|
2021-12-24 20:47:54 +00:00
|
|
|
{
|
2022-01-04 13:59:13 +00:00
|
|
|
if (\get_class($expr) !== $binaryOpClass) {
|
2022-01-04 09:29:33 +00:00
|
|
|
// Different binary operators, as well as non-BinaryOp expressions
|
|
|
|
// are considered trivial case of a single operand (no operators).
|
2022-01-04 13:59:13 +00:00
|
|
|
return [$expr];
|
2022-01-02 11:32:22 +00:00
|
|
|
}
|
2021-12-24 20:47:54 +00:00
|
|
|
$conditions = [];
|
2022-01-04 13:59:13 +00:00
|
|
|
/** @var BinaryOp|Expr $expr */
|
2022-06-07 08:22:29 +00:00
|
|
|
while ($expr instanceof BinaryOp) {
|
2022-01-04 13:59:13 +00:00
|
|
|
$conditions[] = $expr->right;
|
|
|
|
$expr = $expr->left;
|
2022-06-04 17:37:29 +00:00
|
|
|
if ($binaryOpClass !== \get_class($expr)) {
|
2022-01-04 13:59:13 +00:00
|
|
|
$conditions[] = $expr;
|
2021-12-24 20:47:54 +00:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
\krsort($conditions);
|
|
|
|
return $conditions;
|
|
|
|
}
|
|
|
|
}
|