insertAt() public method

Insert instances of Token inside collection.
public insertAt ( integer $index, Tokens | PhpCsFixer\Tokenizer\Token[] | PhpCsFixer\Tokenizer\Token $items )
$index integer start inserting index
$items Tokens | PhpCsFixer\Tokenizer\Token[] | PhpCsFixer\Tokenizer\Token instances of Token to insert
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     for ($index = $tokens->count() - 1; $index >= 0; --$index) {
         $token = $tokens[$index];
         if ($token->equals('.')) {
             if (!$tokens[$index + 1]->isWhitespace()) {
                 $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
             }
             if (!$tokens[$index - 1]->isWhitespace()) {
                 $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $tokensAnalyzer = new TokensAnalyzer($tokens);
     for ($index = $tokens->count() - 1; $index >= 0; --$index) {
         $token = $tokens[$index];
         if ($tokensAnalyzer->isUnaryPredecessorOperator($index) && $token->equals('!')) {
             if (!$tokens[$index + 1]->isWhitespace()) {
                 $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
             }
             if (!$tokens[$index - 1]->isWhitespace()) {
                 $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $tokensAnalyzer = new TokensAnalyzer($tokens);
     for ($index = $tokens->count() - 1; $index >= 0; --$index) {
         if (!$tokensAnalyzer->isBinaryOperator($index)) {
             continue;
         }
         if (!$tokens[$index + 1]->isWhitespace()) {
             $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
         }
         if (!$tokens[$index - 1]->isWhitespace()) {
             $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $lineEnding = $this->whitespacesConfig->getLineEnding();
     for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
         $token = $tokens[$index];
         if (!$token->isGivenKind(T_RETURN)) {
             continue;
         }
         $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];
         if (!$prevNonWhitespaceToken->equalsAny(array(';', '}'))) {
             continue;
         }
         $prevToken = $tokens[$index - 1];
         if ($prevToken->isWhitespace()) {
             $parts = explode("\n", $prevToken->getContent());
             $countParts = count($parts);
             if (1 === $countParts) {
                 $prevToken->setContent(rtrim($prevToken->getContent(), " \t") . $lineEnding . $lineEnding);
             } elseif (count($parts) <= 2) {
                 $prevToken->setContent($lineEnding . $prevToken->getContent());
             }
         } else {
             $tokens->insertAt($index, new Token(array(T_WHITESPACE, $lineEnding . $lineEnding)));
             ++$index;
             ++$limit;
         }
     }
 }
Exemplo n.º 5
0
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     for ($index = $tokens->count() - 1; $index >= 0; --$index) {
         $token = $tokens[$index];
         if (!$token->isGivenKind(T_FUNCTION)) {
             continue;
         }
         $startParenthesisIndex = $tokens->getNextTokenOfKind($index, array('('));
         $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex);
         for ($iter = $endParenthesisIndex - 1; $iter > $startParenthesisIndex; --$iter) {
             if (!$tokens[$iter]->isGivenKind(T_VARIABLE)) {
                 continue;
             }
             // skip ... before $variable for variadic parameter
             if (defined('T_ELLIPSIS')) {
                 $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($iter);
                 if ($tokens[$prevNonWhitespaceIndex]->isGivenKind(T_ELLIPSIS)) {
                     $iter = $prevNonWhitespaceIndex;
                 }
             }
             // skip & before $variable for parameter passed by reference
             $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($iter);
             if ($tokens[$prevNonWhitespaceIndex]->equals('&')) {
                 $iter = $prevNonWhitespaceIndex;
             }
             if (!$tokens[$iter - 1]->equalsAny(array(array(T_WHITESPACE), array(T_COMMENT), array(T_DOC_COMMENT), '(', ','))) {
                 $tokens->insertAt($iter, new Token(array(T_WHITESPACE, ' ')));
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     for ($index = $tokens->count() - 3; $index > 0; --$index) {
         $token = $tokens[$index];
         if (!$token->isGivenKind(T_NEW)) {
             continue;
         }
         $nextIndex = $tokens->getNextTokenOfKind($index, array(':', ';', ',', '(', ')', '[', ']', array(T_CLOSE_TAG), array(CT_ARRAY_SQUARE_BRACE_OPEN), array(CT_ARRAY_SQUARE_BRACE_CLOSE), array(CT_BRACE_CLASS_INSTANTIATION_OPEN), array(CT_BRACE_CLASS_INSTANTIATION_CLOSE)));
         $nextToken = $tokens[$nextIndex];
         // entrance into array index syntax - need to look for exit
         while ($nextToken->equals('[')) {
             $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $nextIndex) + 1;
             $nextToken = $tokens[$nextIndex];
         }
         // new statement has a gap in it - advance to the next token
         if ($nextToken->isWhitespace()) {
             $nextIndex = $tokens->getNextNonWhitespace($nextIndex);
             $nextToken = $tokens[$nextIndex];
         }
         // new statement with () - nothing to do
         if ($nextToken->equals('(')) {
             continue;
         }
         $meaningBeforeNextIndex = $tokens->getPrevMeaningfulToken($nextIndex);
         $tokens->insertAt($meaningBeforeNextIndex + 1, array(new Token('('), new Token(')')));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $tokensAnalyzer = new TokensAnalyzer($tokens);
     foreach ($tokensAnalyzer->getImportUseIndexes() as $index) {
         $indent = '';
         // if previous line ends with comment and current line starts with whitespace, use current indent
         if ($tokens[$index - 1]->isWhitespace(" \t") && $tokens[$index - 2]->isGivenKind(T_COMMENT)) {
             $indent = $tokens[$index - 1]->getContent();
         } elseif ($tokens[$index - 1]->isWhitespace()) {
             $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]);
         }
         $newline = "\n";
         // Handle insert index for inline T_COMMENT with whitespace after semicolon
         $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
         $insertIndex = $semicolonIndex + 1;
         if ($tokens[$insertIndex]->isWhitespace(" \t") && $tokens[$insertIndex + 1]->isComment()) {
             ++$insertIndex;
         }
         // Increment insert index for inline T_COMMENT or T_DOC_COMMENT
         if ($tokens[$insertIndex]->isComment()) {
             ++$insertIndex;
         }
         $afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex);
         if (!$tokens[$afterSemicolon]->isGivenKind(T_USE)) {
             $newline .= "\n";
         }
         if ($tokens[$insertIndex]->isWhitespace()) {
             $nextToken = $tokens[$insertIndex];
             $nextToken->setContent($newline . $indent . ltrim($nextToken->getContent()));
         } elseif ($newline && $indent) {
             $tokens->insertAt($insertIndex, new Token(array(T_WHITESPACE, $newline . $indent)));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $lineEnding = $this->whitespacesConfig->getLineEnding();
     // ignore files with short open tag and ignore non-monolithic files
     if (!$tokens[0]->isGivenKind(T_OPEN_TAG) || !$tokens->isMonolithicPhp()) {
         return;
     }
     $newlineFound = false;
     /** @var Token $token */
     foreach ($tokens as $token) {
         if ($token->isWhitespace() && false !== strpos($token->getContent(), "\n")) {
             $newlineFound = true;
             break;
         }
     }
     // ignore one-line files
     if (!$newlineFound) {
         return;
     }
     $token = $tokens[0];
     if (false === strpos($token->getContent(), "\n")) {
         $token->setContent(rtrim($token->getContent()) . $lineEnding);
     }
     if (!$tokens[1]->isWhitespace() && false === strpos($tokens[1]->getContent(), "\n")) {
         $tokens->insertAt(1, new Token(array(T_WHITESPACE, $lineEnding)));
     }
 }
Exemplo n.º 9
0
 private function clearIncludies(Tokens $tokens, array $includies)
 {
     foreach (array_reverse($includies) as $includy) {
         if ($includy['end']) {
             $tokens->removeLeadingWhitespace($includy['end']);
         }
         $braces = $includy['braces'];
         if ($braces) {
             $nextToken = $tokens[$tokens->getNextMeaningfulToken($braces['close'])];
             if ($nextToken->equals(';')) {
                 $tokens->removeLeadingWhitespace($braces['open']);
                 $tokens->removeTrailingWhitespace($braces['open']);
                 $tokens->removeLeadingWhitespace($braces['close']);
                 $tokens->removeTrailingWhitespace($braces['close']);
                 $tokens[$braces['open']] = new Token(array(T_WHITESPACE, ' '));
                 $tokens[$braces['close']]->clear();
             }
         }
         $nextIndex = $includy['begin'] + 1;
         $nextToken = $tokens[$nextIndex];
         while ($nextToken->isEmpty()) {
             $nextToken = $tokens[++$nextIndex];
         }
         if ($nextToken->isWhitespace()) {
             $nextToken->setContent(' ');
         } elseif ($braces || $tokens[$nextIndex]->isGivenKind(array(T_VARIABLE, T_CONSTANT_ENCAPSED_STRING, T_COMMENT))) {
             $tokens->insertAt($includy['begin'] + 1, new Token(array(T_WHITESPACE, ' ')));
         }
     }
 }
 private function ensureWhitespaceExistence(Tokens $tokens, $index, $after)
 {
     $indexChange = $after ? 0 : 1;
     $token = $tokens[$index];
     if ($token->isWhitespace()) {
         return;
     }
     $tokens->insertAt($index + $indexChange, new Token(array(T_WHITESPACE, ' ')));
 }
Exemplo n.º 11
0
 private function fixShortCastToBoolCast(Tokens $tokens, $start, $end)
 {
     for (; $start <= $end; ++$start) {
         if (!$tokens[$start]->isComment() && !($tokens[$start]->isWhitespace() && $tokens[$start - 1]->isComment())) {
             $tokens[$start]->clear();
         }
     }
     $tokens->insertAt($start, new Token(array(T_BOOL_CAST, '(bool)')));
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $ending = $this->whitespacesConfig->getLineEnding();
     $tokensAnalyzer = new TokensAnalyzer($tokens);
     foreach ($tokensAnalyzer->getImportUseIndexes() as $index) {
         $indent = '';
         // if previous line ends with comment and current line starts with whitespace, use current indent
         if ($tokens[$index - 1]->isWhitespace(" \t") && $tokens[$index - 2]->isGivenKind(T_COMMENT)) {
             $indent = $tokens[$index - 1]->getContent();
         } elseif ($tokens[$index - 1]->isWhitespace()) {
             $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$index - 1]);
         }
         $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', array(T_CLOSE_TAG)));
         // Handle insert index for inline T_COMMENT with whitespace after semicolon
         $insertIndex = $semicolonIndex;
         if ($tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG)) {
             if ($tokens[$insertIndex - 1]->isWhitespace()) {
                 --$insertIndex;
             }
             $tokens->insertAt($insertIndex, new Token(';'));
         }
         if ($semicolonIndex === count($tokens) - 1) {
             $tokens->insertAt($insertIndex + 1, new Token(array(T_WHITESPACE, $ending . $ending . $indent)));
         } else {
             $newline = $ending;
             $tokens[$semicolonIndex]->isGivenKind(T_CLOSE_TAG) ? --$insertIndex : ++$insertIndex;
             if ($tokens[$insertIndex]->isWhitespace(" \t") && $tokens[$insertIndex + 1]->isComment()) {
                 ++$insertIndex;
             }
             // Increment insert index for inline T_COMMENT or T_DOC_COMMENT
             if ($tokens[$insertIndex]->isComment()) {
                 ++$insertIndex;
             }
             $afterSemicolon = $tokens->getNextMeaningfulToken($semicolonIndex);
             if (null === $afterSemicolon || !$tokens[$afterSemicolon]->isGivenKind(T_USE)) {
                 $newline .= $ending;
             }
             if ($tokens[$insertIndex]->isWhitespace()) {
                 $nextToken = $tokens[$insertIndex];
                 $nextMeaningfulAfterUseIndex = $tokens->getNextMeaningfulToken($insertIndex);
                 if (null !== $nextMeaningfulAfterUseIndex && $tokens[$nextMeaningfulAfterUseIndex]->isGivenKind(T_USE)) {
                     if (substr_count($nextToken->getContent(), "\n") < 2) {
                         $nextToken->setContent($newline . $indent . ltrim($nextToken->getContent()));
                     }
                 } else {
                     $nextToken->setContent($newline . $indent . ltrim($nextToken->getContent()));
                 }
             } else {
                 $tokens->insertAt($insertIndex, new Token(array(T_WHITESPACE, $newline . $indent)));
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $tokensAnalyzer = new TokensAnalyzer($tokens);
     for ($index = $tokens->count() - 1; $index >= 0; --$index) {
         if (!$tokensAnalyzer->isBinaryOperator($index)) {
             continue;
         }
         // skip `declare(foo ==bar)`
         $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($index);
         if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_STRING)) {
             $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
             if ($tokens[$prevMeaningfulIndex]->equals('(')) {
                 $prevMeaningfulIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulIndex);
                 if ($tokens[$prevMeaningfulIndex]->isGivenKind(T_DECLARE)) {
                     continue;
                 }
             }
         }
         // fix white space after operator
         if ($tokens[$index + 1]->isWhitespace()) {
             $content = $tokens[$index + 1]->getContent();
             if (' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) {
                 $tokens[$index + 1]->setContent(' ');
             }
         } else {
             $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
         }
         // fix white space before operator
         if ($tokens[$index - 1]->isWhitespace()) {
             $content = $tokens[$index - 1]->getContent();
             if (' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) {
                 $tokens[$index - 1]->setContent(' ');
             }
         } else {
             $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
         }
         --$index;
         // skip check for binary operator on the whitespace token that is fixed.
     }
 }
Exemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
         $token = $tokens[$index];
         if (!$token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) {
             continue;
         }
         $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index);
         $tokens->overrideAt($index, '(');
         $tokens->overrideAt($closeIndex, ')');
         $tokens->insertAt($index, new Token(array(T_ARRAY, 'array')));
     }
 }
 private function fixWhiteSpaceAroundOperator(Tokens $tokens, $index)
 {
     // do not change the alignment of `=>` or `=`, see `(un)align_double_arrow`, `(un)align_equals`
     $preserveAlignment = $tokens[$index]->isGivenKind(T_DOUBLE_ARROW) || $tokens[$index]->equals('=');
     // fix white space after operator
     if ($tokens[$index + 1]->isWhitespace()) {
         $content = $tokens[$index + 1]->getContent();
         if (!$preserveAlignment && ' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) {
             $tokens[$index + 1]->setContent(' ');
         }
     } else {
         $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
     }
     // fix white space before operator
     if ($tokens[$index - 1]->isWhitespace()) {
         $content = $tokens[$index - 1]->getContent();
         if (!$preserveAlignment && ' ' !== $content && false === strpos($content, "\n") && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) {
             $tokens[$index - 1]->setContent(' ');
         }
     } else {
         $tokens->insertAt($index, new Token(array(T_WHITESPACE, ' ')));
     }
 }
