nodeFinder = $nodeFinder; $this->stmtsManipulator = $stmtsManipulator; } public function getRuleDefinition() : RuleDefinition { return new RuleDefinition('Remove unused key in foreach', [new CodeSample(<<<'CODE_SAMPLE' $items = []; foreach ($items as $key => $value) { $result = $value; } CODE_SAMPLE , <<<'CODE_SAMPLE' $items = []; foreach ($items as $value) { $result = $value; } CODE_SAMPLE )]); } /** * @return array> */ public function getNodeTypes() : array { return [StmtsAwareInterface::class]; } /** * @param StmtsAwareInterface $node */ public function refactor(Node $node) : ?Node { if ($node->stmts === null) { return null; } $hasChanged = \false; foreach ($node->stmts as $key => $stmt) { if (!$stmt instanceof Foreach_) { continue; } if (!$stmt->keyVar instanceof Variable) { continue; } $keyVar = $stmt->keyVar; $isNodeUsed = (bool) $this->nodeFinder->findFirst($stmt->stmts, function (Node $node) use($keyVar) : bool { return $this->nodeComparator->areNodesEqual($node, $keyVar); }); if ($isNodeUsed) { continue; } if ($this->stmtsManipulator->isVariableUsedInNextStmt($node, $key + 1, (string) $this->getName($keyVar))) { continue; } $stmt->keyVar = null; $hasChanged = \true; } if ($hasChanged) { return $node; } return null; } }