private function fixMissingControlBraces(Tokens $tokens)
{
$controlTokens = $this->getControlTokens();
for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
$token = $tokens[$index];
if (!$token->isGivenKind($controlTokens)) {
continue;
}
$parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index);
$tokenAfterParenthesis = $tokens[$tokens->getNextMeaningfulToken($parenthesisEndIndex)];
// if Token after parenthesis is { then we do not need to insert brace, but to fix whitespace before it
if ($tokenAfterParenthesis->equals('{')) {
$tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' ');
continue;
}
// do not add braces for cases:
// - structure without block, e.g. while ($iter->next());
// - structure with block, e.g. while ($i) {...}, while ($i) : {...} endwhile;
if ($tokenAfterParenthesis->equalsAny(array(';', '{', ':'))) {
continue;
}
$statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex);
// insert closing brace
$tokens->insertAt($statementEndIndex + 1, array(new Token(array(T_WHITESPACE, ' ')), new Token('}')));
// insert missing `;` if needed
if (!$tokens[$statementEndIndex]->equalsAny(array(';', '}'))) {
$tokens->insertAt($statementEndIndex + 1, new Token(';'));
}
// insert opening brace
$tokens->insertAt($parenthesisEndIndex + 1, new Token('{'));
$tokens->ensureWhitespaceAtIndex($parenthesisEndIndex + 1, 0, ' ');
}
}