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

use PhpCsFixer\AbstractFixer;
use PhpCsFixer\Fixer\ConfigurableFixerInterface;
use PhpCsFixer\Fixer\ConfigurableFixerTrait;
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\Analyzer\Analysis\AttributeAnalysis;
use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer;
use PhpCsFixer\Tokenizer\FCT;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @phpstan-import-type _AttributeItems from AttributeAnalysis
 * @phpstan-import-type _AttributeItem from AttributeAnalysis
 *
 * @phpstan-type _AutogeneratedInputConfiguration array{
 *  attributes?: list<class-string>,
 * }
 * @phpstan-type _AutogeneratedComputedConfiguration array{
 *  attributes: list<class-string>,
 * }
 *
 * @implements ConfigurableFixerInterface<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration>
 *
 * @author Raffaele Carelle <raffaele.carelle@gmail.com>
 *
 * @no-named-arguments Parameter names are not covered by the backward compatibility promise.
 */
final class GeneralAttributeRemoveFixer extends AbstractFixer implements ConfigurableFixerInterface
{
    /** @use ConfigurableFixerTrait<_AutogeneratedInputConfiguration, _AutogeneratedComputedConfiguration> */
    use ConfigurableFixerTrait;

    public function getDefinition(): FixerDefinitionInterface
    {
        return new FixerDefinition(
            'Removes configured attributes by their respective FQN.',
            [
                new CodeSample(
                    <<<'PHP'
                        <?php
                        #[\A\B\Foo]
                        function foo() {}

                        PHP,
                    ['attributes' => ['\A\B\Foo']],
                ),
                new CodeSample(
                    <<<'PHP'
                        <?php
                        use A\B\Bar as BarAlias;

                        #[\A\B\Foo]
                        #[BarAlias]
                        function foo() {}

                        PHP,
                    ['attributes' => ['\A\B\Foo', 'A\B\Bar']],
                ),
            ],
        );
    }

    public function getPriority(): int
    {
        return 0;
    }

    public function isCandidate(Tokens $tokens): bool
    {
        return $tokens->isTokenKindFound(FCT::T_ATTRIBUTE);
    }

    protected function applyFix(\SplFileInfo $file, Tokens $tokens): void
    {
        if (0 === \count($this->configuration['attributes'])) {
            return;
        }

        $index = 0;

        while (null !== $index = $tokens->getNextTokenOfKind($index, [[\T_ATTRIBUTE]])) {
            $attributeAnalysis = AttributeAnalyzer::collectOne($tokens, $index);

            $endIndex = $attributeAnalysis->getEndIndex();

            $removedCount = 0;
            foreach ($attributeAnalysis->getAttributes() as $element) {
                $fullname = AttributeAnalyzer::determineAttributeFullyQualifiedName($tokens, $element['name'], $element['start']);

                if (!\in_array($fullname, $this->configuration['attributes'], true)) {
                    continue;
                }

                $tokens->clearRange($element['start'], $element['end']);
                ++$removedCount;

                $siblingIndex = $tokens->getNonEmptySibling($element['end'], 1);

                // Clear element comma
                if (',' === $tokens[$siblingIndex]->getContent()) {
                    $tokens->clearAt($siblingIndex);
                }
            }

            // Clear whole attribute if all are removed (multiline attribute case)
            if (\count($attributeAnalysis->getAttributes()) === $removedCount) {
                $tokens->clearRange($attributeAnalysis->getStartIndex(), $attributeAnalysis->getEndIndex());
            }

            // Clear trailing comma
            $tokenIndex = $tokens->getMeaningfulTokenSibling($attributeAnalysis->getClosingBracketIndex(), -1);
            if (',' === $tokens[$tokenIndex]->getContent()) {
                $tokens->clearAt($tokenIndex);
            }

            $index = $endIndex;
        }
    }

    protected function createConfigurationDefinition(): FixerConfigurationResolverInterface
    {
        return new FixerConfigurationResolver([
            (new FixerOptionBuilder('attributes', 'List of FQNs of attributes for removal.'))
                ->setAllowedTypes(['class-string[]'])
                ->setDefault([])
                ->getOption(),
        ]);
    }
}
