Updated Rector to commit 3c592b05dc0aa78702a4b38d39711d78c404e279

3c592b05dc [CodeQuality] Remove ForToForeachRector, as overly deatiled and not reliable (#3747)
This commit is contained in:
Tomas Votruba 2023-05-06 21:47:33 +00:00
parent b61a41bf01
commit e7d9598446
12 changed files with 18 additions and 523 deletions

View File

@ -22,7 +22,6 @@ use Rector\CodeQuality\Rector\Equal\UseIdenticalOverEqualWithSameTypeRector;
use Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector;
use Rector\CodeQuality\Rector\Expression\TernaryFalseExpressionToIfRector;
use Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector;
use Rector\CodeQuality\Rector\For_\ForToForeachRector;
use Rector\CodeQuality\Rector\Foreach_\ForeachItemsAssignToEmptyArrayToAssignRector;
use Rector\CodeQuality\Rector\Foreach_\ForeachToInArrayRector;
use Rector\CodeQuality\Rector\Foreach_\SimplifyForeachToArrayFilterRector;
@ -114,5 +113,5 @@ return static function (RectorConfig $rectorConfig) : void {
'mbstrrpos' => 'mb_strrpos',
'mbsubstr' => 'mb_substr',
]);
$rectorConfig->rules([CombinedAssignRector::class, SimplifyEmptyArrayCheckRector::class, ReplaceMultipleBooleanNotRector::class, ForeachToInArrayRector::class, SimplifyForeachToCoalescingRector::class, SimplifyFuncGetArgsCountRector::class, SimplifyInArrayValuesRector::class, SimplifyStrposLowerRector::class, GetClassToInstanceOfRector::class, SimplifyArraySearchRector::class, SimplifyConditionsRector::class, SimplifyIfNotNullReturnRector::class, SimplifyIfReturnBoolRector::class, SimplifyUselessVariableRector::class, UnnecessaryTernaryExpressionRector::class, RemoveExtraParametersRector::class, SimplifyDeMorganBinaryRector::class, SimplifyTautologyTernaryRector::class, SimplifyForeachToArrayFilterRector::class, SingleInArrayToCompareRector::class, SimplifyIfElseToTernaryRector::class, JoinStringConcatRector::class, ConsecutiveNullCompareReturnsToNullCoalesceQueueRector::class, ExplicitBoolCompareRector::class, CombineIfRector::class, UseIdenticalOverEqualWithSameTypeRector::class, SimplifyBoolIdenticalTrueRector::class, SimplifyRegexPatternRector::class, BooleanNotIdenticalToNotIdenticalRector::class, StrvalToTypeCastRector::class, FloatvalToTypeCastRector::class, CallableThisArrayToAnonymousFunctionRector::class, AndAssignsToSeparateLinesRector::class, ForToForeachRector::class, CompactToVariablesRector::class, CompleteDynamicPropertiesRector::class, IsAWithStringWithThirdArgumentRector::class, StrlenZeroToIdenticalEmptyStringRector::class, RemoveAlwaysTrueConditionSetInConstructorRector::class, ThrowWithPreviousExceptionRector::class, RemoveSoleValueSprintfRector::class, ShortenElseIfRector::class, AddPregQuoteDelimiterRector::class, ArrayMergeOfNonArraysToSimpleArrayRector::class, IntvalToTypeCastRector::class, BoolvalToTypeCastRector::class, ArrayKeyExistsTernaryThenValueToCoalescingRector::class, AbsolutizeRequireAndIncludePathRector::class, ChangeArrayPushToArrayAssignRector::class, ForRepeatedCountToOwnVariableRector::class, ForeachItemsAssignToEmptyArrayToAssignRector::class, InlineIfToExplicitIfRector::class, ArrayKeysAndInArrayToArrayKeyExistsRector::class, SplitListAssignToSeparateLineRector::class, UnusedForeachValueToArrayKeysRector::class, CommonNotEqualRector::class, SetTypeToCastRector::class, LogicalToBooleanRector::class, VarToPublicPropertyRector::class, IssetOnPropertyObjectToPropertyExistsRector::class, NewStaticToNewSelfRector::class, UnwrapSprintfOneArgumentRector::class, SwitchNegatedTernaryRector::class, SingularSwitchToIfRector::class, SimplifyIfNullableReturnRector::class, NarrowUnionTypeDocRector::class, FuncGetArgsToVariadicParamRector::class, CallUserFuncToMethodCallRector::class, CallUserFuncWithArrowFunctionToInlineRector::class, CountArrayToEmptyArrayComparisonRector::class, FlipTypeControlToUseExclusiveTypeRector::class, ExplicitMethodCallOverMagicGetSetRector::class, InlineArrayReturnAssignRector::class, InlineIsAInstanceOfRector::class, TernaryFalseExpressionToIfRector::class, InlineConstructorDefaultToPropertyRector::class, SimplifyIfExactValueReturnValueRector::class, SimplifyUselessLastVariableAssignRector::class, ReturnTypeFromStrictScalarReturnExprRector::class, TernaryEmptyArrayArrayDimFetchToCoalesceRector::class, OptionalParametersAfterRequiredRector::class, SimplifyEmptyCheckOnEmptyArrayRector::class, SwitchTrueToIfRector::class]);
$rectorConfig->rules([CombinedAssignRector::class, SimplifyEmptyArrayCheckRector::class, ReplaceMultipleBooleanNotRector::class, ForeachToInArrayRector::class, SimplifyForeachToCoalescingRector::class, SimplifyFuncGetArgsCountRector::class, SimplifyInArrayValuesRector::class, SimplifyStrposLowerRector::class, GetClassToInstanceOfRector::class, SimplifyArraySearchRector::class, SimplifyConditionsRector::class, SimplifyIfNotNullReturnRector::class, SimplifyIfReturnBoolRector::class, SimplifyUselessVariableRector::class, UnnecessaryTernaryExpressionRector::class, RemoveExtraParametersRector::class, SimplifyDeMorganBinaryRector::class, SimplifyTautologyTernaryRector::class, SimplifyForeachToArrayFilterRector::class, SingleInArrayToCompareRector::class, SimplifyIfElseToTernaryRector::class, JoinStringConcatRector::class, ConsecutiveNullCompareReturnsToNullCoalesceQueueRector::class, ExplicitBoolCompareRector::class, CombineIfRector::class, UseIdenticalOverEqualWithSameTypeRector::class, SimplifyBoolIdenticalTrueRector::class, SimplifyRegexPatternRector::class, BooleanNotIdenticalToNotIdenticalRector::class, StrvalToTypeCastRector::class, FloatvalToTypeCastRector::class, CallableThisArrayToAnonymousFunctionRector::class, AndAssignsToSeparateLinesRector::class, CompactToVariablesRector::class, CompleteDynamicPropertiesRector::class, IsAWithStringWithThirdArgumentRector::class, StrlenZeroToIdenticalEmptyStringRector::class, RemoveAlwaysTrueConditionSetInConstructorRector::class, ThrowWithPreviousExceptionRector::class, RemoveSoleValueSprintfRector::class, ShortenElseIfRector::class, AddPregQuoteDelimiterRector::class, ArrayMergeOfNonArraysToSimpleArrayRector::class, IntvalToTypeCastRector::class, BoolvalToTypeCastRector::class, ArrayKeyExistsTernaryThenValueToCoalescingRector::class, AbsolutizeRequireAndIncludePathRector::class, ChangeArrayPushToArrayAssignRector::class, ForRepeatedCountToOwnVariableRector::class, ForeachItemsAssignToEmptyArrayToAssignRector::class, InlineIfToExplicitIfRector::class, ArrayKeysAndInArrayToArrayKeyExistsRector::class, SplitListAssignToSeparateLineRector::class, UnusedForeachValueToArrayKeysRector::class, CommonNotEqualRector::class, SetTypeToCastRector::class, LogicalToBooleanRector::class, VarToPublicPropertyRector::class, IssetOnPropertyObjectToPropertyExistsRector::class, NewStaticToNewSelfRector::class, UnwrapSprintfOneArgumentRector::class, SwitchNegatedTernaryRector::class, SingularSwitchToIfRector::class, SimplifyIfNullableReturnRector::class, NarrowUnionTypeDocRector::class, FuncGetArgsToVariadicParamRector::class, CallUserFuncToMethodCallRector::class, CallUserFuncWithArrowFunctionToInlineRector::class, CountArrayToEmptyArrayComparisonRector::class, FlipTypeControlToUseExclusiveTypeRector::class, ExplicitMethodCallOverMagicGetSetRector::class, InlineArrayReturnAssignRector::class, InlineIsAInstanceOfRector::class, TernaryFalseExpressionToIfRector::class, InlineConstructorDefaultToPropertyRector::class, SimplifyIfExactValueReturnValueRector::class, SimplifyUselessLastVariableAssignRector::class, ReturnTypeFromStrictScalarReturnExprRector::class, TernaryEmptyArrayArrayDimFetchToCoalesceRector::class, OptionalParametersAfterRequiredRector::class, SimplifyEmptyCheckOnEmptyArrayRector::class, SwitchTrueToIfRector::class]);
};

