Skip to content

Commit fb4abd2

Browse files
authored
[CodeQuality] Skip equal to identical on numeric string and boolean on UseIdenticalOverEqualWithSameTypeRector (#7410)
* [CodeQuality] Skip equal to identical on numeric string on UseIdenticalOverEqualWithSameTypeRector * fix * fix * fix * udpdate fixture * fix * fix
1 parent 5f35406 commit fb4abd2

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Rector\Tests\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector\Fixture;
4+
5+
/**
6+
* @see https://3v4l.org/9XRF6
7+
*/
8+
final class SkipIdenticalNumericStringCompareBool
9+
{
10+
public function equal()
11+
{
12+
// maybe compare to numeric string
13+
$value = rand(0, 1) ? '1' : null;
14+
15+
var_dump(true == $value);
16+
var_dump($value == true);
17+
}
18+
}

rules/CodeQuality/Rector/Equal/UseIdenticalOverEqualWithSameTypeRector.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use PhpParser\Node\Expr\BinaryOp\NotIdentical;
1313
use PHPStan\Type\BooleanType;
1414
use PHPStan\Type\MixedType;
15+
use PHPStan\Type\Type;
1516
use Rector\Rector\AbstractRector;
1617
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
1718
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
@@ -73,6 +74,10 @@ public function refactor(Node $node): ?Node
7374
$leftStaticType = $this->nodeTypeResolver->getNativeType($node->left);
7475
$rightStaticType = $this->nodeTypeResolver->getNativeType($node->right);
7576

77+
if ($this->shouldSkipCompareNumericString($leftStaticType, $rightStaticType)) {
78+
return null;
79+
}
80+
7681
// objects can be different by content
7782
if (! $leftStaticType->isObject()->no() || ! $rightStaticType->isObject()->no()) {
7883
return null;
@@ -96,6 +101,20 @@ public function refactor(Node $node): ?Node
96101
return $this->processIdenticalOrNotIdentical($node);
97102
}
98103

104+
private function shouldSkipCompareNumericString(Type $leftStaticType, Type $rightStaticType): bool
105+
{
106+
// use ! ->no() as to support both yes and maybe
107+
if ($leftStaticType instanceof BooleanType) {
108+
return ! $rightStaticType->isNumericString()->no();
109+
}
110+
111+
if ($rightStaticType instanceof BooleanType) {
112+
return ! $leftStaticType->isNumericString()->no();
113+
}
114+
115+
return false;
116+
}
117+
99118
private function processIdenticalOrNotIdentical(Equal|NotEqual $node): Identical|NotIdentical
100119
{
101120
if ($node instanceof Equal) {

0 commit comments

Comments
 (0)