rector/rules/Naming/Matcher/ForeachMatcher.php

64 lines
2.0 KiB
PHP
Raw Normal View History

<?php
declare (strict_types=1);
namespace Rector\Naming\Matcher;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\Function_;
use Rector\Core\PhpParser\Node\BetterNodeFinder;
use Rector\Naming\ValueObject\VariableAndCallForeach;
use Rector\NodeNameResolver\NodeNameResolver;
2021-03-01 02:28:35 +01:00
final class ForeachMatcher
{
/**
* @readonly
* @var \Rector\NodeNameResolver\NodeNameResolver
*/
2021-03-01 02:28:35 +01:00
private $nodeNameResolver;
/**
* @readonly
* @var \Rector\Naming\Matcher\CallMatcher
2021-03-01 02:28:35 +01:00
*/
private $callMatcher;
/**
* @readonly
* @var \Rector\Core\PhpParser\Node\BetterNodeFinder
*/
private $betterNodeFinder;
public function __construct(NodeNameResolver $nodeNameResolver, \Rector\Naming\Matcher\CallMatcher $callMatcher, BetterNodeFinder $betterNodeFinder)
{
2021-03-01 02:28:35 +01:00
$this->nodeNameResolver = $nodeNameResolver;
$this->callMatcher = $callMatcher;
$this->betterNodeFinder = $betterNodeFinder;
2021-03-01 02:28:35 +01:00
}
public function match(Foreach_ $foreach) : ?VariableAndCallForeach
2021-03-01 02:28:35 +01:00
{
$call = $this->callMatcher->matchCall($foreach);
if ($call === null) {
return null;
}
if (!$foreach->valueVar instanceof Variable) {
2021-03-01 02:28:35 +01:00
return null;
}
$functionLike = $this->getFunctionLike($foreach);
if ($functionLike === null) {
return null;
}
$variableName = $this->nodeNameResolver->getName($foreach->valueVar);
if ($variableName === null) {
return null;
}
return new VariableAndCallForeach($foreach->valueVar, $call, $variableName, $functionLike);
}
/**
* @return \PhpParser\Node\Stmt\ClassMethod|\PhpParser\Node\Stmt\Function_|\PhpParser\Node\Expr\Closure|null
*/
private function getFunctionLike(Foreach_ $foreach)
{
return $this->betterNodeFinder->findParentByTypes($foreach, [Closure::class, ClassMethod::class, Function_::class]);
}
}