View File

@ -1,4 +1,4 @@
# 421 Rules Overview
# 420 Rules Overview
<br>
@ -6,7 +6,7 @@
- [Arguments](#arguments) (6)
- [CodeQuality](#codequality) (79)
- [CodeQuality](#codequality) (78)
- [CodingStyle](#codingstyle) (39)
@ -808,30 +808,6 @@ Change `count()` in for function to own variable
<br>
### ForToForeachRector
Change `for()` to `foreach()` where useful
- class: [`Rector\CodeQuality\Rector\For_\ForToForeachRector`](../rules/CodeQuality/Rector/For_/ForToForeachRector.php)
```diff
class SomeClass
{
public function run($tokens)
{
- for ($i = 0, $c = count($tokens); $i < $c; ++$i) {
- if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'fn') {
+ foreach ($tokens as $i => $token) {
+ if ($token[0] === T_STRING && $token[1] === 'fn') {
$tokens[$i][0] = self::T_FN;
}
}
}
}
```
<br>
### ForeachItemsAssignToEmptyArrayToAssignRector
Change `foreach()` items assign to empty array to direct assign

View File

@ -1,164 +0,0 @@
<?php
declare (strict_types=1);
namespace Rector\CodeQuality\NodeAnalyzer;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\BinaryOp\Greater;
use PhpParser\Node\Expr\BinaryOp\Smaller;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\PostInc;
use PhpParser\Node\Expr\PreInc;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\For_;
use PhpParser\Node\Stmt\Unset_;
use Rector\Core\NodeManipulator\AssignManipulator;
use Rector\Core\PhpParser\Comparing\NodeComparator;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\NodeTypeResolver\Node\AttributeKey;
final class ForAnalyzer
{
/**
* @var string
*/
private const COUNT = 'count';
/**
* @readonly
* @var \Rector\NodeNameResolver\NodeNameResolver
*/
private $nodeNameResolver;
/**
* @readonly
* @var \Rector\Core\PhpParser\Node\BetterNodeFinder
*/
private $betterNodeFinder;
/**
* @readonly
* @var \Rector\Core\NodeManipulator\AssignManipulator
*/
private $assignManipulator;
/**
* @readonly
* @var \Rector\Core\PhpParser\Comparing\NodeComparator
*/
private $nodeComparator;
public function __construct(NodeNameResolver $nodeNameResolver, BetterNodeFinder $betterNodeFinder, AssignManipulator $assignManipulator, NodeComparator $nodeComparator)
{
$this->nodeNameResolver = $nodeNameResolver;
$this->betterNodeFinder = $betterNodeFinder;
$this->assignManipulator = $assignManipulator;
$this->nodeComparator = $nodeComparator;
}
/**
* @param Expr[] $condExprs
*/
public function isCondExprSmallerOrGreater(array $condExprs, string $keyValueName, string $countValueName) : bool
{
// $i < $count
if ($condExprs[0] instanceof Smaller) {
if (!$this->nodeNameResolver->isName($condExprs[0]->left, $keyValueName)) {
return \false;
}
return $this->nodeNameResolver->isName($condExprs[0]->right, $countValueName);
}
// $i > $count
if ($condExprs[0] instanceof Greater) {
if (!$this->nodeNameResolver->isName($condExprs[0]->left, $countValueName)) {
return \false;
}
return $this->nodeNameResolver->isName($condExprs[0]->right, $keyValueName);
}
return \false;
}
/**
* @param Expr[] $loopExprs
* $param
*/
public function isLoopMatch(array $loopExprs, ?string $keyValueName) : bool
{
if (\count($loopExprs) !== 1) {
return \false;
}
if ($keyValueName === null) {
return \false;
}
$prePostInc = $loopExprs[0];
if ($prePostInc instanceof PreInc || $prePostInc instanceof PostInc) {
return $this->nodeNameResolver->isName($prePostInc->var, $keyValueName);
}
return \false;
}
public function isCountValueVariableUsedInsideForStatements(For_ $for, ?Expr $expr) : bool
{
return (bool) $this->betterNodeFinder->findFirst($for->stmts, function (Node $node) use($expr) : bool {
return $this->nodeComparator->areNodesEqual($node, $expr);
});
}
public function isArrayWithKeyValueNameUnsetted(For_ $for) : bool
{
return (bool) $this->betterNodeFinder->findFirst($for->stmts, static function (Node $node) : bool {
/** @var Node $parentNode */
$parentNode = $node->getAttribute(AttributeKey::PARENT_NODE);
if (!$parentNode instanceof Unset_) {
return \false;
}
return $node instanceof ArrayDimFetch;
});
}
public function isAssignmentWithArrayDimFetchAsVariableInsideForStatements(For_ $for, string $keyValueName) : bool
{
return (bool) $this->betterNodeFinder->findFirst($for->stmts, function (Node $node) use($keyValueName) : bool {
if (!$node instanceof Assign) {
return \false;
}
if (!$node->var instanceof ArrayDimFetch) {
return \false;
}
$arrayDimFetch = $node->var;
if (!$arrayDimFetch->dim instanceof Expr) {
return \false;
}
if (!$arrayDimFetch->dim instanceof Variable) {
return \false;
}
return $this->nodeNameResolver->isName($arrayDimFetch->dim, $keyValueName);
});
}
/**
* @param Expr[] $condExprs
*/
public function isCondExprOneOrKeyValueNameNotNull(array $condExprs, ?string $keyValueName) : bool
{
if (\count($condExprs) !== 1) {
return \true;
}
return $keyValueName === null;
}
public function isArrayDimFetchPartOfAssignOrArgParentCount(ArrayDimFetch $arrayDimFetch) : bool
{
$parentNode = $arrayDimFetch->getAttribute(AttributeKey::PARENT_NODE);
if (!$parentNode instanceof Node) {
return \false;
}
if ($this->assignManipulator->isLeftPartOfAssign($arrayDimFetch)) {
return \true;
}
return $this->isArgParentCount($parentNode);
}
private function isArgParentCount(Node $node) : bool
{
if (!$node instanceof Arg) {
return \false;
}
$parentNode = $node->getAttribute(AttributeKey::PARENT_NODE);
if (!$parentNode instanceof FuncCall) {
return \false;
}
return $this->nodeNameResolver->isName($parentNode, self::COUNT);
}
}

View File

@ -8,13 +8,11 @@ use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Foreach_;
use Rector\Core\PhpParser\Comparing\NodeComparator;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
use Rector\PhpDocParser\NodeTraverser\SimpleCallableNodeTraverser;
final class ForeachAnalyzer
{
/**
@ -22,21 +20,11 @@ final class ForeachAnalyzer
* @var \Rector\Core\PhpParser\Comparing\NodeComparator
*/
private $nodeComparator;
/**
* @readonly
* @var \Rector\CodeQuality\NodeAnalyzer\ForAnalyzer
*/
private $forAnalyzer;
/**
* @readonly
* @var \Rector\NodeNameResolver\NodeNameResolver
*/
private $nodeNameResolver;
/**
* @readonly
* @var \Rector\PhpDocParser\NodeTraverser\SimpleCallableNodeTraverser
*/
private $simpleCallableNodeTraverser;
/**
* @readonly
* @var \Rector\Core\PhpParser\Node\BetterNodeFinder
@ -47,12 +35,10 @@ final class ForeachAnalyzer
* @var \Rector\CodeQuality\NodeAnalyzer\VariableNameUsedNextAnalyzer
*/
private $variableNameUsedNextAnalyzer;
public function __construct(NodeComparator $nodeComparator, \Rector\CodeQuality\NodeAnalyzer\ForAnalyzer $forAnalyzer, NodeNameResolver $nodeNameResolver, SimpleCallableNodeTraverser $simpleCallableNodeTraverser, BetterNodeFinder $betterNodeFinder, \Rector\CodeQuality\NodeAnalyzer\VariableNameUsedNextAnalyzer $variableNameUsedNextAnalyzer)
public function __construct(NodeComparator $nodeComparator, NodeNameResolver $nodeNameResolver, BetterNodeFinder $betterNodeFinder, \Rector\CodeQuality\NodeAnalyzer\VariableNameUsedNextAnalyzer $variableNameUsedNextAnalyzer)
{
$this->nodeComparator = $nodeComparator;
$this->forAnalyzer = $forAnalyzer;
$this->nodeNameResolver = $nodeNameResolver;
$this->simpleCallableNodeTraverser = $simpleCallableNodeTraverser;
$this->betterNodeFinder = $betterNodeFinder;
$this->variableNameUsedNextAnalyzer = $variableNameUsedNextAnalyzer;
}
@ -85,32 +71,6 @@ final class ForeachAnalyzer
}
return $onlyStatement->var->var;
}
/**
* @param Stmt[] $stmts
*/
public function useForeachVariableInStmts(Expr $foreachedValue, Expr $singleValue, array $stmts, string $keyValueName) : void
{
$this->simpleCallableNodeTraverser->traverseNodesWithCallable($stmts, function (Node $node) use($foreachedValue, $singleValue, $keyValueName) : ?Expr {
if (!$node instanceof ArrayDimFetch) {
return null;
}
// must be the same as foreach value
if (!$this->nodeComparator->areNodesEqual($node->var, $foreachedValue)) {
return null;
}
if ($this->forAnalyzer->isArrayDimFetchPartOfAssignOrArgParentCount($node)) {
return null;
}
// is dim same as key value name, ...[$i]
if (!$node->dim instanceof Variable) {
return null;
}
if (!$this->nodeNameResolver->isName($node->dim, $keyValueName)) {
return null;
}
return $singleValue;
});
}
public function isValueVarUsed(Foreach_ $foreach, string $singularValueVarName) : bool
{
$isUsedInStmts = (bool) $this->betterNodeFinder->findFirst($foreach->stmts, function (Node $node) use($singularValueVarName) : bool {

View File

@ -5,7 +5,6 @@ namespace Rector\CodeQuality\NodeAnalyzer;
use PhpParser\Node;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\For_;
use PhpParser\Node\Stmt\Foreach_;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\NodeNameResolver\NodeNameResolver;
@ -26,12 +25,9 @@ final class VariableNameUsedNextAnalyzer
$this->betterNodeFinder = $betterNodeFinder;
$this->nodeNameResolver = $nodeNameResolver;
}
/**
* @param \PhpParser\Node\Stmt\For_|\PhpParser\Node\Stmt\Foreach_ $for
*/
public function isValueVarUsedNext($for, string $valueVarName) : bool
public function isValueVarUsedNext(Foreach_ $foreach, string $valueVarName) : bool
{
return (bool) $this->betterNodeFinder->findFirstNext($for, function (Node $node) use($valueVarName) : bool {
return (bool) $this->betterNodeFinder->findFirstNext($foreach, function (Node $node) use($valueVarName) : bool {
if (!$node instanceof Variable) {
return \false;
}

View File

@ -1,26 +0,0 @@
<?php
declare (strict_types=1);
namespace Rector\CodeQuality\NodeFactory;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\For_;
use PhpParser\Node\Stmt\Foreach_;
use Rector\Core\Exception\ShouldNotHappenException;
final class ForeachFactory
{
public function createFromFor(For_ $for, string $iteratedVariableName, ?Expr $iteratedExpr, ?string $keyValueName) : Foreach_
{
if (!$iteratedExpr instanceof Expr) {
throw new ShouldNotHappenException();
}
if ($keyValueName === null) {
throw new ShouldNotHappenException();
}
$foreach = new Foreach_($iteratedExpr, new Variable($iteratedVariableName));
$foreach->stmts = $for->stmts;
$foreach->keyVar = new Variable($keyValueName);
return $foreach;
}
}

View File

@ -1,240 +0,0 @@
<?php
declare (strict_types=1);
namespace Rector\CodeQuality\Rector\For_;
use RectorPrefix202305\Doctrine\Inflector\Inflector;
use PhpParser\Node;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\BinaryOp;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Stmt\For_;
use PhpParser\Node\Stmt\Foreach_;
use Rector\CodeQuality\NodeAnalyzer\ForAnalyzer;
use Rector\CodeQuality\NodeAnalyzer\ForeachAnalyzer;
use Rector\CodeQuality\NodeAnalyzer\VariableNameUsedNextAnalyzer;
use Rector\CodeQuality\NodeFactory\ForeachFactory;
use Rector\Core\Exception\ShouldNotHappenException;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\CodeQuality\Rector\For_\ForToForeachRector\ForToForeachRectorTest
*/
final class ForToForeachRector extends AbstractRector
{
/**
* @var string
*/
private const COUNT = 'count';
/**
* @var string|null
*/
private $keyValueName;
/**
* @var string|null
*/
private $countValueName;
/**
* @var \PhpParser\Node\Expr|null
*/
private $countValueVariableExpr;
/**
* @var \PhpParser\Node\Expr|null
*/
private $iteratedExpr;
/**
* @readonly
* @var \Doctrine\Inflector\Inflector
*/
private $inflector;
/**
* @readonly
* @var \Rector\CodeQuality\NodeAnalyzer\ForAnalyzer
*/
private $forAnalyzer;
/**
* @readonly
* @var \Rector\CodeQuality\NodeFactory\ForeachFactory
*/
private $foreachFactory;
/**
* @readonly
* @var \Rector\CodeQuality\NodeAnalyzer\ForeachAnalyzer
*/
private $foreachAnalyzer;
/**
* @readonly
* @var \Rector\CodeQuality\NodeAnalyzer\VariableNameUsedNextAnalyzer
*/
private $variableNameUsedNextAnalyzer;
public function __construct(Inflector $inflector, ForAnalyzer $forAnalyzer, ForeachFactory $foreachFactory, ForeachAnalyzer $foreachAnalyzer, VariableNameUsedNextAnalyzer $variableNameUsedNextAnalyzer)
{
$this->inflector = $inflector;
$this->forAnalyzer = $forAnalyzer;
$this->foreachFactory = $foreachFactory;
$this->foreachAnalyzer = $foreachAnalyzer;
$this->variableNameUsedNextAnalyzer = $variableNameUsedNextAnalyzer;
}
public function getRuleDefinition() : RuleDefinition
{
return new RuleDefinition('Change for() to foreach() where useful', [new CodeSample(<<<'CODE_SAMPLE'
class SomeClass
{
public function run($tokens)
{
for ($i = 0, $c = count($tokens); $i < $c; ++$i) {
if ($tokens[$i][0] === T_STRING && $tokens[$i][1] === 'fn') {
$tokens[$i][0] = self::T_FN;
}
}
}
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
class SomeClass
{
public function run($tokens)
{
foreach ($tokens as $i => $token) {
if ($token[0] === T_STRING && $token[1] === 'fn') {
$tokens[$i][0] = self::T_FN;
}
}
}
}
CODE_SAMPLE
)]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes() : array
{
return [For_::class];
}
/**
* @param For_ $node
*/
public function refactor(Node $node) : ?Node
{
$this->reset();
$this->matchInit($node->init);
if (!$this->isConditionMatch($node->cond)) {
return null;
}
if (!$this->forAnalyzer->isLoopMatch($node->loop, $this->keyValueName)) {
return null;
}
if (!$this->iteratedExpr instanceof Expr) {
return null;
}
if ($this->keyValueName === null) {
return null;
}
$iteratedVariable = $this->getName($this->iteratedExpr);
if ($iteratedVariable === null) {
return null;
}
$init = $node->init;
if (\count($init) > 2) {
return null;
}
if ($this->forAnalyzer->isCountValueVariableUsedInsideForStatements($node, $this->countValueVariableExpr)) {
return null;
}
if ($this->forAnalyzer->isAssignmentWithArrayDimFetchAsVariableInsideForStatements($node, $this->keyValueName)) {
return null;
}
if ($this->forAnalyzer->isArrayWithKeyValueNameUnsetted($node)) {
return null;
}
return $this->processForToForeach($node, $iteratedVariable);
}
private function processForToForeach(For_ $for, string $iteratedVariable) : ?Foreach_
{
$originalVariableSingle = $this->inflector->singularize($iteratedVariable);
$iteratedVariableSingle = $originalVariableSingle;
if ($iteratedVariableSingle === $iteratedVariable) {
$iteratedVariableSingle = 'single' . \ucfirst($iteratedVariableSingle);
}
if (!$this->variableNameUsedNextAnalyzer->isValueVarUsedNext($for, $iteratedVariableSingle)) {
return $this->createForeachFromForWithIteratedVariableSingle($for, $iteratedVariableSingle);
}
if ($iteratedVariableSingle === $originalVariableSingle) {
return null;
}
if (!$this->variableNameUsedNextAnalyzer->isValueVarUsedNext($for, $originalVariableSingle)) {
return $this->createForeachFromForWithIteratedVariableSingle($for, $originalVariableSingle);
}
return null;
}
private function createForeachFromForWithIteratedVariableSingle(For_ $for, string $iteratedVariableSingle) : Foreach_
{
$foreach = $this->foreachFactory->createFromFor($for, $iteratedVariableSingle, $this->iteratedExpr, $this->keyValueName);
$this->mirrorComments($foreach, $for);
if ($this->keyValueName === null) {
throw new ShouldNotHappenException();
}
$this->foreachAnalyzer->useForeachVariableInStmts($foreach->expr, $foreach->valueVar, $foreach->stmts, $this->keyValueName);
return $foreach;
}
private function reset() : void
{
$this->keyValueName = null;
$this->countValueVariableExpr = null;
$this->countValueName = null;
$this->iteratedExpr = null;
}
/**
* @param Expr[] $initExprs
*/
private function matchInit(array $initExprs) : void
{
foreach ($initExprs as $initExpr) {
if (!$initExpr instanceof Assign) {
continue;
}
if ($this->valueResolver->isValue($initExpr->expr, 0)) {
$this->keyValueName = $this->getName($initExpr->var);
}
if (!$initExpr->expr instanceof FuncCall) {
continue;
}
$funcCall = $initExpr->expr;
if ($this->nodeNameResolver->isName($funcCall, self::COUNT) && $funcCall->args[0] instanceof Arg) {
$this->countValueVariableExpr = $initExpr->var;
$this->countValueName = $this->getName($initExpr->var);
$this->iteratedExpr = $funcCall->args[0]->value;
}
}
}
/**
* @param Expr[] $condExprs
*/
private function isConditionMatch(array $condExprs) : bool
{
if ($this->forAnalyzer->isCondExprOneOrKeyValueNameNotNull($condExprs, $this->keyValueName)) {
return \false;
}
/** @var string $keyValueName */
$keyValueName = $this->keyValueName;
if ($this->countValueName !== null) {
return $this->forAnalyzer->isCondExprSmallerOrGreater($condExprs, $keyValueName, $this->countValueName);
}
if (!$condExprs[0] instanceof BinaryOp) {
return \false;
}
$funcCall = $condExprs[0]->right;
if (!$funcCall instanceof FuncCall) {
return \false;
}
if ($this->nodeNameResolver->isName($funcCall, self::COUNT) && $funcCall->args[0] instanceof Arg) {
$this->iteratedExpr = $funcCall->args[0]->value;
return \true;
}
return \false;
}
}

View File

@ -19,12 +19,12 @@ final class VersionResolver
* @api
* @var string
*/
public const PACKAGE_VERSION = 'd13351c5b5800fdd9a25f1d8d9198749898ff2f6';
public const PACKAGE_VERSION = '3c592b05dc0aa78702a4b38d39711d78c404e279';
/**
* @api
* @var string
*/
public const RELEASE_DATE = '2023-05-06 18:19:49';
public const RELEASE_DATE = '2023-05-06 22:43:46';
/**
* @var int
*/

2
vendor/autoload.php vendored
View File

@ -22,4 +22,4 @@ if (PHP_VERSION_ID < 50600) {
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit2f4ad052e54c0e0c4358aed15203c363::getLoader();
return ComposerAutoloaderInit24fc5fd2b6218b109e4932a3a051625f::getLoader();

View File

@ -1206,14 +1206,12 @@ return array(
'Rector\\CodeQuality\\CompactConverter' => $baseDir . '/rules/CodeQuality/CompactConverter.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ClassLikeAnalyzer' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/ClassLikeAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ConstructorPropertyDefaultExprResolver' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/ConstructorPropertyDefaultExprResolver.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ForAnalyzer' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/ForAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ForeachAnalyzer' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/ForeachAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\LocalPropertyAnalyzer' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/LocalPropertyAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ReturnAnalyzer' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/ReturnAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\VariableDimFetchAssignResolver' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/VariableDimFetchAssignResolver.php',
'Rector\\CodeQuality\\NodeAnalyzer\\VariableNameUsedNextAnalyzer' => $baseDir . '/rules/CodeQuality/NodeAnalyzer/VariableNameUsedNextAnalyzer.php',
'Rector\\CodeQuality\\NodeFactory\\ArrayFilterFactory' => $baseDir . '/rules/CodeQuality/NodeFactory/ArrayFilterFactory.php',
'Rector\\CodeQuality\\NodeFactory\\ForeachFactory' => $baseDir . '/rules/CodeQuality/NodeFactory/ForeachFactory.php',
'Rector\\CodeQuality\\NodeFactory\\MissingPropertiesFactory' => $baseDir . '/rules/CodeQuality/NodeFactory/MissingPropertiesFactory.php',
'Rector\\CodeQuality\\NodeFactory\\PropertyTypeDecorator' => $baseDir . '/rules/CodeQuality/NodeFactory/PropertyTypeDecorator.php',
'Rector\\CodeQuality\\NodeManipulator\\ExprBoolCaster' => $baseDir . '/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php',
@ -1238,7 +1236,6 @@ return array(
'Rector\\CodeQuality\\Rector\\Expression\\InlineIfToExplicitIfRector' => $baseDir . '/rules/CodeQuality/Rector/Expression/InlineIfToExplicitIfRector.php',
'Rector\\CodeQuality\\Rector\\Expression\\TernaryFalseExpressionToIfRector' => $baseDir . '/rules/CodeQuality/Rector/Expression/TernaryFalseExpressionToIfRector.php',
'Rector\\CodeQuality\\Rector\\For_\\ForRepeatedCountToOwnVariableRector' => $baseDir . '/rules/CodeQuality/Rector/For_/ForRepeatedCountToOwnVariableRector.php',
'Rector\\CodeQuality\\Rector\\For_\\ForToForeachRector' => $baseDir . '/rules/CodeQuality/Rector/For_/ForToForeachRector.php',
'Rector\\CodeQuality\\Rector\\Foreach_\\ForeachItemsAssignToEmptyArrayToAssignRector' => $baseDir . '/rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php',
'Rector\\CodeQuality\\Rector\\Foreach_\\ForeachToInArrayRector' => $baseDir . '/rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php',
'Rector\\CodeQuality\\Rector\\Foreach_\\SimplifyForeachToArrayFilterRector' => $baseDir . '/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php',

View File

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit2f4ad052e54c0e0c4358aed15203c363
class ComposerAutoloaderInit24fc5fd2b6218b109e4932a3a051625f
{
private static $loader;
@ -22,17 +22,17 @@ class ComposerAutoloaderInit2f4ad052e54c0e0c4358aed15203c363
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInit2f4ad052e54c0e0c4358aed15203c363', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit24fc5fd2b6218b109e4932a3a051625f', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit2f4ad052e54c0e0c4358aed15203c363', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit24fc5fd2b6218b109e4932a3a051625f', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363::getInitializer($loader));
call_user_func(\Composer\Autoload\ComposerStaticInit24fc5fd2b6218b109e4932a3a051625f::getInitializer($loader));
$loader->setClassMapAuthoritative(true);
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363::$files;
$filesToLoad = \Composer\Autoload\ComposerStaticInit24fc5fd2b6218b109e4932a3a051625f::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;

View File

@ -4,7 +4,7 @@
namespace Composer\Autoload;
class ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363
class ComposerStaticInit24fc5fd2b6218b109e4932a3a051625f
{
public static $files = array (
'ad155f8f1cf0d418fe49e248db8c661b' => __DIR__ . '/..' . '/react/promise/src/functions_include.php',
@ -1448,14 +1448,12 @@ class ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363
'Rector\\CodeQuality\\CompactConverter' => __DIR__ . '/../..' . '/rules/CodeQuality/CompactConverter.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ClassLikeAnalyzer' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/ClassLikeAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ConstructorPropertyDefaultExprResolver' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/ConstructorPropertyDefaultExprResolver.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ForAnalyzer' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/ForAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ForeachAnalyzer' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/ForeachAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\LocalPropertyAnalyzer' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/LocalPropertyAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\ReturnAnalyzer' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/ReturnAnalyzer.php',
'Rector\\CodeQuality\\NodeAnalyzer\\VariableDimFetchAssignResolver' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/VariableDimFetchAssignResolver.php',
'Rector\\CodeQuality\\NodeAnalyzer\\VariableNameUsedNextAnalyzer' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeAnalyzer/VariableNameUsedNextAnalyzer.php',
'Rector\\CodeQuality\\NodeFactory\\ArrayFilterFactory' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeFactory/ArrayFilterFactory.php',
'Rector\\CodeQuality\\NodeFactory\\ForeachFactory' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeFactory/ForeachFactory.php',
'Rector\\CodeQuality\\NodeFactory\\MissingPropertiesFactory' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeFactory/MissingPropertiesFactory.php',
'Rector\\CodeQuality\\NodeFactory\\PropertyTypeDecorator' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeFactory/PropertyTypeDecorator.php',
'Rector\\CodeQuality\\NodeManipulator\\ExprBoolCaster' => __DIR__ . '/../..' . '/rules/CodeQuality/NodeManipulator/ExprBoolCaster.php',
@ -1480,7 +1478,6 @@ class ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363
'Rector\\CodeQuality\\Rector\\Expression\\InlineIfToExplicitIfRector' => __DIR__ . '/../..' . '/rules/CodeQuality/Rector/Expression/InlineIfToExplicitIfRector.php',
'Rector\\CodeQuality\\Rector\\Expression\\TernaryFalseExpressionToIfRector' => __DIR__ . '/../..' . '/rules/CodeQuality/Rector/Expression/TernaryFalseExpressionToIfRector.php',
'Rector\\CodeQuality\\Rector\\For_\\ForRepeatedCountToOwnVariableRector' => __DIR__ . '/../..' . '/rules/CodeQuality/Rector/For_/ForRepeatedCountToOwnVariableRector.php',
'Rector\\CodeQuality\\Rector\\For_\\ForToForeachRector' => __DIR__ . '/../..' . '/rules/CodeQuality/Rector/For_/ForToForeachRector.php',
'Rector\\CodeQuality\\Rector\\Foreach_\\ForeachItemsAssignToEmptyArrayToAssignRector' => __DIR__ . '/../..' . '/rules/CodeQuality/Rector/Foreach_/ForeachItemsAssignToEmptyArrayToAssignRector.php',
'Rector\\CodeQuality\\Rector\\Foreach_\\ForeachToInArrayRector' => __DIR__ . '/../..' . '/rules/CodeQuality/Rector/Foreach_/ForeachToInArrayRector.php',
'Rector\\CodeQuality\\Rector\\Foreach_\\SimplifyForeachToArrayFilterRector' => __DIR__ . '/../..' . '/rules/CodeQuality/Rector/Foreach_/SimplifyForeachToArrayFilterRector.php',
@ -3127,9 +3124,9 @@ class ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit2f4ad052e54c0e0c4358aed15203c363::$classMap;
$loader->prefixLengthsPsr4 = ComposerStaticInit24fc5fd2b6218b109e4932a3a051625f::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit24fc5fd2b6218b109e4932a3a051625f::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit24fc5fd2b6218b109e4932a3a051625f::$classMap;
}, null, ClassLoader::class);
}