CombineConsecutiveIssetsFixer.php 4.95 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
<?php

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Fixer\LanguageConstruct;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author SpacePossum
 */
final class CombineConsecutiveIssetsFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Using `isset($var) &&` multiple times should be done in one call.',
            [new CodeSample("<?php\n\$a = isset(\$a) && isset(\$b);\n")]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run before MultilineWhitespaceBeforeSemicolonsFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer and NoSpacesInsideParenthesisFixer.
        return 3;
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isAllTokenKindsFound([T_ISSET, T_BOOLEAN_AND]);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        $tokenCount = $tokens->count();

        for ($index = 1; $index < $tokenCount; ++$index) {
            if (!$tokens[$index]->isGivenKind(T_ISSET) || $tokens[$tokens->getPrevMeaningfulToken($index)]->equals('!')) {
                continue;
            }

            $issetInfo = $this->getIssetInfo($tokens, $index);
            $issetCloseBraceIndex = end($issetInfo); // ')' token
            $insertLocation = prev($issetInfo) + 1; // one index after the previous meaningful of ')'

            $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex);

            while ($tokens[$booleanAndTokenIndex]->isGivenKind(T_BOOLEAN_AND)) {
                $issetIndex = $tokens->getNextMeaningfulToken($booleanAndTokenIndex);
                if (!$tokens[$issetIndex]->isGivenKind(T_ISSET)) {
                    $index = $issetIndex;

                    break;
                }

                // fetch info about the 'isset' statement that we're merging
                $nextIssetInfo = $this->getIssetInfo($tokens, $issetIndex);

                // clone what we want to move, do not clone '(' and ')' of the 'isset' statement we're merging
                $clones = $this->getTokenClones($tokens, \array_slice($nextIssetInfo, 1, -1));

                // clean up no the tokens of the 'isset' statement we're merging
                $this->clearTokens($tokens, array_merge($nextIssetInfo, [$issetIndex, $booleanAndTokenIndex]));

                // insert the tokens to create the new statement
                array_unshift($clones, new Token(','), new Token([T_WHITESPACE, ' ']));
                $tokens->insertAt($insertLocation, $clones);

                // correct some counts and offset based on # of tokens inserted
                $numberOfTokensInserted = \count($clones);
                $tokenCount += $numberOfTokensInserted;
                $issetCloseBraceIndex += $numberOfTokensInserted;
                $insertLocation += $numberOfTokensInserted;

                $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex);
            }
        }
    }

    /**
     * @param Tokens $tokens
     * @param int[]  $indexes
     */
    private function clearTokens(Tokens $tokens, array $indexes)
    {
        foreach ($indexes as $index) {
            $tokens->clearTokenAndMergeSurroundingWhitespace($index);
        }
    }

    /**
     * @param Tokens $tokens
     * @param int    $index  of T_ISSET
     *
     * @return int[] indexes of meaningful tokens belonging to the isset statement
     */
    private function getIssetInfo(Tokens $tokens, $index)
    {
        $openIndex = $tokens->getNextMeaningfulToken($index);

        $braceOpenCount = 1;
        $meaningfulTokenIndexes = [$openIndex];

        for ($i = $openIndex + 1;; ++$i) {
            if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) {
                continue;
            }

            $meaningfulTokenIndexes[] = $i;

            if ($tokens[$i]->equals(')')) {
                --$braceOpenCount;
                if (0 === $braceOpenCount) {
                    break;
                }
            } elseif ($tokens[$i]->equals('(')) {
                ++$braceOpenCount;
            }
        }

        return $meaningfulTokenIndexes;
    }

    /**
     * @param Tokens $tokens
     * @param int[]  $indexes
     *
     * @return Token[]
     */
    private function getTokenClones(Tokens $tokens, array $indexes)
    {
        $clones = [];

        foreach ($indexes as $i) {
            $clones[] = clone $tokens[$i];
        }

        return $clones;
    }
}