Exemplo n.º 16
0
 /**
  * @param Tokens $tokens
  * @param int    $index  Index of concat token
  * @param int    $offset 1 or -1
  */
 private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, $index, $offset)
 {
     $offsetIndex = $index + $offset;
     if (!$tokens[$offsetIndex]->isWhitespace()) {
         $tokens->insertAt($index + (1 === $offset ?: 0), new Token(array(T_WHITESPACE, ' ')));
         return;
     }
     if (false !== strpos($tokens[$offsetIndex]->getContent(), "\n")) {
         return;
     }
     if ($tokens[$index + $offset * 2]->isComment()) {
         return;
     }
     $tokens[$offsetIndex]->setContent(' ');
 }
Exemplo n.º 17
0
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     static $insideCastSpaceReplaceMap = array(' ' => '', "\t" => '', "\n" => '', "\r" => '', "" => '', "\v" => '');
     foreach ($tokens as $index => $token) {
         if ($token->isCast()) {
             $token->setContent(strtr($token->getContent(), $insideCastSpaceReplaceMap));
             // force single whitespace after cast token:
             if ($tokens[$index + 1]->isWhitespace(" \t")) {
                 // - if next token is whitespaces that contains only spaces and tabs - override next token with single space
                 $tokens[$index + 1]->setContent(' ');
             } elseif (!$tokens[$index + 1]->isWhitespace()) {
                 // - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token
                 $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, ' ')));
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $count = $tokens->count();
     if (0 === $count) {
         return;
     }
     $token = $tokens[$count - 1];
     if ($token->isGivenKind(array(T_INLINE_HTML, T_CLOSE_TAG, T_OPEN_TAG))) {
         return;
     }
     if ($token->isWhitespace()) {
         $lineBreak = false === strrpos($token->getContent(), "\r") ? "\n" : "\r\n";
         $token->setContent($lineBreak);
     } else {
         $tokens->insertAt($count, new Token(array(T_WHITESPACE, "\n")));
     }
 }
