Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,14 @@ parameters:
-
identifier: symplify.noReference
message: '#Use explicit return value over magic &reference#'

# known type
-
identifier: argument.type
message: '#Parameter \#1 \$expr of method Rector\\CodeQuality\\Rector\\BooleanOr\\RepeatedOrEqualToInArrayRector\:\:matchComparedExprAndValueExpr\(\) expects PhpParser\\Node\\Expr\\BinaryOp\\Equal\|PhpParser\\Node\\Expr\\BinaryOp\\Identical, PhpParser\\Node\\Expr given#'

-
path: rules/Renaming/Rector/Name/RenameClassRector.php
identifier: return.type

- '#Method Rector\\(.*?)Rector\:\:refactor\(\) never returns \d so it can be removed from the return type#'
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector\Fixture;

final class CompareSameVariable
{
public function demo($someVariable): bool
{
if ($someVariable === 'a' || $someVariable === 'b' || $someVariable === 'c') {
return true;
}

return false;
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector\Fixture;

final class CompareSameVariable
{
public function demo($someVariable): bool
{
if (in_array($someVariable, ['a', 'b', 'c'], true)) {
return true;
}

return false;
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector\Fixture;

final class NonStrictInArray
{
public function demo($someVariable): bool
{
if ($someVariable == 'a' || $someVariable == 'b' || $someVariable == 'c') {
return true;
}

return false;
}
}

?>
-----
<?php

namespace Rector\Tests\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector\Fixture;

final class NonStrictInArray
{
public function demo($someVariable): bool
{
if (in_array($someVariable, ['a', 'b', 'c'])) {
return true;
}

return false;
}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Rector\Tests\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector\Fixture;

final class SkipTwoOrLess
{
public function demo($someVariable): bool
{
if ($someVariable === 'a' || $someVariable === 'b') {
return true;
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Rector\Tests\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class RepeatedOrEqualToInArrayRectorTest extends AbstractRectorTestCase
{
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

declare(strict_types=1);

use Rector\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector;
use Rector\Config\RectorConfig;

return RectorConfig::configure()
->withRules([RepeatedOrEqualToInArrayRector::class]);
179 changes: 179 additions & 0 deletions rules/CodeQuality/Rector/BooleanOr/RepeatedOrEqualToInArrayRector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
<?php

declare(strict_types=1);

namespace Rector\CodeQuality\Rector\BooleanOr;

use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\BinaryOp\BooleanOr;
use PhpParser\Node\Expr\BinaryOp\Equal;
use PhpParser\Node\Expr\BinaryOp\Identical;
use PhpParser\Node\Expr\ConstFetch;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use Rector\CodeQuality\ValueObject\ComparedExprAndValueExpr;
use Rector\PhpParser\Node\BetterNodeFinder;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \Rector\Tests\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector\RepeatedOrEqualToInArrayRectorTest
*/
final class RepeatedOrEqualToInArrayRector extends AbstractRector
{
public function __construct(
private readonly BetterNodeFinder $betterNodeFinder,
) {
}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Simplify repeated || compare of same value, to in_array() class',
[
new CodeSample(
<<<'CODE_SAMPLE'
if ($value === 10 || $value === 20 || $value === 30) {
// ...
}

CODE_SAMPLE
,
<<<'CODE_SAMPLE'
if (in_array($value, [10, 20, 30], true)) {
// ...
}
CODE_SAMPLE
),
]
);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [BooleanOr::class];
}

/**
* @param BooleanOr $node
*/
public function refactor(Node $node): ?FuncCall
{
$identicals = $this->betterNodeFinder->findInstanceOf($node, Identical::class);
$equals = $this->betterNodeFinder->findInstanceOf($node, Equal::class);

if (! $this->isEqualOrIdentical($node->right)) {
return null;
}

// match compared variable and expr
if (! $node->left instanceof BooleanOr && ! $this->isEqualOrIdentical($node->left)) {
return null;
}

$comparedExprAndValueExprs = $this->matchComparedAndDesiredValues($node);
if ($comparedExprAndValueExprs === null) {
return null;
}

if (count($comparedExprAndValueExprs) < 3) {
return null;
}

// ensure all compared expr are the same
$valueExprs = $this->resolveValueExprs($comparedExprAndValueExprs);

/** @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);

$args = $this->nodeFactory->createArgs([$firstComparedExprAndValue->getComparedExpr(), $array]);

if ($identicals !== [] && $equals === []) {
$args[] = new Arg(new ConstFetch(new Name('true')));
}

return new FuncCall(new Name('in_array'), $args);
}

private function isEqualOrIdentical(Expr $expr): bool
{
if ($expr instanceof Identical) {
return true;
}

return $expr instanceof Equal;
}

private function matchComparedExprAndValueExpr(Identical|Equal $expr): ComparedExprAndValueExpr
{
return new ComparedExprAndValueExpr($expr->left, $expr->right);
}

/**
* @param ComparedExprAndValueExpr[] $comparedExprAndValueExprs
* @return Expr[]
*/
private function resolveValueExprs(array $comparedExprAndValueExprs): array
{
$valueExprs = [];

foreach ($comparedExprAndValueExprs as $comparedExprAndValueExpr) {
$valueExprs[] = $comparedExprAndValueExpr->getValueExpr();
}

return $valueExprs;
}

/**
* @return null|ComparedExprAndValueExpr[]
*/
private function matchComparedAndDesiredValues(BooleanOr $booleanOr): ?array
{
/** @var Identical|Equal $rightCompare */
$rightCompare = $booleanOr->right;

// match compared expr and desired value
$comparedExprAndValueExprs = [$this->matchComparedExprAndValueExpr($rightCompare)];

$currentBooleanOr = $booleanOr;

while ($currentBooleanOr->left instanceof BooleanOr) {
if (! $this->isEqualOrIdentical($currentBooleanOr->left->right)) {
return null;
}

$comparedExprAndValueExprs[] = $this->matchComparedExprAndValueExpr($currentBooleanOr->left->right);
$currentBooleanOr = $currentBooleanOr->left;
}

if (! $this->isEqualOrIdentical($currentBooleanOr->left)) {
return null;
}

/** @var Identical|Equal $leftCompare */
$leftCompare = $currentBooleanOr->left;

$comparedExprAndValueExprs[] = $this->matchComparedExprAndValueExpr($leftCompare);

// keep original natural order, as left/right goes from bottom up
return array_reverse($comparedExprAndValueExprs);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@

namespace Rector\CodeQuality\Rector\If_;

use PhpParser\Token;
use PhpParser\Node;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Else_;
use PhpParser\Node\Stmt\ElseIf_;
use PhpParser\Node\Stmt\If_;
use PhpParser\Token;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
Expand Down
26 changes: 26 additions & 0 deletions rules/CodeQuality/ValueObject/ComparedExprAndValueExpr.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Rector\CodeQuality\ValueObject;

use PhpParser\Node\Expr;

final readonly class ComparedExprAndValueExpr
{
public function __construct(
private Expr $comparedExpr,
private Expr $valueExpr
) {
}

public function getComparedExpr(): Expr
{
return $this->comparedExpr;
}

public function getValueExpr(): Expr
{
return $this->valueExpr;
}
}
4 changes: 2 additions & 2 deletions rules/Php70/EregToPcreTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ private function _ere2pcre(string $content, int $i): array
$r[$rr] .= '[' . $cls . ']';
} elseif ($char === ')') {
break;
} elseif ($char === '*' || $char === '+' || $char === '?') {
} elseif (in_array($char, ['*', '+', '?'], true)) {
throw new InvalidEregException('unescaped metacharacter "' . $char . '"');
} elseif ($char === '{') {
if ($i + 1 < $l && \str_contains('0123456789', $content[$i + 1])) {
Expand Down Expand Up @@ -177,7 +177,7 @@ private function _ere2pcre(string $content, int $i): array

// piece after the atom (only ONE of them is possible)
$char = $content[$i];
if ($char === '*' || $char === '+' || $char === '?') {
if (in_array($char, ['*', '+', '?'], true)) {
$r[$rr] .= $char;
++$i;
} elseif ($char === '{') {
Expand Down
2 changes: 2 additions & 0 deletions src/Config/Level/CodeQualityLevel.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector;
use Rector\CodeQuality\Rector\BooleanNot\ReplaceMultipleBooleanNotRector;
use Rector\CodeQuality\Rector\BooleanNot\SimplifyDeMorganBinaryRector;
use Rector\CodeQuality\Rector\BooleanOr\RepeatedOrEqualToInArrayRector;
use Rector\CodeQuality\Rector\Catch_\ThrowWithPreviousExceptionRector;
use Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector;
use Rector\CodeQuality\Rector\Class_\ConvertStaticToSelfRector;
Expand Down Expand Up @@ -104,6 +105,7 @@ final class CodeQualityLevel
SimplifyEmptyArrayCheckRector::class,
ReplaceMultipleBooleanNotRector::class,
ForeachToInArrayRector::class,
RepeatedOrEqualToInArrayRector::class,
SimplifyForeachToCoalescingRector::class,
SimplifyFuncGetArgsCountRector::class,
SimplifyInArrayValuesRector::class,
Expand Down