Skip to content

Commit

Permalink
Call insertSlices only once
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbalandan committed Oct 6, 2021
1 parent fad7768 commit 05b95ef
Showing 1 changed file with 28 additions and 10 deletions.
38 changes: 28 additions & 10 deletions src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php
Expand Up @@ -83,12 +83,16 @@ public function isRisky(): bool
*/
protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
{
$functionsAnalyser = new FunctionsAnalyzer();
$indicesToFix = [];
$tokenSlices = [];

for ($index = $tokens->count() - 1; $index > 0; --$index) {
if (!$tokens[$index]->equals([T_STRING, 'get_class'], false)) {
continue;
}

if (!(new FunctionsAnalyzer())->isGlobalFunctionCall($tokens, $index)) {
if (!$functionsAnalyser->isGlobalFunctionCall($tokens, $index)) {
continue;
}

Expand Down Expand Up @@ -125,18 +129,19 @@ protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
continue;
}

$this->fixGetClassCall($tokens, $index, $braceOpenIndex, $braceCloseIndex, current($variableTokensIndices));
$indicesToFix[$index] = [$braceOpenIndex, $braceCloseIndex, current($variableTokensIndices)];
}

foreach ($indicesToFix as $index => $getClassInfo) {
$tokenSlices += $this->getReplacementTokenSlices($tokens, $index, $getClassInfo[2]);
$this->fixSurroundingTokens($tokens, $index, $getClassInfo[0], $getClassInfo[1]);
}

$tokens->insertSlices($tokenSlices);
}

private function fixGetClassCall(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex, int $variableIndex): void
private function fixSurroundingTokens(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex): void
{
$replacements = [
new Token([T_VARIABLE, $tokens[$variableIndex]->getContent()]),
new Token([T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
];

for ($i = $braceOpenIndex; $i <= $braceCloseIndex; ++$i) {
if ($tokens[$i]->isGivenKind([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT])) {
continue;
Expand All @@ -152,6 +157,19 @@ private function fixGetClassCall(Tokens $tokens, int $index, int $braceOpenIndex
}

$tokens->clearAt($index);
$tokens->insertSlices([$index => $replacements]);
}

/**
* @return array<int, array<int, Token>>
*/
private function getReplacementTokenSlices(Tokens $tokens, int $index, int $variableTokenIndex): array
{
return [
$index => [
new Token([T_VARIABLE, $tokens[$variableTokenIndex]->getContent()]),
new Token([T_DOUBLE_COLON, '::']),
new Token([CT::T_CLASS_CONSTANT, 'class']),
],
];
}
}

0 comments on commit 05b95ef

Please sign in to comment.