Exemplo n.º 19
0
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     if (!$tokens->isMonolithicPhp()) {
         return;
     }
     $closeTags = $tokens->findGivenKind(T_CLOSE_TAG);
     if (empty($closeTags)) {
         return;
     }
     list($index, $token) = each($closeTags);
     $tokens->removeLeadingWhitespace($index);
     $token->clear();
     $prevIndex = $tokens->getPrevNonWhitespace($index);
     $prevToken = $tokens[$prevIndex];
     if (!$prevToken->equalsAny(array(';', '}'))) {
         $tokens->insertAt($prevIndex + 1, new Token(';'));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function process(Tokens $tokens, Token $token, $index)
 {
     if (!$token->isComment()) {
         return;
     }
     $content = $token->getContent();
     $trimmedContent = rtrim($content);
     // nothing trimmed, nothing to do
     if ($content === $trimmedContent) {
         return;
     }
     $whitespaces = substr($content, strlen($trimmedContent));
     $token->setContent($trimmedContent);
     if (isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace()) {
         $tokens[$index + 1]->setContent($whitespaces . $tokens[$index + 1]->getContent());
     } else {
         $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, $whitespaces)));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     for ($index = $tokens->count() - 1; $index >= 0; --$index) {
         $token = $tokens[$index];
         if (!$token->isGivenKind(T_NAMESPACE)) {
             continue;
         }
         $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{'));
         $semicolonToken = $tokens[$semicolonIndex];
         if (!isset($tokens[$semicolonIndex + 1]) || !$semicolonToken->equals(';')) {
             continue;
         }
         $nextToken = $tokens[$semicolonIndex + 1];
         if (!$nextToken->isWhitespace()) {
             $tokens->insertAt($semicolonIndex + 1, new Token(array(T_WHITESPACE, "\n\n")));
         } else {
             $nextToken->setContent("\n\n" . ltrim($nextToken->getContent()));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     for ($index = $tokens->count() - 1; $index >= 0; --$index) {
         $token = $tokens[$index];
         if (!$token->equals(array(T_STRING, 'trigger_error'), false)) {
             continue;
         }
         $start = $index;
         $prev = $tokens->getPrevMeaningfulToken($start);
         if ($tokens[$prev]->isGivenKind(T_NS_SEPARATOR)) {
             $start = $prev;
             $prev = $tokens->getPrevMeaningfulToken($start);
         }
         if ($tokens[$prev]->isGivenKind(T_STRING) || $tokens[$prev]->equals('@')) {
             continue;
         }
         $end = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($index, array(T_STRING, '(')));
         if ($tokens[$tokens->getPrevMeaningfulToken($end)]->equals(array(T_STRING, 'E_USER_DEPRECATED'))) {
             $tokens->insertAt($start, new Token('@'));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $ending = $this->whitespacesConfig->getLineEnding();
     $lastIndex = $tokens->count() - 1;
     for ($index = $lastIndex; $index >= 0; --$index) {
         $token = $tokens[$index];
         if (!$token->isGivenKind(T_NAMESPACE)) {
             continue;
         }
         $semicolonIndex = $tokens->getNextTokenOfKind($index, array(';', '{', array(T_CLOSE_TAG)));
         $semicolonToken = $tokens[$semicolonIndex];
         if (!isset($tokens[$semicolonIndex + 1]) || !$semicolonToken->equals(';')) {
             continue;
         }
         $nextIndex = $semicolonIndex + 1;
         $nextToken = $tokens[$nextIndex];
         if (!$nextToken->isWhitespace()) {
             $tokens->insertAt($semicolonIndex + 1, new Token(array(T_WHITESPACE, $ending . $ending)));
         } else {
             $nextToken->setContent(($nextIndex === $lastIndex ? $ending : $ending . $ending) . ltrim($nextToken->getContent()));
         }
     }
 }
Exemplo n.º 24
0
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     static $nextTokenKinds = null;
     if (null === $nextTokenKinds) {
         $nextTokenKinds = array('?', ';', ',', '(', ')', '[', ']', ':', '<', '>', '+', '-', '*', '/', '%', '&', '^', '|', array(T_IS_SMALLER_OR_EQUAL), array(T_IS_GREATER_OR_EQUAL), array(T_IS_EQUAL), array(T_IS_NOT_EQUAL), array(T_IS_IDENTICAL), array(T_IS_NOT_IDENTICAL), array(T_CLOSE_TAG), array(T_LOGICAL_AND), array(T_LOGICAL_OR), array(T_LOGICAL_XOR), array(T_BOOLEAN_AND), array(T_BOOLEAN_OR), array(T_INC), array(T_DEC), array(T_SL), array(T_SR), array(T_INSTANCEOF), array(T_AS), array(T_DOUBLE_ARROW), array(CT_ARRAY_SQUARE_BRACE_OPEN), array(CT_ARRAY_SQUARE_BRACE_CLOSE), array(CT_BRACE_CLASS_INSTANTIATION_OPEN), array(CT_BRACE_CLASS_INSTANTIATION_CLOSE));
         if (defined('T_POW')) {
             $nextTokenKinds[] = array(T_POW);
         }
         if (defined('T_SPACESHIP')) {
             $nextTokenKinds[] = array(T_SPACESHIP);
         }
     }
     for ($index = $tokens->count() - 3; $index > 0; --$index) {
         $token = $tokens[$index];
         if (!$token->isGivenKind(T_NEW)) {
             continue;
         }
         $nextIndex = $tokens->getNextTokenOfKind($index, $nextTokenKinds);
         $nextToken = $tokens[$nextIndex];
         // entrance into array index syntax - need to look for exit
         while ($nextToken->equals('[')) {
             $nextIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $nextIndex) + 1;
             $nextToken = $tokens[$nextIndex];
         }
         // new statement has a gap in it - advance to the next token
         if ($nextToken->isWhitespace()) {
             $nextIndex = $tokens->getNextNonWhitespace($nextIndex);
             $nextToken = $tokens[$nextIndex];
         }
         // new statement with () - nothing to do
         if ($nextToken->equals('(')) {
             continue;
         }
         $meaningBeforeNextIndex = $tokens->getPrevMeaningfulToken($nextIndex);
         $tokens->insertAt($meaningBeforeNextIndex + 1, array(new Token('('), new Token(')')));
     }
 }
 private function fixArray(Tokens $tokens, $index)
 {
     $tokensAnalyzer = new TokensAnalyzer($tokens);
     if (!$tokensAnalyzer->isArrayMultiLine($index)) {
         return;
     }
     $startIndex = $index;
     if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
         $startIndex = $tokens->getNextTokenOfKind($startIndex, array('('));
         $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
     } else {
         $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex);
     }
     $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex);
     $beforeEndToken = $tokens[$beforeEndIndex];
     // if there is some item between braces then add `,` after it
     if ($startIndex !== $beforeEndIndex && !$beforeEndToken->equalsAny(array(',', array(T_END_HEREDOC)))) {
         $tokens->insertAt($beforeEndIndex + 1, new Token(','));
         $endToken = $tokens[$endIndex];
         if (!$endToken->isComment() && !$endToken->isWhitespace()) {
             $tokens->ensureWhitespaceAtIndex($endIndex, 1, ' ');
         }
     }
 }
 /**
  * @param Tokens $tokens
  * @param int    $index
  * @param bool   $after
  */
 private function ensureWhitespaceExistence(Tokens $tokens, $index, $after)
 {
     if ($tokens[$index]->isWhitespace()) {
         if (false === strpos($tokens[$index]->getContent(), "\n") && !$tokens[$index - 1]->isComment()) {
             $tokens[$index]->setContent(' ');
         }
         return;
     }
     $indexChange = $after ? 0 : 1;
     $tokens->insertAt($index + $indexChange, new Token(array(T_WHITESPACE, ' ')));
 }
