foreach ($arguments as $start => $end) { $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); $content = $info->getName(); if (isset($imports[$content])) { unset($imports[$content]); if (0 === \count($imports)) { return $imports; } } } return $imports; } /** * @param int $index * * @return false|int */ private function getLambdaUseIndex(Tokens $tokens, $index) { if (!$tokens[$index]->isGivenKind(T_FUNCTION) || !$this->tokensAnalyzer->isLambda($index)) { return false; } $lambdaUseIndex = $tokens->getNextMeaningfulToken($index); // we are @ '(' or '&' after this if ($tokens[$lambdaUseIndex]->isGivenKind(CT::T_RETURN_REF)) { $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); } $lambdaUseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseIndex); // we are @ ')' after this $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); if (!$tokens[$lambdaUseIndex]->isGivenKind(CT::T_USE_LAMBDA)) { return false; } return $lambdaUseIndex; } /** * @return array */ private function filterArguments(Tokens $tokens, array $arguments) { $imports = []; foreach ($arguments as $start => $end) { $info = $this->argumentsAnalyzer->getArgumentInfo($tokens, $start, $end); $argument = $info->getNameIndex(); if ($tokens[$tokens->getPrevMeaningfulToken($argument)]->equals('&')) { continue; } $argumentCandidate = $tokens[$argument]; if ('$this' === $argumentCandidate->getContent()) { continue; } if ($this->tokensAnalyzer->isSuperGlobal($argument)) { continue; } $imports[$argumentCandidate->getContent()] = $argument; } return $imports; } private function clearImports(Tokens $tokens, array $imports) { foreach ($imports as $content => $removeIndex) { $tokens->clearTokenAndMergeSurroundingWhitespace($removeIndex); $previousRemoveIndex = $tokens->getPrevMeaningfulToken($removeIndex); if ($tokens[$previousRemoveIndex]->equals(',')) { $tokens->clearTokenAndMergeSurroundingWhitespace($previousRemoveIndex); } elseif ($tokens[$previousRemoveIndex]->equals('(')) { $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($removeIndex)); // next is always ',' here } } } /** * Remove `use` and all imported variables. * * @param int $lambdaUseIndex * @param int $lambdaUseCloseBraceIndex */ private function clearImportsAndUse(Tokens $tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex) { for ($i = $lambdaUseCloseBraceIndex; $i >= $lambdaUseIndex; --$i) { if ($tokens[$i]->isComment()) { continue; } if ($tokens[$i]->isWhitespace()) { $previousIndex = $tokens->getPrevNonWhitespace($i); if ($tokens[$previousIndex]->isComment()) { continue; } } $tokens->clearTokenAndMergeSurroundingWhitespace($i); } } }