<?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\ListNotation;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author SpacePossum
 */
final class ListSyntaxFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
    private $candidateTokenKind;

    /**
     * Use 'syntax' => 'long'|'short'.
     *
     * @param null|array<string, string> $configuration
     *
     * @throws InvalidFixerConfigurationException
     */
    public function configure(array $configuration = null)
    {
        parent::configure($configuration);

        $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN : T_LIST;
    }

    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'List (`array` destructuring) assignment should be declared using the configured syntax. Requires PHP >= 7.1.',
            [
                new VersionSpecificCodeSample(
                    "<?php\n[\$sample] = \$array;\n",
                    new VersionSpecification(70100)
                ),
                new VersionSpecificCodeSample(
                    "<?php\nlist(\$sample) = \$array;\n",
                    new VersionSpecification(70100),
                    ['syntax' => 'short']
                ),
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run before the BinaryOperatorSpacesFixer and TernaryOperatorSpacesFixer.
        return 1;
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return \PHP_VERSION_ID >= 70100 && $tokens->isTokenKindFound($this->candidateTokenKind);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        for ($index = $tokens->count() - 1; 0 <= $index; --$index) {
            if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) {
                if (T_LIST === $this->candidateTokenKind) {
                    $this->fixToShortSyntax($tokens, $index);
                } else {
                    $this->fixToLongSyntax($tokens, $index);
                }
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function createConfigurationDefinition()
    {
        return new FixerConfigurationResolver([
            (new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` `list` syntax.'))
                ->setAllowedValues(['long', 'short'])
                ->setDefault('long')
                ->getOption(),
        ]);
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     */
    private function fixToLongSyntax(Tokens $tokens, $index)
    {
        static $typesOfInterest = [
            [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE],
            [CT::T_ARRAY_SQUARE_BRACE_OPEN],
        ];

        $closeIndex = $tokens->getNextTokenOfKind($index, $typesOfInterest);
        if (!$tokens[$closeIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE)) {
            return;
        }

        $tokens[$index] = new Token('(');
        $tokens[$closeIndex] = new Token(')');
        $tokens->insertAt($index, new Token([T_LIST, 'list']));
    }

    /**
     * @param Tokens $tokens
     * @param int    $index
     */
    private function fixToShortSyntax(Tokens $tokens, $index)
    {
        $openIndex = $tokens->getNextTokenOfKind($index, ['(']);
        $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex);

        $tokens[$openIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '[']);
        $tokens[$closeIndex] = new Token([CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']);

        $tokens->clearTokenAndMergeSurroundingWhitespace($index);
    }
}


<?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\Differ;

use PhpCsFixer\Preg;
use Symfony\Component\Console\Formatter\OutputFormatter;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 */
final class DiffConsoleFormatter
{
    /**
     * @var bool
     */
    private $isDecoratedOutput;

    /**
     * @var string
     */
    private $template;

    /**
     * @param bool   $isDecoratedOutput
     * @param string $template
     */
    public function __construct($isDecoratedOutput, $template = '%s')
    {
        $this->isDecoratedOutput = $isDecoratedOutput;
        $this->template = $template;
    }

    /**
     * @param string $diff
     * @param string $lineTemplate
     *
     * @return string
     */
    public function format($diff, $lineTemplate = '%s')
    {
        $isDecorated = $this->isDecoratedOutput;

        $template = $isDecorated
            ? $this->template
            : Preg::replace('/<[^<>]+>/', '', $this->template)
        ;

        return sprintf(
            $template,
            implode(
                PHP_EOL,
                array_map(
                    static function ($line) use ($isDecorated, $lineTemplate) {
                        if ($isDecorated) {
                            $count = 0;
                            $line = Preg::replaceCallback(
                                [
                                    '/^(\+.*)/',
                                    '/^(\-.*)/',
                                    '/^(@.*)/',
                                ],
                                function ($matches) {
                                    if ('+' === $matches[0][0]) {
                                        $colour = 'green';
                                    } elseif ('-' === $matches[0][0]) {
                                        $colour = 'red';
                                    } else {
                                        $colour = 'cyan';
                                    }

                                    return sprintf('<fg=%s>%s</fg=%s>', $colour, OutputFormatter::escape($matches[0]), $colour);
                                },
                                $line,
                                1,
                                $count
                            );

                            if (0 === $count) {
                                $line = OutputFormatter::escape($line);
                            }
                        }

                        return sprintf($lineTemplate, $line);
                    },
                    Preg::split('#\R#u', $diff)
                )
            )
        );
    }
}


<?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\Console\Command;

use PhpCsFixer\Console\Application;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\DefinedFixerInterface;
use PhpCsFixer\Fixer\DeprecatedFixerInterface;
use PhpCsFixer\Fixer\FixerInterface;
use PhpCsFixer\FixerConfiguration\AliasedFixerOption;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption;
use PhpCsFixer\FixerConfiguration\FixerOptionInterface;
use PhpCsFixer\FixerFactory;
use PhpCsFixer\Preg;
use PhpCsFixer\RuleSet;
use PhpCsFixer\Utils;
use Symfony\Component\Console\Command\HelpCommand as BaseHelpCommand;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author SpacePossum
 *
 * @internal
 */
final class HelpCommand extends BaseHelpCommand
{
    const COMMAND_NAME = 'help';

    /**
     * Returns help-copy suitable for console output.
     *
     * @return string
     */
    public static function getHelpCopy()
    {
        $template =
            <<<'EOF'
The <info>%command.name%</info> command tries to fix as much coding standards
problems as possible on a given file or files in a given directory and its subdirectories:

    <info>$ php %command.full_name% /path/to/dir</info>
    <info>$ php %command.full_name% /path/to/file</info>

By default <comment>--path-mode</comment> is set to ``override``, which means, that if you specify the path to a file or a directory via
command arguments, then the paths provided to a ``Finder`` in config file will be ignored. You can use <comment>--path-mode=intersection</comment>
to merge paths from the config file and from the argument:

    <info>$ php %command.full_name% --path-mode=intersection /path/to/dir</info>

The <comment>--format</comment> option for the output format. Supported formats are ``txt`` (default one), ``json``, ``xml``, ``checkstyle`` and ``junit``.

NOTE: the output for the following formats are generated in accordance with XML schemas

* ``junit`` follows the `JUnit xml schema from Jenkins </doc/junit-10.xsd>`_
* ``checkstyle`` follows the common `"checkstyle" xml schema </doc/checkstyle.xsd>`_

The <comment>--verbose</comment> option will show the applied rules. When using the ``txt`` format it will also displays progress notifications.

The <comment>--rules</comment> option limits the rules to apply on the
project:

    <info>$ php %command.full_name% /path/to/project --rules=@PSR2</info>

By default the PSR1 and PSR2 rules are used.

The <comment>--rules</comment> option lets you choose the exact rules to
apply (the rule names must be separated by a comma):

    <info>$ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type</info>

You can also blacklist the rules you don't want by placing a dash in front of the rule name, if this is more convenient,
using <comment>-name_of_fixer</comment>:

    <info>$ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type</info>

When using combinations of exact and blacklist rules, applying exact rules along with above blacklisted results:

    <info>$ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison</info>

Complete configuration for rules can be supplied using a ``json`` formatted string.

    <info>$ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}'</info>

The <comment>--dry-run</comment> flag will run the fixer without making changes to your files.

The <comment>--diff</comment> flag can be used to let the fixer output all the changes it makes.

The <comment>--diff-format</comment> option allows to specify in which format the fixer should output the changes it makes:

* <comment>udiff</comment>: unified diff format;
* <comment>sbd</comment>: Sebastianbergmann/diff format (default when using `--diff` without specifying `diff-format`).

The <comment>--allow-risky</comment> option (pass ``yes`` or ``no``) allows you to set whether risky rules may run. Default value is taken from config file.
Risky rule is a rule, which could change code behaviour. By default no risky rules are run.

The <comment>--stop-on-violation</comment> flag stops the execution upon first file that needs to be fixed.

The <comment>--show-progress</comment> option allows you to choose the way process progress is rendered:

* <comment>none</comment>: disables progress output;
* <comment>run-in</comment>: [deprecated] simple single-line progress output;
* <comment>estimating</comment>: [deprecated] multiline progress output with number of files and percentage on each line. Note that with this option, the files list is evaluated before processing to get the total number of files and then kept in memory to avoid using the file iterator twice. This has an impact on memory usage so using this option is not recommended on very large projects;
* <comment>estimating-max</comment>: [deprecated] same as <comment>dots</comment>;
* <comment>dots</comment>: same as <comment>estimating</comment> but using all terminal columns instead of default 80.

If the option is not provided, it defaults to <comment>run-in</comment> unless a config file that disables output is used, in which case it defaults to <comment>none</comment>. This option has no effect if the verbosity of the command is less than <comment>verbose</comment>.

    <info>$ php %command.full_name% --verbose --show-progress=estimating</info>

The command can also read from standard input, in which case it won't
automatically fix anything:

    <info>$ cat foo.php | php %command.full_name% --diff -</info>

Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that
would be default in next MAJOR release (unified differ, estimating, full-width progress indicator):

    <info>$ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff</info>

Choose from the list of available rules:

%%%FIXERS_DETAILS%%%

The <comment>--dry-run</comment> option displays the files that need to be
fixed but without actually modifying them:

    <info>$ php %command.full_name% /path/to/code --dry-run</info>

Config file
-----------

Instead of using command line options to customize the rule, you can save the
project configuration in a <comment>.php_cs.dist</comment> file in the root directory of your project.
The file must return an instance of `PhpCsFixer\ConfigInterface` (<url>%%%CONFIG_INTERFACE_URL%%%</url>)
which lets you configure the rules, the files and directories that
need to be analyzed. You may also create <comment>.php_cs</comment> file, which is
the local configuration that will be used instead of the project configuration. It
is a good practice to add that file into your <comment>.gitignore</comment> file.
With the <comment>--config</comment> option you can specify the path to the
<comment>.php_cs</comment> file.

The example below will add two rules to the default list of PSR2 set rules:

    <?php

    $finder = PhpCsFixer\Finder::create()
        ->exclude('somedir')
        ->notPath('src/Symfony/Component/Translation/Tests/fixtures/resources.php')
        ->in(__DIR__)
    ;

    return PhpCsFixer\Config::create()
        ->setRules([
            '@PSR2' => true,
            'strict_param' => true,
            'array_syntax' => ['syntax' => 'short'],
        ])
        ->setFinder($finder)
    ;

    ?>

**NOTE**: ``exclude`` will work only for directories, so if you need to exclude file, try ``notPath``.

See `Symfony\Finder` (<url>https://symfony.com/doc/current/components/finder.html</url>)
online documentation for other `Finder` methods.

You may also use a blacklist for the rules instead of the above shown whitelist approach.
The following example shows how to use all ``Symfony`` rules but the ``full_opening_tag`` rule.

    <?php

    $finder = PhpCsFixer\Finder::create()
        ->exclude('somedir')
        ->in(__DIR__)
    ;

    return PhpCsFixer\Config::create()
        ->setRules([
            '@Symfony' => true,
            'full_opening_tag' => false,
        ])
        ->setFinder($finder)
    ;

    ?>

You may want to use non-linux whitespaces in your project. Then you need to
configure them in your config file.

    <?php

    return PhpCsFixer\Config::create()
        ->setIndent("\t")
        ->setLineEnding("\r\n")
    ;

    ?>

By using ``--using-cache`` option with ``yes`` or ``no`` you can set if the caching
mechanism should be used.

Caching
-------

The caching mechanism is enabled by default. This will speed up further runs by
fixing only files that were modified since the last run. The tool will fix all
files if the tool version has changed or the list of rules has changed.
Cache is supported only for tool downloaded as phar file or installed via
composer.

Cache can be disabled via ``--using-cache`` option or config file:

    <?php

    return PhpCsFixer\Config::create()
        ->setUsingCache(false)
    ;

    ?>

Cache file can be specified via ``--cache-file`` option or config file:

    <?php

    return PhpCsFixer\Config::create()
        ->setCacheFile(__DIR__.'/.php_cs.cache')
    ;

    ?>

Using PHP CS Fixer on CI
------------------------

Require ``friendsofphp/php-cs-fixer`` as a ``dev`` dependency:

    $ ./composer.phar require --dev friendsofphp/php-cs-fixer

Then, add the following command to your CI:

%%%CI_INTEGRATION%%%

Where ``$COMMIT_RANGE`` is your range of commits, e.g. ``$TRAVIS_COMMIT_RANGE`` or ``HEAD~..HEAD``.

Exit code
---------

Exit code is built using following bit flags:

*  0 - OK.
*  1 - General error (or PHP minimal requirement not matched).
*  4 - Some files have invalid syntax (only in dry-run mode).
*  8 - Some files need fixing (only in dry-run mode).
* 16 - Configuration error of the application.
* 32 - Configuration error of a Fixer.
* 64 - Exception raised within the application.

(Applies to exit code of the `fix` command only)
EOF
        ;

        return strtr($template, [
            '%%%CONFIG_INTERFACE_URL%%%' => sprintf(
                'https://github.com/FriendsOfPHP/PHP-CS-Fixer/blob/v%s/src/ConfigInterface.php',
                self::getLatestReleaseVersionFromChangeLog()
            ),
            '%%%CI_INTEGRATION%%%' => implode("\n", array_map(
                static function ($line) { return '    $ '.$line; },
                \array_slice(file(__DIR__.'/../../../dev-tools/ci-integration.sh', FILE_IGNORE_NEW_LINES), 3)
            )),
            '%%%FIXERS_DETAILS%%%' => self::getFixersHelp(),
        ]);
    }

    /**
     * @param mixed $value
     *
     * @return string
     */
    public static function toString($value)
    {
        if (\is_array($value)) {
            // Output modifications:
            // - remove new-lines
            // - combine multiple whitespaces
            // - switch array-syntax to short array-syntax
            // - remove whitespace at array opening
            // - remove trailing array comma and whitespace at array closing
            // - remove numeric array indexes
            static $replaces = [
                ['#\r|\n#', '#\s{1,}#', '#array\s*\((.*)\)#s', '#\[\s+#', '#,\s*\]#', '#\d+\s*=>\s*#'],
                ['', ' ', '[$1]', '[', ']', ''],
            ];

            $str = var_export($value, true);
            do {
                $strNew = Preg::replace(
                    $replaces[0],
                    $replaces[1],
                    $str
                );

                if ($strNew === $str) {
                    break;
                }

                $str = $strNew;
            } while (true);
        } else {
            $str = var_export($value, true);
        }

        return Preg::replace('/\bNULL\b/', 'null', $str);
    }

    /**
     * Returns the allowed values of the given option that can be converted to a string.
     *
     * @param FixerOptionInterface $option
     *
     * @return null|array
     */
    public static function getDisplayableAllowedValues(FixerOptionInterface $option)
    {
        $allowed = $option->getAllowedValues();

        if (null !== $allowed) {
            $allowed = array_filter($allowed, static function ($value) {
                return !($value instanceof \Closure);
            });

            usort($allowed, static function ($valueA, $valueB) {
                if ($valueA instanceof AllowedValueSubset) {
                    return -1;
                }

                if ($valueB instanceof AllowedValueSubset) {
                    return 1;
                }

                return strcasecmp(
                    self::toString($valueA),
                    self::toString($valueB)
                );
            });

            if (0 === \count($allowed)) {
                $allowed = null;
            }
        }

        return $allowed;
    }

    /**
     * @throws \RuntimeException when failing to parse the change log file
     *
     * @return string
     */
    public static function getLatestReleaseVersionFromChangeLog()
    {
        static $version = null;

        if (null !== $version) {
            return $version;
        }

        $changelogFile = self::getChangeLogFile();
        if (null === $changelogFile) {
            $version = Application::VERSION;

            return $version;
        }

        $changelog = @file_get_contents($changelogFile);
        if (false === $changelog) {
            $error = error_get_last();

            throw new \RuntimeException(sprintf(
                'Failed to read content of the changelog file "%s".%s',
                $changelogFile,
                $error ? ' '.$error['message'] : ''
            ));
        }

        for ($i = (int) Application::VERSION; $i > 0; --$i) {
            if (1 === Preg::match('/Changelog for v('.$i.'.\d+.\d+)/', $changelog, $matches)) {
                $version = $matches[1];

                break;
            }
        }

        if (null === $version) {
            throw new \RuntimeException(sprintf('Failed to parse changelog data of "%s".', $changelogFile));
        }

        return $version;
    }

    /**
     * {@inheritdoc}
     */
    protected function initialize(InputInterface $input, OutputInterface $output)
    {
        $output->getFormatter()->setStyle('url', new OutputFormatterStyle('blue'));
    }

    /**
     * @return null|string
     */
    private static function getChangeLogFile()
    {
        $changelogFile = __DIR__.'/../../../CHANGELOG.md';

        return is_file($changelogFile) ? $changelogFile : null;
    }

    /**
     * @return string
     */
    private static function getFixersHelp()
    {
        $help = '';
        $fixerFactory = new FixerFactory();
        $fixers = $fixerFactory->registerBuiltInFixers()->getFixers();

        // sort fixers by name
        usort(
            $fixers,
            static function (FixerInterface $a, FixerInterface $b) {
                return strcmp($a->getName(), $b->getName());
            }
        );

        $ruleSets = [];
        foreach (RuleSet::create()->getSetDefinitionNames() as $setName) {
            $ruleSets[$setName] = new RuleSet([$setName => true]);
        }

        $getSetsWithRule = static function ($rule) use ($ruleSets) {
            $sets = [];

            foreach ($ruleSets as $setName => $ruleSet) {
                if ($ruleSet->hasRule($rule)) {
                    $sets[] = $setName;
                }
            }

            return $sets;
        };

        $count = \count($fixers) - 1;
        foreach ($fixers as $i => $fixer) {
            $sets = $getSetsWithRule($fixer->getName());

            if ($fixer instanceof DefinedFixerInterface) {
                $description = $fixer->getDefinition()->getSummary();
            } else {
                $description = '[n/a]';
            }

            if ($fixer instanceof DeprecatedFixerInterface) {
                $successors = $fixer->getSuccessorsNames();
                $message = [] === $successors
                    ? 'will be removed on next major version'
                    : sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors));
                $description .= sprintf(' DEPRECATED: %s.', $message);
            }

            $description = implode("\n   | ", self::wordwrap(
                Preg::replace('/(`.+?`)/', '<info>$1</info>', $description),
                72
            ));

            if (!empty($sets)) {
                $help .= sprintf(" * <comment>%s</comment> [%s]\n   | %s\n", $fixer->getName(), implode(', ', $sets), $description);
            } else {
                $help .= sprintf(" * <comment>%s</comment>\n   | %s\n", $fixer->getName(), $description);
            }

            if ($fixer->isRisky()) {
                $help .= sprintf(
                    "   | *Risky rule: %s.*\n",
                    Preg::replace(
                        '/(`.+?`)/',
                        '<info>$1</info>',
                        lcfirst(Preg::replace('/\.$/', '', $fixer->getDefinition()->getRiskyDescription()))
                    )
                );
            }

            if ($fixer instanceof ConfigurationDefinitionFixerInterface) {
                $configurationDefinition = $fixer->getConfigurationDefinition();
                $configurationDefinitionOptions = $configurationDefinition->getOptions();
                if (\count($configurationDefinitionOptions)) {
                    $help .= "   |\n   | Configuration options:\n";

                    usort(
                        $configurationDefinitionOptions,
                        static function (FixerOptionInterface $optionA, FixerOptionInterface $optionB) {
                            return strcmp($optionA->getName(), $optionB->getName());
                        }
                    );

                    foreach ($configurationDefinitionOptions as $option) {
                        $line = '<info>'.OutputFormatter::escape($option->getName()).'</info>';

                        $allowed = self::getDisplayableAllowedValues($option);
                        if (null !== $allowed) {
                            foreach ($allowed as &$value) {
                                if ($value instanceof AllowedValueSubset) {
                                    $value = 'a subset of <comment>'.self::toString($value->getAllowedValues()).'</comment>';
                                } else {
                                    $value = '<comment>'.self::toString($value).'</comment>';
                                }
                            }
                        } else {
                            $allowed = array_map(
                                function ($type) {
                                    return '<comment>'.$type.'</comment>';
                                },
                                $option->getAllowedTypes()
                            );
                        }

                        if (null !== $allowed) {
                            $line .= ' ('.implode(', ', $allowed).')';
                        }

                        $line .= ': '.Preg::replace(
                            '/(`.+?`)/',
                            '<info>$1</info>',
                            lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDescription())))
                        ).'; ';
                        if ($option->hasDefault()) {
                            $line .= 'defaults to <comment>'.self::toString($option->getDefault()).'</comment>';
                        } else {
                            $line .= 'required';
                        }

                        if ($option instanceof DeprecatedFixerOption) {
                            $line .= '. DEPRECATED: '.Preg::replace(
                                '/(`.+?`)/',
                                '<info>$1</info>',
                                lcfirst(Preg::replace('/\.$/', '', OutputFormatter::escape($option->getDeprecationMessage())))
                            );
                        }

                        if ($option instanceof AliasedFixerOption) {
                            $line .= '; DEPRECATED alias: <comment>'.$option->getAlias().'</comment>';
                        }

                        foreach (self::wordwrap($line, 72) as $index => $line) {
                            $help .= (0 === $index ? '   | - ' : '   |   ').$line."\n";
                        }
                    }
                }
            } elseif ($fixer instanceof ConfigurableFixerInterface) {
                $help .= "   | *Configurable rule.*\n";
            }

            if ($count !== $i) {
                $help .= "\n";
            }
        }

        // prevent "\</foo>" from being rendered as an escaped literal style tag
        return Preg::replace('#\\\\(</.*?>)#', '<<$1', $help);
    }

    /**
     * Wraps a string to the given number of characters, ignoring style tags.
     *
     * @param string $string
     * @param int    $width
     *
     * @return string[]
     */
    private static function wordwrap($string, $width)
    {
        $result = [];
        $currentLine = 0;
        $lineLength = 0;
        foreach (explode(' ', $string) as $word) {
            $wordLength = \strlen(Preg::replace('~</?(\w+)>~', '', $word));
            if (0 !== $lineLength) {
                ++$wordLength; // space before word
            }

            if ($lineLength + $wordLength > $width) {
                ++$currentLine;
                $lineLength = 0;
            }

            $result[$currentLine][] = $word;
            $lineLength += $wordLength;
        }

        return array_map(static function ($line) {
            return implode(' ', $line);
        }, $result);
    }
}


<?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\DoctrineAnnotation;

use Doctrine\Common\Annotations\DocLexer;
use PhpCsFixer\AbstractDoctrineAnnotationFixer;
use PhpCsFixer\Doctrine\Annotation\Token;
use PhpCsFixer\Doctrine\Annotation\Tokens;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;

/**
 * Adds braces to Doctrine annotations when missing.
 */
final class DoctrineAnnotationBracesFixer extends AbstractDoctrineAnnotationFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Doctrine annotations without arguments must use the configured syntax.',
            [
                new CodeSample(
                    "<?php\n/**\n * @Foo()\n */\nclass Bar {}\n"
                ),
                new CodeSample(
                    "<?php\n/**\n * @Foo\n */\nclass Bar {}\n",
                    ['syntax' => 'with_braces']
                ),
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function createConfigurationDefinition()
    {
        return new FixerConfigurationResolver(array_merge(
            parent::createConfigurationDefinition()->getOptions(),
            [
                (new FixerOptionBuilder('syntax', 'Whether to add or remove braces.'))
                    ->setAllowedValues(['with_braces', 'without_braces'])
                    ->setDefault('without_braces')
                    ->getOption(),
            ]
        ));
    }

    /**
     * {@inheritdoc}
     */
    protected function fixAnnotations(Tokens $tokens)
    {
        if ('without_braces' === $this->configuration['syntax']) {
            $this->removesBracesFromAnnotations($tokens);
        } else {
            $this->addBracesToAnnotations($tokens);
        }
    }

    /**
     * @param Tokens $tokens
     */
    private function addBracesToAnnotations(Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$tokens[$index]->isType(DocLexer::T_AT)) {
                continue;
            }

            $braceIndex = $tokens->getNextMeaningfulToken($index + 1);
            if (null !== $braceIndex && $tokens[$braceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) {
                continue;
            }

            $tokens->insertAt($index + 2, new Token(DocLexer::T_OPEN_PARENTHESIS, '('));
            $tokens->insertAt($index + 3, new Token(DocLexer::T_CLOSE_PARENTHESIS, ')'));
        }
    }

    /**
     * @param Tokens $tokens
     */
    private function removesBracesFromAnnotations(Tokens $tokens)
    {
        for ($index = 0, $max = \count($tokens); $index < $max; ++$index) {
            if (!$tokens[$index]->isType(DocLexer::T_AT)) {
                continue;
            }

            $openBraceIndex = $tokens->getNextMeaningfulToken($index + 1);
            if (null === $openBraceIndex) {
                continue;
            }

            if (!$tokens[$openBraceIndex]->isType(DocLexer::T_OPEN_PARENTHESIS)) {
                continue;
            }

            $closeBraceIndex = $tokens->getNextMeaningfulToken($openBraceIndex);
            if (null === $closeBraceIndex) {
                continue;
            }

            if (!$tokens[$closeBraceIndex]->isType(DocLexer::T_CLOSE_PARENTHESIS)) {
                continue;
            }

            for ($currentIndex = $index + 2; $currentIndex <= $closeBraceIndex; ++$currentIndex) {
                $tokens[$currentIndex]->clear();
            }
        }
    }
}


<?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\FunctionNotation;

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

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class FunctionTypehintSpaceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Add missing space between function\'s argument and its typehint.',
            [new CodeSample("<?php\nfunction sample(array\$a)\n{}\n")]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(T_FUNCTION);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\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, ['(', ';', [T_CLOSE_TAG]]);
            if (!$tokens[$startParenthesisIndex]->equals('(')) {
                continue;
            }

            $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
                $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([[T_WHITESPACE], [T_COMMENT], [T_DOC_COMMENT], '(', ','])) {
                    $tokens->insertAt($iter, new Token([T_WHITESPACE, ' ']));
                }
            }
        }
    }
}


<?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\Naming;

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

/**
 * @author Fred Cox <mcfedr@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class NoHomoglyphNamesFixer extends AbstractFixer
{
    /**
     * Used the program https://github.com/mcfedr/homoglyph-download
     * to generate this list from
     * http://homoglyphs.net/?text=abcdefghijklmnopqrstuvwxyz&lang=en&exc7=1&exc8=1&exc13=1&exc14=1.
     *
     * Symbols replaced include
     * - Latin homoglyphs
     * - IPA extensions
     * - Greek and Coptic
     * - Cyrillic
     * - Cyrillic Supplement
     * - Letterlike Symbols
     * - Latin Numbers
     * - Fullwidth Latin
     *
     * This is not the complete list of unicode homographs, but limited
     * to those you are more likely to have typed/copied by accident
     *
     * @var array
     */
    private static $replacements = [
        'O' => '0',
        '０' => '0',
        'I' => '1',
        '１' => '1',
        '２' => '2',
        '３' => '3',
        '４' => '4',
        '５' => '5',
        '６' => '6',
        '７' => '7',
        '８' => '8',
        '９' => '9',
        'Α' => 'A',
        'А' => 'A',
        'Ａ' => 'A',
        'ʙ' => 'B',
        'Β' => 'B',
        'В' => 'B',
        'Ｂ' => 'B',
        'Ϲ' => 'C',
        'С' => 'C',
        'Ⅽ' => 'C',
        'Ｃ' => 'C',
        'Ⅾ' => 'D',
        'Ｄ' => 'D',
        'Ε' => 'E',
        'Е' => 'E',
        'Ｅ' => 'E',
        'Ϝ' => 'F',
        'Ｆ' => 'F',
        'ɢ' => 'G',
        'Ԍ' => 'G',
        'Ｇ' => 'G',
        'ʜ' => 'H',
        'Η' => 'H',
        'Н' => 'H',
        'Ｈ' => 'H',
        'l' => 'I',
        'Ι' => 'I',
        'І' => 'I',
        'Ⅰ' => 'I',
        'Ｉ' => 'I',
        'Ј' => 'J',
        'Ｊ' => 'J',
        'Κ' => 'K',
        'К' => 'K',
        'K' => 'K',
        'Ｋ' => 'K',
        'ʟ' => 'L',
        'Ⅼ' => 'L',
        'Ｌ' => 'L',
        'Μ' => 'M',
        'М' => 'M',
        'Ⅿ' => 'M',
        'Ｍ' => 'M',
        'ɴ' => 'N',
        'Ν' => 'N',
        'Ｎ' => 'N',
        'Ο' => 'O',
        'О' => 'O',
        'Ｏ' => 'O',
        'Ρ' => 'P',
        'Р' => 'P',
        'Ｐ' => 'P',
        'Ｑ' => 'Q',
        'ʀ' => 'R',
        'Ｒ' => 'R',
        'Ѕ' => 'S',
        'Ｓ' => 'S',
        'Τ' => 'T',
        'Т' => 'T',
        'Ｔ' => 'T',
        'Ｕ' => 'U',
        'Ѵ' => 'V',
        'Ⅴ' => 'V',
        'Ｖ' => 'V',
        'Ｗ' => 'W',
        'Χ' => 'X',
        'Х' => 'X',
        'Ⅹ' => 'X',
        'Ｘ' => 'X',
        'ʏ' => 'Y',
        'Υ' => 'Y',
        'Ү' => 'Y',
        'Ｙ' => 'Y',
        'Ζ' => 'Z',
        'Ｚ' => 'Z',
        '＿' => '_',
        'ɑ' => 'a',
        'а' => 'a',
        'ａ' => 'a',
        'Ь' => 'b',
        'ｂ' => 'b',
        'ϲ' => 'c',
        'с' => 'c',
        'ⅽ' => 'c',
        'ｃ' => 'c',
        'ԁ' => 'd',
        'ⅾ' => 'd',
        'ｄ' => 'd',
        'е' => 'e',
        'ｅ' => 'e',
        'ｆ' => 'f',
        'ɡ' => 'g',
        'ｇ' => 'g',
        'һ' => 'h',
        'ｈ' => 'h',
        'ɩ' => 'i',
        'і' => 'i',
        'ⅰ' => 'i',
        'ｉ' => 'i',
        'ј' => 'j',
        'ｊ' => 'j',
        'ｋ' => 'k',
        'ⅼ' => 'l',
        'ｌ' => 'l',
        'ⅿ' => 'm',
        'ｍ' => 'm',
        'ｎ' => 'n',
        'ο' => 'o',
        'о' => 'o',
        'ｏ' => 'o',
        'р' => 'p',
        'ｐ' => 'p',
        'ｑ' => 'q',
        'ｒ' => 'r',
        'ѕ' => 's',
        'ｓ' => 's',
        'ｔ' => 't',
        'ｕ' => 'u',
        'ν' => 'v',
        'ѵ' => 'v',
        'ⅴ' => 'v',
        'ｖ' => 'v',
        'ѡ' => 'w',
        'ｗ' => 'w',
        'х' => 'x',
        'ⅹ' => 'x',
        'ｘ' => 'x',
        'у' => 'y',
        'ｙ' => 'y',
        'ｚ' => 'z',
    ];

    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Replace accidental usage of homoglyphs (non ascii characters) in names.',
            [new CodeSample("<?php \$nаmе = 'wrong \"a\" character';\n")],
            null,
            'Renames classes and cannot rename the files. You might have string references to renamed code (`$$name`).'
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isRisky()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isAnyTokenKindsFound([T_VARIABLE, T_STRING]);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind([T_VARIABLE, T_STRING])) {
                continue;
            }

            $replaced = Preg::replaceCallback('/[^[:ascii:]]/u', static function ($matches) {
                return isset(self::$replacements[$matches[0]])
                    ? self::$replacements[$matches[0]]
                    : $matches[0]
                ;
            }, $token->getContent(), -1, $count);

            if ($count) {
                $tokens->offsetSet($index, new Token([$token->getId(), $replaced]));
            }
        }
    }
}


<?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\ArrayNotation;

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

/**
 * @author Jared Henderson <jared@netrivet.com>
 */
final class TrimArraySpacesFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Arrays should be formatted like function/method arguments, without leading or trailing single line space.',
            [new CodeSample("<?php\n\$sample = array( );\n\$sample = array( 'a', 'b' );\n")]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isAnyTokenKindsFound([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        for ($index = 0, $c = $tokens->count(); $index < $c; ++$index) {
            if ($tokens[$index]->isGivenKind([T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) {
                self::fixArray($tokens, $index);
            }
        }
    }

    /**
     * Method to trim leading/trailing whitespace within single line arrays.
     *
     * @param Tokens $tokens
     * @param int    $index
     */
    private static function fixArray(Tokens $tokens, $index)
    {
        $startIndex = $index;

        if ($tokens[$startIndex]->isGivenKind(T_ARRAY)) {
            $startIndex = $tokens->getNextMeaningfulToken($startIndex);
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex);
        } else {
            $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex);
        }

        $nextIndex = $startIndex + 1;
        $nextToken = $tokens[$nextIndex];
        $nextNonWhitespaceIndex = $tokens->getNextNonWhitespace($startIndex);
        $nextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex];
        $tokenAfterNextNonWhitespaceToken = $tokens[$nextNonWhitespaceIndex + 1];

        $prevIndex = $endIndex - 1;
        $prevToken = $tokens[$prevIndex];
        $prevNonWhitespaceIndex = $tokens->getPrevNonWhitespace($endIndex);
        $prevNonWhitespaceToken = $tokens[$prevNonWhitespaceIndex];

        if (
            $nextToken->isWhitespace(" \t")
            && (
                !$nextNonWhitespaceToken->isComment()
                || $nextNonWhitespaceIndex === $prevNonWhitespaceIndex
                || $tokenAfterNextNonWhitespaceToken->isWhitespace(" \t")
                || '/*' === substr($nextNonWhitespaceToken->getContent(), 0, 2)
            )
        ) {
            $tokens->clearAt($nextIndex);
        }

        if (
            $prevToken->isWhitespace(" \t")
            && !$prevNonWhitespaceToken->equals(',')
        ) {
            $tokens->clearAt($prevIndex);
        }
    }
}


<?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\Whitespace;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\VersionSpecification;
use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Jack Cherng <jfcherng@gmail.com>
 */
final class CompactNullableTypehintFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Remove extra spaces in a nullable typehint.',
            [
                new VersionSpecificCodeSample(
                    "<?php\nfunction sample(? string \$str): ? string\n{}\n",
                    new VersionSpecification(70100)
                ),
            ],
            'Rule is applied only in a PHP 7.1+ environment.'
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return \PHP_VERSION_ID >= 70100 && $tokens->isTokenKindFound(CT::T_NULLABLE_TYPE);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        static $typehintKinds = [
            CT::T_ARRAY_TYPEHINT,
            T_CALLABLE,
            T_NS_SEPARATOR,
            T_STRING,
        ];

        for ($index = $tokens->count() - 1; $index >= 0; --$index) {
            if (!$tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) {
                continue;
            }

            // remove whitespaces only if there are only whitespaces
            // between '?' and the variable type
            if (
                $tokens[$index + 1]->isWhitespace() &&
                $tokens[$index + 2]->isGivenKind($typehintKinds)
            ) {
                $tokens->removeTrailingWhitespace($index);
            }
        }
    }
}


<?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;

use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Bram Gotink <bram@gotink.me>
 * @author Graham Campbell <graham@alt-three.com>
 *
 * @internal
 */
abstract class AbstractPsrAutoloadingFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds());
    }

    /**
     * {@inheritdoc}
     */
    public function isRisky()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return -10;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(\SplFileInfo $file)
    {
        if ($file instanceof StdinFileInfo) {
            return false;
        }

        $filenameParts = explode('.', $file->getBasename(), 2);

        if (
            // ignore file with extension other than php
            (!isset($filenameParts[1]) || 'php' !== $filenameParts[1])
            // ignore file with name that cannot be a class name
            || 0 === Preg::match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $filenameParts[0])
        ) {
            return false;
        }

        try {
            $tokens = Tokens::fromCode(sprintf('<?php class %s {}', $filenameParts[0]));

            if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) {
                // name can not be a class name - detected by PHP 5.x
                return false;
            }
        } catch (\ParseError $e) {
            // name can not be a class name - detected by PHP 7.x
            return false;
        }

        // ignore stubs/fixtures, since they are typically containing invalid files for various reasons
        return !Preg::match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath());
    }
}


<?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\Console\Command;

use PhpCsFixer\Config;
use PhpCsFixer\ConfigInterface;
use PhpCsFixer\Console\ConfigurationResolver;
use PhpCsFixer\Console\Output\ErrorOutput;
use PhpCsFixer\Console\Output\NullOutput;
use PhpCsFixer\Console\Output\ProcessOutput;
use PhpCsFixer\Error\ErrorsManager;
use PhpCsFixer\Report\ReportSummary;
use PhpCsFixer\Runner\Runner;
use PhpCsFixer\ToolInfoInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Terminal;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Stopwatch\Stopwatch;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 */
final class FixCommand extends Command
{
    const COMMAND_NAME = 'fix';

    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @var ErrorsManager
     */
    private $errorsManager;

    /**
     * @var Stopwatch
     */
    private $stopwatch;

    /**
     * @var ConfigInterface
     */
    private $defaultConfig;

    /**
     * @var ToolInfoInterface
     */
    private $toolInfo;

    public function __construct(ToolInfoInterface $toolInfo)
    {
        parent::__construct();

        $this->defaultConfig = new Config();
        $this->errorsManager = new ErrorsManager();
        $this->eventDispatcher = new EventDispatcher();
        $this->stopwatch = new Stopwatch();
        $this->toolInfo = $toolInfo;
    }

    /**
     * {@inheritdoc}
     *
     * Override here to only generate the help copy when used.
     */
    public function getHelp()
    {
        return HelpCommand::getHelpCopy();
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName(self::COMMAND_NAME)
            ->setDefinition(
                [
                    new InputArgument('path', InputArgument::IS_ARRAY, 'The path.'),
                    new InputOption('path-mode', '', InputOption::VALUE_REQUIRED, 'Specify path mode (can be override or intersection).', 'override'),
                    new InputOption('allow-risky', '', InputOption::VALUE_REQUIRED, 'Are risky fixers allowed (can be yes or no).'),
                    new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php_cs file.'),
                    new InputOption('dry-run', '', InputOption::VALUE_NONE, 'Only shows which files would have been modified.'),
                    new InputOption('rules', '', InputOption::VALUE_REQUIRED, 'The rules.'),
                    new InputOption('using-cache', '', InputOption::VALUE_REQUIRED, 'Does cache should be used (can be yes or no).'),
                    new InputOption('cache-file', '', InputOption::VALUE_REQUIRED, 'The path to the cache file.'),
                    new InputOption('diff', '', InputOption::VALUE_NONE, 'Also produce diff for each file.'),
                    new InputOption('diff-format', '', InputOption::VALUE_REQUIRED, 'Specify diff format.'),
                    new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats.'),
                    new InputOption('stop-on-violation', '', InputOption::VALUE_NONE, 'Stop execution on first violation.'),
                    new InputOption('show-progress', '', InputOption::VALUE_REQUIRED, 'Type of progress indicator (none, run-in, estimating, estimating-max or dots).'),
                ]
            )
            ->setDescription('Fixes a directory or a file.')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $verbosity = $output->getVerbosity();

        $passedConfig = $input->getOption('config');
        $passedRules = $input->getOption('rules');

        $resolver = new ConfigurationResolver(
            $this->defaultConfig,
            [
                'allow-risky' => $input->getOption('allow-risky'),
                'config' => $passedConfig,
                'dry-run' => $input->getOption('dry-run'),
                'rules' => $passedRules,
                'path' => $input->getArgument('path'),
                'path-mode' => $input->getOption('path-mode'),
                'using-cache' => $input->getOption('using-cache'),
                'cache-file' => $input->getOption('cache-file'),
                'format' => $input->getOption('format'),
                'diff' => $input->getOption('diff'),
                'diff-format' => $input->getOption('diff-format'),
                'stop-on-violation' => $input->getOption('stop-on-violation'),
                'verbosity' => $verbosity,
                'show-progress' => $input->getOption('show-progress'),
            ],
            getcwd(),
            $this->toolInfo
        );

        $reporter = $resolver->getReporter();

        $stdErr = $output instanceof ConsoleOutputInterface
            ? $output->getErrorOutput()
            : ('txt' === $reporter->getFormat() ? $output : null)
        ;

        if (null !== $stdErr) {
            if (null !== $passedConfig && null !== $passedRules) {
                if (getenv('PHP_CS_FIXER_FUTURE_MODE')) {
                    throw new \RuntimeException('Passing both `config` and `rules` options is not possible. This check was performed as `PHP_CS_FIXER_FUTURE_MODE` env var is set.');
                }

                $stdErr->writeln([
                    sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'When passing both "--config" and "--rules" the rules within the configuration file are not used.'),
                    sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'Passing both options is deprecated; version v3.0 PHP-CS-Fixer will exit with a configuration error code.'),
                ]);
            }

            $configFile = $resolver->getConfigFile();
            $stdErr->writeln(sprintf('Loaded config <comment>%s</comment>%s.', $resolver->getConfig()->getName(), null === $configFile ? '' : ' from "'.$configFile.'"'));

            if ($resolver->getUsingCache()) {
                $cacheFile = $resolver->getCacheFile();
                if (is_file($cacheFile)) {
                    $stdErr->writeln(sprintf('Using cache file "%s".', $cacheFile));
                }
            }
        }

        $progressType = $resolver->getProgress();
        $finder = $resolver->getFinder();

        if (null !== $stdErr && $resolver->configFinderIsOverridden()) {
            $stdErr->writeln(
                sprintf($stdErr->isDecorated() ? '<bg=yellow;fg=black;>%s</>' : '%s', 'Paths from configuration file have been overridden by paths provided as command arguments.')
            );
        }

        // @TODO 3.0 remove `run-in` and `estimating`
        if ('none' === $progressType || null === $stdErr) {
            $progressOutput = new NullOutput();
        } elseif ('run-in' === $progressType) {
            $progressOutput = new ProcessOutput($stdErr, $this->eventDispatcher, null, null);
        } else {
            $finder = new \ArrayIterator(iterator_to_array($finder));
            $progressOutput = new ProcessOutput(
                $stdErr,
                $this->eventDispatcher,
                'estimating' !== $progressType ? (new Terminal())->getWidth() : null,
                \count($finder)
            );
        }

        $runner = new Runner(
            $finder,
            $resolver->getFixers(),
            $resolver->getDiffer(),
            'none' !== $progressType ? $this->eventDispatcher : null,
            $this->errorsManager,
            $resolver->getLinter(),
            $resolver->isDryRun(),
            $resolver->getCacheManager(),
            $resolver->getDirectory(),
            $resolver->shouldStopOnViolation()
        );

        $this->stopwatch->start('fixFiles');
        $changed = $runner->fix();
        $this->stopwatch->stop('fixFiles');

        $progressOutput->printLegend();

        $fixEvent = $this->stopwatch->getEvent('fixFiles');

        $reportSummary = new ReportSummary(
            $changed,
            $fixEvent->getDuration(),
            $fixEvent->getMemory(),
            OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity(),
            $resolver->isDryRun(),
            $output->isDecorated()
        );

        $output->isDecorated()
            ? $output->write($reporter->generate($reportSummary))
            : $output->write($reporter->generate($reportSummary), false, OutputInterface::OUTPUT_RAW)
        ;

        $invalidErrors = $this->errorsManager->getInvalidErrors();
        $exceptionErrors = $this->errorsManager->getExceptionErrors();
        $lintErrors = $this->errorsManager->getLintErrors();

        if (null !== $stdErr) {
            $errorOutput = new ErrorOutput($stdErr);

            if (\count($invalidErrors) > 0) {
                $errorOutput->listErrors('linting before fixing', $invalidErrors);
            }

            if (\count($exceptionErrors) > 0) {
                $errorOutput->listErrors('fixing', $exceptionErrors);
            }

            if (\count($lintErrors) > 0) {
                $errorOutput->listErrors('linting after fixing', $lintErrors);
            }
        }

        $exitStatusCalculator = new FixCommandExitStatusCalculator();

        return $exitStatusCalculator->calculate(
            $resolver->isDryRun(),
            \count($changed) > 0,
            \count($invalidErrors) > 0,
            \count($exceptionErrors) > 0
        );
    }
}


<?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\Phpdoc;

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

/**
 * Fix inline tags and make inheritdoc tag always inline.
 */
final class PhpdocInlineTagFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Fix PHPDoc inline tags, make `@inheritdoc` always inline.',
            [new CodeSample(
                '<?php
/**
 * @{TUTORIAL}
 * {{ @link }}
 * {@examples}
 * @inheritdocs
 */
'
            )]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(T_DOC_COMMENT);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_DOC_COMMENT)) {
                continue;
            }

            $content = $token->getContent();

            // Move `@` inside tag, for example @{tag} -> {@tag}, replace multiple curly brackets,
            // remove spaces between '{' and '@', remove 's' at the end of tag.
            // Make sure the tags are written in lower case, remove white space between end
            // of text and closing bracket and between the tag and inline comment.
            $content = Preg::replaceCallback(
                '#(?:@{+|{+[ \t]*@)[ \t]*(example|id|internal|inheritdoc|link|source|toc|tutorial)s?([^}]*)(?:}+)#i',
                static function (array $matches) {
                    $doc = trim($matches[2]);

                    if ('' === $doc) {
                        return '{@'.strtolower($matches[1]).'}';
                    }

                    return '{@'.strtolower($matches[1]).' '.$doc.'}';
                },
                $content
            );

            // Always make inheritdoc inline using with '{' '}' when needed,
            // make sure lowercase.
            $content = Preg::replace(
                '#(?<!{)@inheritdocs?(?!})#i',
                '{@inheritdoc}',
                $content
            );

            $tokens[$index] = new Token([T_DOC_COMMENT, $content]);
        }
    }
}


<?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\Phpdoc;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\ShortDescription;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@alt-three.com>
 */
final class PhpdocSummaryFixer extends AbstractFixer implements WhitespacesAwareFixerInterface
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'PHPDoc summary should end in either a full stop, exclamation mark, or question mark.',
            [new CodeSample('<?php
/**
 * Foo function is great
 */
function foo () {}
')]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(T_DOC_COMMENT);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_DOC_COMMENT)) {
                continue;
            }

            $doc = new DocBlock($token->getContent());
            $end = (new ShortDescription($doc))->getEnd();

            if (null !== $end) {
                $line = $doc->getLine($end);
                $content = rtrim($line->getContent());

                if (!$this->isCorrectlyFormatted($content)) {
                    $line->setContent($content.'.'.$this->whitespacesConfig->getLineEnding());
                    $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]);
                }
            }
        }
    }

    /**
     * Is the last line of the short description correctly formatted?
     *
     * @param string $content
     *
     * @return bool
     */
    private function isCorrectlyFormatted($content)
    {
        if (false !== stripos($content, '{@inheritdoc}')) {
            return true;
        }

        return $content !== rtrim($content, '.。!?¡¿！？');
    }
}


<?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\ControlStructure;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Sullivan Senechal <soullivaneuh@gmail.com>
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Gregor Harlan <gharlan@web.de>
 */
final class NoUnneededControlParenthesesFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface
{
    private static $loops = [
        'break' => ['lookupTokens' => T_BREAK, 'neededSuccessors' => [';']],
        'clone' => ['lookupTokens' => T_CLONE, 'neededSuccessors' => [';', ':', ',', ')'], 'forbiddenContents' => ['?', ':']],
        'continue' => ['lookupTokens' => T_CONTINUE, 'neededSuccessors' => [';']],
        'echo_print' => ['lookupTokens' => [T_ECHO, T_PRINT], 'neededSuccessors' => [';', [T_CLOSE_TAG]]],
        'return' => ['lookupTokens' => T_RETURN, 'neededSuccessors' => [';', [T_CLOSE_TAG]]],
        'switch_case' => ['lookupTokens' => T_CASE, 'neededSuccessors' => [';', ':']],
        'yield' => ['lookupTokens' => T_YIELD, 'neededSuccessors' => [';', ')']],
    ];

    /**
     * Dynamic yield option set on constructor.
     */
    public function __construct()
    {
        parent::__construct();

        // To be moved back to compile time property declaration when PHP support of PHP CS Fixer will be 7.0+
        if (\defined('T_COALESCE')) {
            self::$loops['clone']['forbiddenContents'][] = [T_COALESCE, '??'];
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        $types = [];

        foreach (self::$loops as $loop) {
            $types[] = (array) $loop['lookupTokens'];
        }
        $types = array_merge(...$types);

        return $tokens->isAnyTokenKindsFound($types);
    }

    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Removes unneeded parentheses around control statements.',
            [
                new CodeSample(
                    '<?php
while ($x) { while ($y) { break (2); } }
clone($a);
while ($y) { continue (2); }
echo("foo");
print("foo");
return (1 + 2);
switch ($a) { case($x); }
yield(2);
'
                ),
                new CodeSample(
                    '<?php
while ($x) { while ($y) { break (2); } }
clone($a);
while ($y) { continue (2); }
echo("foo");
print("foo");
return (1 + 2);
switch ($a) { case($x); }
yield(2);
',
                    ['statements' => ['break', 'continue']]
                ),
            ]
        );
    }

    /**
     * Should be run before no_trailing_whitespace.
     *
     * {@inheritdoc}
     */
    public function getPriority()
    {
        return 30;
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        // Checks if specific statements are set and uses them in this case.
        $loops = array_intersect_key(self::$loops, array_flip($this->configuration['statements']));

        foreach ($tokens as $index => $token) {
            if (!$token->equalsAny(['(', [CT::T_BRACE_CLASS_INSTANTIATION_OPEN]])) {
                continue;
            }

            $blockStartIndex = $index;
            $index = $tokens->getPrevMeaningfulToken($index);
            $prevToken = $tokens[$index];

            foreach ($loops as $loop) {
                if (!$prevToken->isGivenKind($loop['lookupTokens'])) {
                    continue;
                }

                $blockEndIndex = $tokens->findBlockEnd(
                    $token->equals('(') ? Tokens::BLOCK_TYPE_PARENTHESIS_BRACE : Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION,
                    $blockStartIndex
                );
                $blockEndNextIndex = $tokens->getNextMeaningfulToken($blockEndIndex);

                if (!$tokens[$blockEndNextIndex]->equalsAny($loop['neededSuccessors'])) {
                    continue;
                }

                if (\array_key_exists('forbiddenContents', $loop)) {
                    $forbiddenTokenIndex = $tokens->getNextTokenOfKind($blockStartIndex, $loop['forbiddenContents']);
                    // A forbidden token is found and is inside the parenthesis.
                    if (null !== $forbiddenTokenIndex && $forbiddenTokenIndex < $blockEndIndex) {
                        continue;
                    }
                }

                if ($tokens[$blockStartIndex - 1]->isWhitespace() || $tokens[$blockStartIndex - 1]->isComment()) {
                    $tokens->clearTokenAndMergeSurroundingWhitespace($blockStartIndex);
                } else {
                    // Adds a space to prevent broken code like `return2`.
                    $tokens[$blockStartIndex] = new Token([T_WHITESPACE, ' ']);
                }

                $tokens->clearTokenAndMergeSurroundingWhitespace($blockEndIndex);
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function createConfigurationDefinition()
    {
        return new FixerConfigurationResolverRootless('statements', [
            (new FixerOptionBuilder('statements', 'List of control statements to fix.'))
                ->setAllowedTypes(['array'])
                ->setDefault([
                    'break',
                    'clone',
                    'continue',
                    'echo_print',
                    'return',
                    'switch_case',
                    'yield',
                ])
                ->getOption(),
        ], $this->getName());
    }
}


<?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\Tokenizer\Transformer;

use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * Transform `&` operator into CT::T_RETURN_REF in `function & foo() {}`.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 */
final class ReturnRefTransformer extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function getCustomTokens()
    {
        return [CT::T_RETURN_REF];
    }

    /**
     * {@inheritdoc}
     */
    public function getRequiredPhpVersionId()
    {
        return 50000;
    }

    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens, Token $token, $index)
    {
        if (
            $token->equals('&')
            && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(T_FUNCTION)
        ) {
            $tokens[$index] = new Token([CT::T_RETURN_REF, '&']);
        }
    }
}


<?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\DocBlock;

use PhpCsFixer\Preg;

/**
 * This class represents a docblock.
 *
 * It internally splits it up into "lines" that we can manipulate.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class DocBlock
{
    /**
     * The array of lines.
     *
     * @var Line[]
     */
    private $lines = [];

    /**
     * The array of annotations.
     *
     * @var null|Annotation[]
     */
    private $annotations;

    /**
     * Create a new docblock instance.
     *
     * @param string $content
     */
    public function __construct($content)
    {
        foreach (Preg::split('/([^\n\r]+\R*)/', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $line) {
            $this->lines[] = new Line($line);
        }
    }

    /**
     * Get the string representation of object.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->getContent();
    }

    /**
     * Get this docblock's lines.
     *
     * @return Line[]
     */
    public function getLines()
    {
        return $this->lines;
    }

    /**
     * Get a single line.
     *
     * @param int $pos
     *
     * @return null|Line
     */
    public function getLine($pos)
    {
        if (isset($this->lines[$pos])) {
            return $this->lines[$pos];
        }
    }

    /**
     * Get this docblock's annotations.
     *
     * @return Annotation[]
     */
    public function getAnnotations()
    {
        if (null === $this->annotations) {
            $this->annotations = [];
            $total = \count($this->lines);

            for ($index = 0; $index < $total; ++$index) {
                if ($this->lines[$index]->containsATag()) {
                    // get all the lines that make up the annotation
                    $lines = \array_slice($this->lines, $index, $this->findAnnotationLength($index), true);
                    $annotation = new Annotation($lines);
                    // move the index to the end of the annotation to avoid
                    // checking it again because we know the lines inside the
                    // current annotation cannot be part of another annotation
                    $index = $annotation->getEnd();
                    // add the current annotation to the list of annotations
                    $this->annotations[] = $annotation;
                }
            }
        }

        return $this->annotations;
    }

    /**
     * @param int $pos
     *
     * @return null|Annotation
     */
    public function getAnnotation($pos)
    {
        $annotations = $this->getAnnotations();

        if (isset($annotations[$pos])) {
            return $annotations[$pos];
        }
    }

    /**
     * Get specific types of annotations only.
     *
     * If none exist, we're returning an empty array.
     *
     * @param string|string[] $types
     *
     * @return Annotation[]
     */
    public function getAnnotationsOfType($types)
    {
        $annotations = [];
        $types = (array) $types;

        foreach ($this->getAnnotations() as $annotation) {
            $tag = $annotation->getTag()->getName();
            foreach ($types as $type) {
                if ($type === $tag) {
                    $annotations[] = $annotation;
                }
            }
        }

        return $annotations;
    }

    /**
     * Get the actual content of this docblock.
     *
     * @return string
     */
    public function getContent()
    {
        return implode('', $this->lines);
    }

    private function findAnnotationLength($start)
    {
        $index = $start;

        while ($line = $this->getLine(++$index)) {
            if ($line->containsATag()) {
                // we've 100% reached the end of the description if we get here
                break;
            }

            if (!$line->containsUsefulContent()) {
                // if next line is also non-useful, or contains a tag, then we're done here
                $next = $this->getLine($index + 1);
                if (null === $next || !$next->containsUsefulContent() || $next->containsATag()) {
                    break;
                }
                // otherwise, continue, the annotation must have contained a blank line in its description
            }
        }

        return $index - $start;
    }
}


<?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\Tokenizer\Transformer;

use PhpCsFixer\Tokenizer\AbstractTransformer;
use PhpCsFixer\Tokenizer\CT;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * Transform `class` class' constant from T_CLASS into CT::T_CLASS_CONSTANT.
 *
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * @internal
 */
final class ClassConstantTransformer extends AbstractTransformer
{
    /**
     * {@inheritdoc}
     */
    public function getCustomTokens()
    {
        return [CT::T_CLASS_CONSTANT];
    }

    /**
     * {@inheritdoc}
     */
    public function getRequiredPhpVersionId()
    {
        return 50500;
    }

    /**
     * {@inheritdoc}
     */
    public function process(Tokens $tokens, Token $token, $index)
    {
        if (!$token->equalsAny([
            [T_CLASS, 'class'],
            [T_STRING, 'class'],
        ], false)) {
            return;
        }

        $prevIndex = $tokens->getPrevMeaningfulToken($index);
        $prevToken = $tokens[$prevIndex];

        if ($prevToken->isGivenKind(T_DOUBLE_COLON)) {
            $tokens[$index] = new Token([CT::T_CLASS_CONSTANT, $token->getContent()]);
        }
    }
}


<?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\StringNotation;

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

/**
 * @author Gregor Harlan <gharlan@web.de>
 */
final class HeredocToNowdocFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Convert `heredoc` to `nowdoc` where possible.',
            [
                new CodeSample(
                    <<<'EOF'
<?php $a = <<<"TEST"
Foo
TEST;

EOF
                ),
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(T_START_HEREDOC);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_START_HEREDOC) || false !== strpos($token->getContent(), "'")) {
                continue;
            }

            if ($tokens[$index + 1]->isGivenKind(T_END_HEREDOC)) {
                $tokens[$index] = $this->convertToNowdoc($token);

                continue;
            }

            if (
                !$tokens[$index + 1]->isGivenKind(T_ENCAPSED_AND_WHITESPACE) ||
                !$tokens[$index + 2]->isGivenKind(T_END_HEREDOC)
            ) {
                continue;
            }

            $content = $tokens[$index + 1]->getContent();
            // regex: odd number of backslashes, not followed by dollar
            if (Preg::match('/(?<!\\\\)(?:\\\\{2})*\\\\(?![$\\\\])/', $content)) {
                continue;
            }

            $tokens[$index] = $this->convertToNowdoc($token);
            $content = str_replace(['\\\\', '\\$'], ['\\', '$'], $content);
            $tokens[$index + 1] = new Token([
                $tokens[$index + 1]->getId(),
                $content,
            ]);
        }
    }

    /**
     * Transforms the heredoc start token to nowdoc notation.
     *
     * @param Token $token
     *
     * @return Token
     */
    private function convertToNowdoc(Token $token)
    {
        return new Token([
            $token->getId(),
            Preg::replace('/^([Bb]?<<<)([ \t]*)"?([^\s"]+)"?/', '$1$2\'$3\'', $token->getContent()),
        ]);
    }
}


<?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\Phpdoc;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\DocBlock\DocBlock;
use PhpCsFixer\DocBlock\Line;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Preg;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Graham Campbell <graham@alt-three.com>
 */
final class PhpdocVarWithoutNameFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            '`@var` and `@type` annotations should not contain the variable name.',
            [new CodeSample('<?php
final class Foo
{
    /**
     * @var int $bar
     */
    public $bar;

    /**
     * @type $baz float
     */
    public $baz;
}
')]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(T_DOC_COMMENT);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if (!$token->isGivenKind(T_DOC_COMMENT)) {
                continue;
            }

            $doc = new DocBlock($token->getContent());

            // don't process single line docblocks
            if (1 === \count($doc->getLines())) {
                continue;
            }

            $annotations = $doc->getAnnotationsOfType(['param', 'return', 'type', 'var']);

            // only process docblocks where the first meaningful annotation is @type or @var
            if (!isset($annotations[0]) || !\in_array($annotations[0]->getTag()->getName(), ['type', 'var'], true)) {
                continue;
            }

            $this->fixLine($doc->getLine($annotations[0]->getStart()));

            $tokens[$index] = new Token([T_DOC_COMMENT, $doc->getContent()]);
        }
    }

    private function fixLine(Line $line)
    {
        $content = $line->getContent();

        Preg::matchAll('/ \$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/', $content, $matches);

        if (isset($matches[0][0])) {
            $line->setContent(str_replace($matches[0][0], '', $content));
        }
    }
}


<?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\ArrayNotation;

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

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 */
final class NormalizeIndexBraceFixer extends AbstractFixer
{
    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'Array index should always be written by using square braces.',
            [new CodeSample("<?php\necho \$sample{\$index};\n")]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isTokenKindFound(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN);
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        foreach ($tokens as $index => $token) {
            if ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) {
                $tokens[$index] = new Token('[');
            } elseif ($token->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE)) {
                $tokens[$index] = new Token(']');
            }
        }
    }
}


<?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\Whitespace;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\AllowedValueSubset;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use PhpCsFixer\Tokenizer\TokensAnalyzer;

/**
 * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
 * @author Andreas Möller <am@localheinz.com>
 * @author SpacePossum
 */
final class BlankLineBeforeStatementFixer extends AbstractFixer implements ConfigurationDefinitionFixerInterface, WhitespacesAwareFixerInterface
{
    /**
     * @var array
     */
    private static $tokenMap = [
        'break' => T_BREAK,
        'case' => T_CASE,
        'continue' => T_CONTINUE,
        'declare' => T_DECLARE,
        'default' => T_DEFAULT,
        'die' => T_EXIT,
        'do' => T_DO,
        'exit' => T_EXIT,
        'for' => T_FOR,
        'foreach' => T_FOREACH,
        'goto' => T_GOTO,
        'if' => T_IF,
        'include' => T_INCLUDE,
        'include_once' => T_INCLUDE_ONCE,
        'require' => T_REQUIRE,
        'require_once' => T_REQUIRE_ONCE,
        'return' => T_RETURN,
        'switch' => T_SWITCH,
        'throw' => T_THROW,
        'try' => T_TRY,
        'while' => T_WHILE,
        'yield' => T_YIELD,
    ];

    /**
     * @var array
     */
    private $fixTokenMap = [];

    /**
     * {@inheritdoc}
     */
    public function configure(array $configuration = null)
    {
        parent::configure($configuration);

        $this->fixTokenMap = [];

        foreach ($this->configuration['statements'] as $key) {
            $this->fixTokenMap[$key] = self::$tokenMap[$key];
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getDefinition()
    {
        return new FixerDefinition(
            'An empty line feed must precede any configured statement.',
            [
                new CodeSample(
                    '<?php
function A() {
    echo 1;
    return 1;
}
'
                ),
                new CodeSample(
                    '<?php
switch ($foo) {
    case 42:
        $bar->process();
        break;
    case 44:
        break;
}
',
                    [
                        'statements' => ['break'],
                    ]
                ),
                new CodeSample(
                    '<?php
foreach ($foo as $bar) {
    if ($bar->isTired()) {
        $bar->sleep();
        continue;
    }
}
',
                    [
                        'statements' => ['continue'],
                    ]
                ),
                new CodeSample(
                    '<?php
if ($foo === false) {
    die(0);
} else {
    $bar = 9000;
    die(1);
}
',
                    [
                        'statements' => ['die'],
                    ]
                ),
                new CodeSample(
                    '<?php
$i = 0;
do {
    echo $i;
} while ($i > 0);
',
                    [
                        'statements' => ['do'],
                    ]
                ),
                new CodeSample(
                    '<?php
if ($foo === false) {
    exit(0);
} else {
    $bar = 9000;
    exit(1);
}
',
                    [
                        'statements' => ['exit'],
                    ]
                ),
                new CodeSample(
                    '<?php
a:

if ($foo === false) {
    goto a;
} else {
    $bar = 9000;
    goto b;
}
',
                    [
                        'statements' => ['goto'],
                    ]
                ),
                new CodeSample(
                    '<?php
$a = 9000;
if (true) {
    $foo = $bar;
}
',
                    [
                        'statements' => ['if'],
                    ]
                ),
                new CodeSample(
                    '<?php

if (true) {
    $foo = $bar;
    return;
}
',
                    [
                        'statements' => ['return'],
                    ]
                ),
                new CodeSample(
                    '<?php
$a = 9000;
switch ($a) {
    case 42:
        break;
}
',
                    [
                        'statements' => ['switch'],
                    ]
                ),
                new CodeSample(
                    '<?php
if (null === $a) {
    $foo->bar();
    throw new \UnexpectedValueException("A cannot be null");
}
',
                    [
                        'statements' => ['throw'],
                    ]
                ),
                new CodeSample(
                    '<?php
$a = 9000;
try {
    $foo->bar();
} catch (\Exception $exception) {
    $a = -1;
}
',
                    [
                        'statements' => ['try'],
                    ]
                ),
                new CodeSample(
                    '<?php

if (true) {
    $foo = $bar;
    yield $foo;
}
',
                    [
                        'statements' => ['yield'],
                    ]
                ),
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getPriority()
    {
        // should be run after NoUselessReturnFixer and NoExtraBlankLinesFixer
        return -21;
    }

    /**
     * {@inheritdoc}
     */
    public function isCandidate(Tokens $tokens)
    {
        return $tokens->isAnyTokenKindsFound(array_values($this->fixTokenMap));
    }

    /**
     * {@inheritdoc}
     */
    protected function applyFix(\SplFileInfo $file, Tokens $tokens)
    {
        $lineEnding = $this->whitespacesConfig->getLineEnding();
        $tokenKinds = array_values($this->fixTokenMap);
        $analyzer = new TokensAnalyzer($tokens);

        for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) {
            $token = $tokens[$index];

            if (!$token->isGivenKind($tokenKinds) || ($token->isGivenKind(T_WHILE) && $analyzer->isWhilePartOfDoWhile($index))) {
                continue;
            }

            $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)];

            if (!$prevNonWhitespaceToken->equalsAny([';', '}'])) {
                continue;
            }

            $prevIndex = $index - 1;
            $prevToken = $tokens[$prevIndex];

            if ($prevToken->isWhitespace()) {
                $countParts = substr_count($prevToken->getContent(), "\n");

                if (0 === $countParts) {
                    $tokens[$prevIndex] = new Token([T_WHITESPACE, rtrim($prevToken->getContent(), " \t").$lineEnding.$lineEnding]);
                } elseif (1 === $countParts) {
                    $tokens[$prevIndex] = new Token([T_WHITESPACE, $lineEnding.$prevToken->getContent()]);
                }
            } else {
                $tokens->insertAt($index, new Token([T_WHITESPACE, $lineEnding.$lineEnding]));

                ++$index;
                ++$limit;
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function createConfigurationDefinition()
    {
        return new FixerConfigurationResolver([
            (new FixerOptionBuilder('statements', 'List of statements which must be preceded by an empty line.'))
                ->setAllowedTypes(['array'])
                ->setAllowedValues([new AllowedValueSubset(array_keys(self::$tokenMap))])
                ->setDefault([
                    'break',
                    'continue',
                    'declare',
                    'return',
                    'throw',
                    'try',
                ])
                ->getOption(),
        ]);
    }
}