Exemplo n.º 27
0
 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $namespace = false;
     $namespaceIndex = 0;
     $namespaceEndIndex = 0;
     $classyName = null;
     $classyIndex = 0;
     foreach ($tokens as $index => $token) {
         if ($token->isGivenKind(T_NAMESPACE)) {
             if (false !== $namespace) {
                 return;
             }
             $namespaceIndex = $tokens->getNextMeaningfulToken($index);
             $namespaceEndIndex = $tokens->getNextTokenOfKind($index, array(';'));
             $namespace = trim($tokens->generatePartialCode($namespaceIndex, $namespaceEndIndex - 1));
         } elseif ($token->isClassy()) {
             if (null !== $classyName) {
                 return;
             }
             $classyIndex = $tokens->getNextMeaningfulToken($index);
             $classyName = $tokens[$classyIndex]->getContent();
         }
     }
     if (null === $classyName) {
         return;
     }
     if (false !== $namespace) {
         $normNamespace = str_replace('\\', '/', $namespace);
         $path = str_replace('\\', '/', $file->getRealPath());
         $dir = dirname($path);
         if (isset($this->configuration['dir'])) {
             $dir = substr($dir, strlen(realpath($this->configuration['dir'])) + 1);
             if (strlen($normNamespace) > strlen($dir)) {
                 if ('' !== $dir) {
                     $normNamespace = substr($normNamespace, -strlen($dir));
                 } else {
                     $normNamespace = '';
                 }
             }
         }
         $dir = substr($dir, -strlen($normNamespace));
         if (false === $dir) {
             $dir = '';
         }
         $filename = basename($path, '.php');
         if ($classyName !== $filename) {
             $tokens[$classyIndex]->setContent($filename);
         }
         if ($normNamespace !== $dir && strtolower($normNamespace) === strtolower($dir)) {
             for ($i = $namespaceIndex; $i <= $namespaceEndIndex; ++$i) {
                 $tokens[$i]->clear();
             }
             $namespace = substr($namespace, 0, -strlen($dir)) . str_replace('/', '\\', $dir);
             $newNamespace = Tokens::fromCode('<?php namespace ' . $namespace . ';');
             $newNamespace[0]->clear();
             $newNamespace[1]->clear();
             $newNamespace[2]->clear();
             $newNamespace->clearEmptyTokens();
             $tokens->insertAt($namespaceIndex, $newNamespace);
         }
     } else {
         $normClass = str_replace('_', '/', $classyName);
         $path = str_replace('\\', '/', $file->getRealPath());
         $filename = substr($path, -strlen($normClass) - 4, -4);
         if ($normClass !== $filename && strtolower($normClass) === strtolower($filename)) {
             $tokens[$classyIndex]->setContent(str_replace('/', '_', $filename));
         }
     }
 }
