<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Orm;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\Subselect;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;

/**
 * Function that selects the first item of a subquery.
 * This is required, because DQL does not have OFFSET / LIMIT built into the language.
 *
 * This function must be registered with doctrine as a "custom string function".
 *
 * @see https://www.colinodell.com/blog/201703/limiting-subqueries-doctrine-2-dql
 * @see https://github.com/doctrine/orm/issues/5409#issuecomment-636911410
 */
final class First extends FunctionNode
{
    /** @var Subselect */
    private $subselect;

    public function parse(Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->subselect = $parser->Subselect();
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }

    public function getSql(SqlWalker $sqlWalker)
    {
        return '(' . $this->subselect->dispatch($sqlWalker) . ' LIMIT 1)';
    }
}
