|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Rector\PHPUnit\CodeQuality\NodeAnalyser; |
| 6 | + |
| 7 | +use PhpParser\Node\ClosureUse; |
| 8 | +use PhpParser\Node\Expr\ArrowFunction; |
| 9 | +use PhpParser\Node\Expr\Variable; |
| 10 | +use Rector\NodeNameResolver\NodeNameResolver; |
| 11 | +use Rector\PhpParser\Node\BetterNodeFinder; |
| 12 | + |
| 13 | +final readonly class ClosureUsesResolver |
| 14 | +{ |
| 15 | + public function __construct( |
| 16 | + private BetterNodeFinder $betterNodeFinder, |
| 17 | + private NodeNameResolver $nodeNameResolver |
| 18 | + ) { |
| 19 | + |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * @return ClosureUse[] |
| 24 | + */ |
| 25 | + public function resolveFromArrowFunction(ArrowFunction $arrowFunction): array |
| 26 | + { |
| 27 | + // fill needed uses from arrow function to closure |
| 28 | + $arrowFunctionVariables = $this->betterNodeFinder->findInstancesOfScoped( |
| 29 | + $arrowFunction->getStmts(), |
| 30 | + Variable::class |
| 31 | + ); |
| 32 | + |
| 33 | + $paramNames = $this->resolveParamNames($arrowFunction); |
| 34 | + |
| 35 | + $externalVariableNames = []; |
| 36 | + |
| 37 | + foreach ($arrowFunctionVariables as $arrowFunctionVariable) { |
| 38 | + // skip those defined in params |
| 39 | + if ($this->nodeNameResolver->isNames($arrowFunctionVariable, $paramNames)) { |
| 40 | + continue; |
| 41 | + } |
| 42 | + |
| 43 | + $variableName = $this->nodeNameResolver->getName($arrowFunctionVariable); |
| 44 | + if (! is_string($variableName)) { |
| 45 | + continue; |
| 46 | + } |
| 47 | + |
| 48 | + $externalVariableNames[] = $variableName; |
| 49 | + } |
| 50 | + |
| 51 | + $externalVariableNames = array_unique($externalVariableNames); |
| 52 | + $externalVariableNames = array_diff($externalVariableNames, ['this']); |
| 53 | + |
| 54 | + $closureUses = []; |
| 55 | + foreach ($externalVariableNames as $externalVariableName) { |
| 56 | + $closureUses[] = new ClosureUse(new Variable($externalVariableName)); |
| 57 | + } |
| 58 | + |
| 59 | + return $closureUses; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @return string[] |
| 64 | + */ |
| 65 | + private function resolveParamNames(ArrowFunction $arrowFunction): array |
| 66 | + { |
| 67 | + $paramNames = []; |
| 68 | + foreach ($arrowFunction->getParams() as $param) { |
| 69 | + $paramNames[] = $this->nodeNameResolver->getName($param); |
| 70 | + } |
| 71 | + |
| 72 | + return $paramNames; |
| 73 | + } |
| 74 | +} |
0 commit comments