<?php

declare(strict_types=1);

/*
 * 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\Strict;

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver;
use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
use PhpCsFixer\FixerConfiguration\FixerOptionBuilder;
use PhpCsFixer\FixerDefinition\CodeSample;
use PhpCsFixer\FixerDefinition\FixerDefinition;
use PhpCsFixer\FixerDefinition\FixerDefinitionInterface;
use PhpCsFixer\Tokenizer\Token;
use PhpCsFixer\Tokenizer\Tokens;
use Symfony\Component\OptionsResolver\Options;

/**
 * @phpstan-type _AutogeneratedInputConfiguration array{
 *  preserve_existing_declaration?: bool,
 *  strategy?: 'add_when_missing'|'enforce'|'remove',
 * }
 * @phpstan-type _AutogeneratedComputedConfiguration array{
 *  strategy: 'add_when_missing'|'enforce'|'remove',
 * }
 *
 * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 *
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
 */
final class DeclareStrictTypesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface
{
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
    use ConfigurableFixerTrait;

    public function getDefinition(): FixerDefinitionInterface
    {
        return new FixerDefinition(
            'Force a strict types mode in all files.',
            [
                new CodeSample(
                    "<?php\n",
                ),
                new CodeSample(
                    "<?php\ndeclare(Strict_Types=0);\n",
                    ['strategy' => 'enforce'],
                ),
                new CodeSample(
                    "<?php\ndeclare(Strict_Types=0);\n",
                    ['strategy' => 'add_when_missing'],
                ),
                new CodeSample(
                    "<?php\ndeclare(strict_types=1);\n",
                    ['strategy' => 'remove'],
                ),
                new CodeSample(
                    "<?php\ndeclare(strict_types=1, ticks=1);\n",
                    ['strategy' => 'remove'],
                ),
                new CodeSample( // @TODO v4.0: remove me, "preserve_existing_declaration" option is deprecated
                    "<?php\ndeclare(Strict_Types=0);\n",
                    ['preserve_existing_declaration' => false],
                ),
                new CodeSample( // @TODO v4.0: remove me, "preserve_existing_declaration" option is deprecated
                    "<?php\ndeclare(Strict_Types=0);\n",
                    ['preserve_existing_declaration' => true],
                ),
            ],
            null,
            'Enabling strict types will stop non strict code from working.',
        );
    }

    /**
     * {@inheritdoc}
     *
     * Must run before BlankLineAfterOpeningTagFixer, DeclareEqualNormalizeFixer, HeaderCommentFixer.
     */
    public function getPriority(): int
    {
        return 2;
    }

    public function isCandidate(Tokens $tokens): bool
    {
        return $tokens->isMonolithicPhp() && !$tokens->isTokenKindFound(\T_OPEN_TAG_WITH_ECHO);
    }

    public function isRisky(): bool
    {
        return true;
    }

    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
    {
        $fixerName = $this->getName();

        return new FixerConfigurationResolver([
            (new FixerOptionBuilder('preserve_existing_declaration', 'Whether existing strict_types=? should be preserved and not overridden.'))
                ->setAllowedTypes(['bool'])
                ->setDefault(false)
                ->setNormalizer(static function (Options $options, bool $value) use ($fixerName): bool {
                    if (true === $value && 'enforce' !== $options['strategy']) {
                        throw new InvalidFixerConfigurationException(
                            $fixerName,
                            'Cannot configure "strategy" in parallel to configuring "preserve_existing_declaration".',
                        );
                    }

                    return $value;
                })
                ->setDeprecationMessage('Use `strategy` to configure behaviour.') // @TODO 4.0: remove option and normalizer related to it
                ->getOption(),
            (new FixerOptionBuilder('strategy', 'Whether existing strict_types=? should be enforced, removed (effectively turning strict mode off and using the engine into default type coercion mode), or added when missing.'))
                ->setAllowedValues(['remove', 'add_when_missing', 'enforce'])
                ->setDefault('enforce')
                ->getOption(),
        ]);
    }

    /**
     * @TODO v4.0: remove the hook
     */
    protected function configurePostNormalisation(): void
    {
        // @phpstan-ignore-next-line offsetAccess.notFound "preserve_existing_declaration" option is deprecated
        if ('enforce' === $this->configuration['strategy'] && true === $this->configuration['preserve_existing_declaration']) {
            $this->configuration['strategy'] = 'add_when_missing';
        }

        // @phpstan-ignore-next-line unset.offset "preserve_existing_declaration" option is deprecated
        unset($this->configuration['preserve_existing_declaration']);
    }

    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
    {
        $openTagIndex = $tokens[0]->isGivenKind(\T_INLINE_HTML) ? 1 : 0;

        $declaration = $this->getStrictTypesDeclaration($tokens);

        if ('remove' === $this->configuration['strategy']) {
            if (null !== $declaration) {
                $this->removeStrictTypesDeclaration($tokens, $declaration);
            }

            return;
        }

        if (null === $declaration) {
            $this->insertSequence($openTagIndex, $tokens); // declaration not found, insert one

            return;
        }

        $this->fixStrictTypesCasingAndValue($tokens, $declaration['sequence']);
    }

    /**
     * @return null|array{declare_index: int, open_parenthesis: int, close_parenthesis: int, sequence: array<int, Token>}
     */
    private function getStrictTypesDeclaration(Tokens $tokens): ?array
    {
        foreach ($tokens->findGivenKind(\T_DECLARE) as $index => $token) {
            $openParenthesis = $tokens->getNextMeaningfulToken($index);
            $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS, $openParenthesis);

            $strictTypesSequence = $tokens->findSequence([[\T_STRING, 'strict_types'], '=', [\T_LNUMBER]], $openParenthesis, $closeParenthesis, false);
            if (null === $strictTypesSequence) {
                continue;
            }

            return [
                'declare_index' => $index,
                'open_parenthesis' => $openParenthesis,
                'close_parenthesis' => $closeParenthesis,
                'sequence' => $strictTypesSequence,
            ];
        }