Exemplo n.º 28
0
 private function ensureOnNewLine(Tokens $tokens, $index)
 {
     // while not whitespace and not comment go back
     for (--$index; $index > 0; --$index) {
         if (!$tokens[$index]->isGivenKind(array(T_NS_SEPARATOR, T_STRING))) {
             break;
         }
     }
     if ("\n" === substr($tokens[$index]->getContent(), -1)) {
         return $index;
     }
     if (!$tokens[$index]->isWhitespace()) {
         $tokens->insertAt($index + 1, new Token(array(T_WHITESPACE, "\n")));
         return $index;
     }
     if (false !== strpos($tokens[$index]->getContent(), "\n")) {
         return $index;
     }
     $tokens[$index]->setContent($tokens[$index]->getContent() . "\n");
     return $index;
 }
Exemplo n.º 29
0
 /**
  * @param Tokens $tokens
  */
 private function insertSequence(Tokens $tokens)
 {
     $sequence = $this->getDeclareStrictTypeSequence();
     $sequence[] = new Token(';');
     $tokens->insertAt(1, $sequence);
     $this->fixWhiteSpaceAroundSequence($tokens, count($sequence));
 }
Exemplo n.º 30
0
 /**
  * @param Tokens $tokens
  * @param int    $startIndex
  * @param int    $endIndex
  * @param int    $reqLineCount
  */
 private function correctLineBreaks(Tokens $tokens, $startIndex, $endIndex, $reqLineCount = 2)
 {
     ++$startIndex;
     $numbOfWhiteTokens = $endIndex - $startIndex;
     if (0 === $numbOfWhiteTokens) {
         $tokens->insertAt($startIndex, new Token(array(T_WHITESPACE, str_repeat("\n", $reqLineCount))));
         return;
     }
     $lineBreakCount = $this->getLineBreakCount($tokens, $startIndex, $endIndex);
     if ($reqLineCount === $lineBreakCount) {
         return;
     }
     if ($lineBreakCount < $reqLineCount) {
         $tokens[$startIndex]->setContent(str_repeat("\n", $reqLineCount - $lineBreakCount) . $tokens[$startIndex]->getContent());
         return;
     }
     // $lineCount = > $reqLineCount : check the one Token case first since this one will be true most of the time
     if (1 === $numbOfWhiteTokens) {
         $tokens[$startIndex]->setContent(preg_replace('/[\\r\\n]/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount));
         return;
     }
     // $numbOfWhiteTokens = > 1
     $toReplaceCount = $lineBreakCount - $reqLineCount;
     for ($i = $startIndex; $i < $endIndex && $toReplaceCount > 0; ++$i) {
         $tokenLineCount = substr_count($tokens[$i]->getContent(), "\n");
         if ($tokenLineCount > 0) {
             $tokens[$i]->setContent(preg_replace('/[\\r\\n]/', '', $tokens[$i]->getContent(), min($toReplaceCount, $tokenLineCount)));
             $toReplaceCount -= $tokenLineCount;
         }
     }
 }