2021-02-23 02:25:34 +01:00
|
|
|
<?php
|
|
|
|
|
2021-05-09 20:15:43 +00:00
|
|
|
declare (strict_types=1);
|
2022-06-06 17:12:56 +00:00
|
|
|
namespace Rector\CodeQuality\NodeAnalyzer;
|
2021-02-23 02:25:34 +01:00
|
|
|
|
2022-06-06 17:12:56 +00:00
|
|
|
use PhpParser\Node\Expr;
|
|
|
|
use PhpParser\Node\Expr\ArrayDimFetch;
|
|
|
|
use PhpParser\Node\Expr\Assign;
|
|
|
|
use PhpParser\Node\Stmt\Expression;
|
|
|
|
use PhpParser\Node\Stmt\Foreach_;
|
|
|
|
use Rector\Core\PhpParser\Comparing\NodeComparator;
|
2021-02-23 02:25:34 +01:00
|
|
|
final class ForeachAnalyzer
|
|
|
|
{
|
|
|
|
/**
|
2023-06-11 23:01:39 +00:00
|
|
|
* @readonly
|
2021-05-10 23:39:21 +00:00
|
|
|
* @var \Rector\Core\PhpParser\Comparing\NodeComparator
|
2021-02-23 02:25:34 +01:00
|
|
|
*/
|
|
|
|
private $nodeComparator;
|
2023-07-09 11:25:27 +00:00
|
|
|
public function __construct(NodeComparator $nodeComparator)
|
2021-05-09 20:15:43 +00:00
|
|
|
{
|
2021-02-23 02:25:34 +01:00
|
|
|
$this->nodeComparator = $nodeComparator;
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Matches$
|
|
|
|
* foreach ($values as $value) {
|
|
|
|
* <$assigns[]> = $value;
|
|
|
|
* }
|
|
|
|
*/
|
2022-06-07 08:22:29 +00:00
|
|
|
public function matchAssignItemsOnlyForeachArrayVariable(Foreach_ $foreach) : ?Expr
|
2021-02-23 02:25:34 +01:00
|
|
|
{
|
2021-05-09 20:15:43 +00:00
|
|
|
if (\count($foreach->stmts) !== 1) {
|
2021-02-23 02:25:34 +01:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
$onlyStatement = $foreach->stmts[0];
|
2022-06-07 08:22:29 +00:00
|
|
|
if ($onlyStatement instanceof Expression) {
|
2021-02-23 02:25:34 +01:00
|
|
|
$onlyStatement = $onlyStatement->expr;
|
|
|
|
}
|
2022-06-07 08:22:29 +00:00
|
|
|
if (!$onlyStatement instanceof Assign) {
|
2021-02-23 02:25:34 +01:00
|
|
|
return null;
|
|
|
|
}
|
2022-06-07 08:22:29 +00:00
|
|
|
if (!$onlyStatement->var instanceof ArrayDimFetch) {
|
2021-02-23 02:25:34 +01:00
|
|
|
return null;
|
|
|
|
}
|
2023-03-23 23:21:34 +00:00
|
|
|
if ($onlyStatement->var->dim instanceof Expr) {
|
2021-02-23 02:25:34 +01:00
|
|
|
return null;
|
|
|
|
}
|
2021-05-09 20:15:43 +00:00
|
|
|
if (!$this->nodeComparator->areNodesEqual($foreach->valueVar, $onlyStatement->expr)) {
|
2021-02-23 02:25:34 +01:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
return $onlyStatement->var->var;
|
|
|
|
}
|
|
|
|
}
|