        return null;
    }

    /**
     * @param array{declare_index: int, open_parenthesis: int, close_parenthesis: int, sequence: array<int, Token>} $declaration
     */
    private function removeStrictTypesDeclaration(Tokens $tokens, array $declaration): void
    {
        $sequenceIndices = array_keys($declaration['sequence']);
        $sequenceIndexMap = array_fill_keys($sequenceIndices, true);
        \assert(\array_key_exists(0, $sequenceIndices));
        $sequenceStart = $sequenceIndices[0];
        $sequenceEnd = $sequenceIndices[\count($sequenceIndices) - 1];

        if (!$this->hasOtherDeclareOptions($tokens, $declaration['open_parenthesis'], $declaration['close_parenthesis'], $sequenceIndexMap)) {
            $this->removeDeclareStatement($tokens, $declaration['declare_index'], $declaration['close_parenthesis']);

            return;
        }

        for ($index = $sequenceEnd; $index >= $sequenceStart; --$index) {
            if ($tokens->isEmptyAt($index)) {
                continue;
            }

            $tokens->clearTokenAndMergeSurroundingWhitespace($index);
        }

        $prevMeaningful = $tokens->getPrevMeaningfulToken($sequenceStart);
        if (null !== $prevMeaningful && $tokens[$prevMeaningful]->equals(',')) {
            $tokens->clearTokenAndMergeSurroundingWhitespace($prevMeaningful);

            $nextMeaningful = $tokens->getNextMeaningfulToken($sequenceEnd);
            if (null !== $nextMeaningful) {
                $tokens->removeLeadingWhitespace($nextMeaningful, " \t");
            }

            return;
        }

        $nextMeaningful = $tokens->getNextMeaningfulToken($sequenceEnd);
        if (null !== $nextMeaningful && $tokens[$nextMeaningful]->equals(',')) {
            $tokens->clearTokenAndMergeSurroundingWhitespace($nextMeaningful);

            $afterComma = $tokens->getNextMeaningfulToken($nextMeaningful);
            if (null !== $afterComma) {
                $tokens->removeLeadingWhitespace($afterComma, " \t");
            }
        }
    }

    /**
     * @param array<int, true> $sequenceIndexMap
     */
    private function hasOtherDeclareOptions(Tokens $tokens, int $openParenthesis, int $closeParenthesis, array $sequenceIndexMap): bool
    {
        $index = $tokens->getNextMeaningfulToken($openParenthesis);
        while (null !== $index && $index < $closeParenthesis) {
            if ($tokens[$index]->isGivenKind(\T_STRING) && !isset($sequenceIndexMap[$index])) {
                return true;
            }

            $index = $tokens->getNextMeaningfulToken($index);
        }

        return false;
    }

    private function removeDeclareStatement(Tokens $tokens, int $declareIndex, int $closeParenthesis): void
    {
        $semicolonIndex = $tokens->getNextMeaningfulToken($closeParenthesis);
        if (null === $semicolonIndex) {
            return;
        }

        for ($index = $semicolonIndex; $index >= $declareIndex; --$index) {
            if ($tokens->isEmptyAt($index)) {
                continue;
            }

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

    /**
     * @param array<int, Token> $sequence
     */
    private function fixStrictTypesCasingAndValue(Tokens $tokens, array $sequence): void
    {
        foreach ($sequence as $index => $token) {
            if ($token->isGivenKind(\T_STRING)) {
                $tokens[$index] = new Token([\T_STRING, strtolower($token->getContent())]);

                continue;
            }

            if ($token->isGivenKind(\T_LNUMBER) && 'enforce' === $this->configuration['strategy']) {
                $tokens[$index] = new Token([\T_LNUMBER, '1']);

                break;
            }
        }
    }

    private function insertSequence(int $openTagIndex, Tokens $tokens): void
    {
        $sequence = [
            new Token([\T_DECLARE, 'declare']),
            new Token('('),
            new Token([\T_STRING, 'strict_types']),
            new Token('='),
            new Token([\T_LNUMBER, '1']),
            new Token(')'),
            new Token(';'),
        ];
        $nextIndex = $openTagIndex + \count($sequence) + 1;

        $tokens->insertAt($openTagIndex + 1, $sequence);

        // transform "<?php" or "<?php\n" to "<?php " if needed
        $content = $tokens[$openTagIndex]->getContent();
        if (!str_contains($content, ' ') || str_contains($content, "\n")) {
            $tokens[$openTagIndex] = new Token([$tokens[$openTagIndex]->getId(), trim($tokens[$openTagIndex]->getContent()).' ']);
        }

        if (\count($tokens) === $nextIndex) {
            return; // no more tokens after sequence, single_blank_line_at_eof might add a line
        }

        $lineEnding = $this->whitespacesConfig->getLineEnding();
        if ($tokens[$nextIndex]->isWhitespace()) {
            $content = $tokens[$nextIndex]->getContent();
            $tokens[$nextIndex] = new Token([\T_WHITESPACE, $lineEnding.ltrim($content, " \t")]);
        } else {
            $tokens->insertAt($nextIndex, new Token([\T_WHITESPACE, $lineEnding]));
        }
    }
}
