More yoda conditions

This commit is contained in:
David Stone
2025-02-09 12:30:02 -07:00
parent d9122a410d
commit 0a4c81c105
97 changed files with 323 additions and 289 deletions

View File

@ -34,7 +34,15 @@ final class YodaConditionsRector extends AbstractRector
public function refactor(Node $node): ?Node
{
// Ensure the left operand is not a constant
if ($node->left instanceof Node\Expr\Variable && (! $node->right instanceof Node\Expr\Variable)) {
if ((
$node->left instanceof Node\Expr\Variable ||
$node->left instanceof Node\Expr\PropertyFetch ||
$node->left instanceof Node\Expr\ArrayDimFetch) && (
$node->right instanceof Scalar ||
$node->right instanceof ConstFetch ||
$node->right instanceof Node\Expr\FuncCall ||
$node->right instanceof Node\Expr\MethodCall
)) {
// Swap the left and right operands
$this->mirrorComments($node->right, $node->left);
[$node->left, $node->right] = [$node->right, $node->left];

View File

@ -2,6 +2,8 @@
namespace Rector\Tests\TypeDeclaration\Rector\YodaConditionsRector\Fixture;
const A_CONST = 'x';
$arr = array('x'=>1);
$obj = (object) $arr;
$a = 'x';
if ($a === 'x') {
$a = 'xx';
@ -21,12 +23,20 @@ if (strlen($a) === 1) {
if ($a === 0 || $a === rand()) {
return $a;
}
if ($obj->x === 1) {
echo $obj->x;
}
if ($arr['x'] === 1) {
echo $arr['x'];
}
?>
-----
<?php
namespace Rector\Tests\TypeDeclaration\Rector\YodaConditionsRector\Fixture;
const A_CONST = 'x';
$arr = array('x'=>1);
$obj = (object) $arr;
$a = 'x';
if ('x' === $a) {
$a = 'xx';
@ -46,4 +56,10 @@ if (strlen($a) === 1) {
if (0 === $a || rand() === $a) {
return $a;
}
if (1 === $obj->x) {
echo $obj->x;
}
if (1 === $arr['x']) {
echo $arr['x'];
}
?>