-
Notifications
You must be signed in to change notification settings - Fork 522
Simplify by replacing chained $var === const
with in_array()
#4098
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ondrejmirtes
merged 3 commits into
phpstan:2.1.x
from
zonuexe:refactor/or-idetical-chain-to-in_array
Jul 17, 2025
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
163 changes: 163 additions & 0 deletions
163
build/PHPStan/Build/OrChainIdenticalComparisonToInArrayRule.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
<?php declare(strict_types = 1); | ||
|
||
namespace PHPStan\Build; | ||
|
||
use PhpParser\Node; | ||
use PhpParser\Node\Arg; | ||
use PhpParser\Node\ArrayItem; | ||
use PhpParser\Node\Expr; | ||
use PhpParser\Node\Expr\Array_; | ||
use PhpParser\Node\Expr\BinaryOp\BooleanOr; | ||
use PhpParser\Node\Expr\BinaryOp\Identical; | ||
use PhpParser\Node\Expr\ClassConstFetch; | ||
use PhpParser\Node\Expr\ConstFetch; | ||
use PhpParser\Node\Expr\FuncCall; | ||
use PhpParser\Node\Name; | ||
use PhpParser\Node\Scalar; | ||
use PhpParser\Node\Stmt\If_; | ||
use PHPStan\Analyser\Scope; | ||
use PHPStan\DependencyInjection\AutowiredParameter; | ||
use PHPStan\File\FileHelper; | ||
use PHPStan\Node\Printer\ExprPrinter; | ||
use PHPStan\Rules\IdentifierRuleError; | ||
use PHPStan\Rules\Rule; | ||
use PHPStan\Rules\RuleErrorBuilder; | ||
use function array_map; | ||
use function array_merge; | ||
use function array_shift; | ||
use function count; | ||
use function dirname; | ||
use function str_starts_with; | ||
|
||
/** | ||
* @implements Rule<If_> | ||
*/ | ||
final class OrChainIdenticalComparisonToInArrayRule implements Rule | ||
{ | ||
|
||
public function __construct( | ||
#[AutowiredParameter] | ||
private ExprPrinter $printer, | ||
private FileHelper $fileHelper, | ||
private bool $skipTests = true, | ||
) | ||
{ | ||
} | ||
|
||
public function getNodeType(): string | ||
{ | ||
return If_::class; | ||
} | ||
|
||
public function processNode(Node $node, Scope $scope): array | ||
{ | ||
$errors = $this->processConditionNode($node->cond, $scope); | ||
foreach ($node->elseifs as $elseifCondNode) { | ||
$errors = array_merge($errors, $this->processConditionNode($elseifCondNode->cond, $scope)); | ||
} | ||
|
||
return $errors; | ||
} | ||
|
||
/** | ||
* @return list<IdentifierRuleError> | ||
*/ | ||
public function processConditionNode(Expr $condNode, Scope $scope): array | ||
{ | ||
$comparisons = $this->unpackOrChain($condNode); | ||
if (count($comparisons) < 2) { | ||
return []; | ||
} | ||
|
||
$firstComparison = array_shift($comparisons); | ||
if (!$firstComparison instanceof Identical) { | ||
return []; | ||
} | ||
|
||
$subjectAndValue = $this->getSubjectAndValue($firstComparison); | ||
if ($subjectAndValue === null) { | ||
return []; | ||
} | ||
|
||
if ($this->skipTests && str_starts_with($this->fileHelper->normalizePath($scope->getFile()), $this->fileHelper->normalizePath(dirname(__DIR__, 3) . '/tests'))) { | ||
return []; | ||
} | ||
|
||
$subjectNode = $subjectAndValue['subject']; | ||
$subjectStr = $this->printer->printExpr($subjectNode); | ||
$values = [$subjectAndValue['value']]; | ||
|
||
foreach ($comparisons as $comparison) { | ||
if (!$comparison instanceof Identical) { | ||
return []; | ||
} | ||
|
||
$currentSubjectAndValue = $this->getSubjectAndValue($comparison); | ||
if ($currentSubjectAndValue === null) { | ||
return []; | ||
} | ||
|
||
if ($this->printer->printExpr($currentSubjectAndValue['subject']) !== $subjectStr) { | ||
return []; | ||
} | ||
|
||
$values[] = $currentSubjectAndValue['value']; | ||
} | ||
|
||
$errorBuilder = RuleErrorBuilder::message('This chain of identical comparisons can be simplified using in_array().') | ||
->line($condNode->getStartLine()) | ||
->fixNode($condNode, static fn (Expr $node) => self::createInArrayCall($subjectNode, $values)) | ||
->identifier('or.chainIdenticalComparison'); | ||
|
||
return [$errorBuilder->build()]; | ||
} | ||
|
||
/** | ||
* @return list<Expr> | ||
*/ | ||
private function unpackOrChain(Expr $node): array | ||
{ | ||
if ($node instanceof BooleanOr) { | ||
return [...$this->unpackOrChain($node->left), ...$this->unpackOrChain($node->right)]; | ||
} | ||
|
||
return [$node]; | ||
} | ||
|
||
/** | ||
* @phpstan-assert-if-true Scalar|ClassConstFetch|ConstFetch $node | ||
*/ | ||
private static function isSubjectNode(Expr $node): bool | ||
{ | ||
return $node instanceof Scalar || $node instanceof ClassConstFetch || $node instanceof ConstFetch; | ||
} | ||
|
||
/** | ||
* @return array{subject: Expr, value: Scalar|ClassConstFetch|ConstFetch}|null | ||
*/ | ||
private function getSubjectAndValue(Identical $comparison): ?array | ||
{ | ||
if (self::isSubjectNode($comparison->left) && !self::isSubjectNode($comparison->left)) { | ||
return ['subject' => $comparison->right, 'value' => $comparison->left]; | ||
} | ||
|
||
if (!self::isSubjectNode($comparison->left) && self::isSubjectNode($comparison->right)) { | ||
return ['subject' => $comparison->left, 'value' => $comparison->right]; | ||
} | ||
|
||
return null; | ||
} | ||
|
||
/** | ||
* @param list<Scalar|ClassConstFetch|ConstFetch> $values | ||
*/ | ||
private static function createInArrayCall(Expr $subjectNode, array $values): FuncCall | ||
{ | ||
return new FuncCall(new Name('\in_array'), [ | ||
new Arg($subjectNode), | ||
new Arg(new Array_(array_map(static fn ($value) => new ArrayItem($value), $values))), | ||
new Arg(new ConstFetch(new Name('true'))), | ||
]); | ||
} | ||
|
||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
tests/PHPStan/Build/OrChainIdenticalComparisonToInArrayRuleTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
<?php declare(strict_types = 1); | ||
|
||
namespace PHPStan\Build; | ||
|
||
use PHPStan\File\FileHelper; | ||
use PHPStan\Node\Printer\ExprPrinter; | ||
use PHPStan\Node\Printer\Printer; | ||
use PHPStan\Rules\Rule; | ||
use PHPStan\Testing\RuleTestCase; | ||
|
||
/** | ||
* @extends RuleTestCase<OrChainIdenticalComparisonToInArrayRule> | ||
*/ | ||
final class OrChainIdenticalComparisonToInArrayRuleTest extends RuleTestCase | ||
{ | ||
|
||
protected function getRule(): Rule | ||
{ | ||
return new OrChainIdenticalComparisonToInArrayRule(new ExprPrinter(new Printer()), self::getContainer()->getByType(FileHelper::class), false); | ||
} | ||
|
||
public function testRule(): void | ||
{ | ||
$this->analyse([__DIR__ . '/data/or-chain-identical-comparison.php'], [ | ||
[ | ||
'This chain of identical comparisons can be simplified using in_array().', | ||
7, | ||
], | ||
[ | ||
'This chain of identical comparisons can be simplified using in_array().', | ||
11, | ||
], | ||
[ | ||
'This chain of identical comparisons can be simplified using in_array().', | ||
15, | ||
], | ||
[ | ||
'This chain of identical comparisons can be simplified using in_array().', | ||
17, | ||
], | ||
]); | ||
} | ||
|
||
public function testFix(): void | ||
{ | ||
$this->fix(__DIR__ . '/data/or-chain-identical-comparison.php', __DIR__ . '/data/or-chain-identical-comparison.php.fixed'); | ||
} | ||
|
||
} |
31 changes: 31 additions & 0 deletions
31
tests/PHPStan/Build/data/or-chain-identical-comparison.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
<?php | ||
|
||
if ($var === 'foo') { | ||
echo 'ok'; | ||
} | ||
|
||
if ($var === 'foo' || $var === 'bar') { | ||
echo 'ok'; | ||
} | ||
|
||
if ($var === 'foo' || $var === 'bar' || $var === 'buz') { | ||
echo 'ok'; | ||
} | ||
|
||
if ($var === 'foo' || $var === 'bar' || $var === 'buz') { | ||
echo 'ok'; | ||
} elseif ($var === 'foofoo' || $var === 'barbar' || $var === 'buzbuz') { | ||
echo 'ok'; | ||
} | ||
|
||
if ($var === 'foo' || $var === 'bar' || $var2 === 'buz') { | ||
echo 'no'; | ||
} | ||
|
||
if ($var === 'foo' || $var2 === 'bar' || $var === 'buz') { | ||
echo 'no'; | ||
} | ||
|
||
if ($var === 'foo' || $var2 === 'bar' || $var2 === 'buz') { | ||
echo 'no'; | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.