<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Modified by __root__ on 29-March-2026 using Strauss.
 * @see https://github.com/BrianHenryIE/strauss
 */

namespace Dreitier\Nadi\Vendor\Twig\TokenParser;

use Dreitier\Nadi\Vendor\Twig\Error\SyntaxError;
use Dreitier\Nadi\Vendor\Twig\Node\Node;
use Dreitier\Nadi\Vendor\Twig\Node\TypesNode;
use Dreitier\Nadi\Vendor\Twig\Token;
use Dreitier\Nadi\Vendor\Twig\TokenStream;

/**
 * Declare variable types.
 *
 *  {% types {foo: 'number', bar?: 'string'} %}
 *
 * @author Jeroen Versteeg <jeroen@alisqi.com>
 *
 * @internal
 */
final class TypesTokenParser extends AbstractTokenParser
{
    public function parse(Token $token): Node
    {
        $stream = $this->parser->getStream();
        $types = $this->parseSimpleMappingExpression($stream);
        $stream->expect(Token::BLOCK_END_TYPE);

        return new TypesNode($types, $token->getLine());
    }

    /**
     * @return array<string, array{type: string, optional: bool}>
     *
     * @throws SyntaxError
     */
    private function parseSimpleMappingExpression(TokenStream $stream): array
    {
        $enclosed = null !== $stream->nextIf(Token::PUNCTUATION_TYPE, '{');
        $types = [];
        $first = true;
        while (!($stream->test(Token::PUNCTUATION_TYPE, '}') || $stream->test(Token::BLOCK_END_TYPE))) {
            if (!$first) {
                $stream->expect(Token::PUNCTUATION_TYPE, ',', 'A type string must be followed by a comma');

                // trailing ,?
                if ($stream->test(Token::PUNCTUATION_TYPE, '}') || $stream->test(Token::BLOCK_END_TYPE)) {
                    break;
                }
            }
            $first = false;

            $nameToken = $stream->expect(Token::NAME_TYPE);

            if ($stream->nextIf(Token::OPERATOR_TYPE, '?:')) {
                $isOptional = true;
            } else {
                $isOptional = null !== $stream->nextIf(Token::OPERATOR_TYPE, '?');
                $stream->expect(Token::PUNCTUATION_TYPE, ':', 'A type name must be followed by a colon (:)');
            }

            $valueToken = $stream->expect(Token::STRING_TYPE);

            $types[$nameToken->getValue()] = [
                'type' => $valueToken->getValue(),
                'optional' => $isOptional,
            ];
        }

        if ($enclosed) {
            $stream->expect(Token::PUNCTUATION_TYPE, '}', 'An opened mapping is not properly closed');
        }

        return $types;
    }

    public function getTag(): string
    {
        return 'types';
    }
}
