<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Doctrine\DQL;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\AST\Node;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;

/**
 * Postgresql LEAST function.
 *
 * Borrowed from https://github.com/beberlei/DoctrineExtensions/blob/master/src/Query/Postgresql/Least.php
 * (https://github.com/beberlei/DoctrineExtensions/blob/master/LICENSE) and
 * https://gist.github.com/olimsaidov/4bbd530b1b645ce75e1bbb781b5dd91f
 */
class Least extends FunctionNode
{
    /**
     * @var array|Node[]
     */
    private array $exprs = [];

    public function getSql(SqlWalker $sqlWalker)
    {
        return 'LEAST('.implode(', ', array_map(static fn (Node $expr) => $expr->dispatch($sqlWalker), $this->exprs)).')';
    }

    public function parse(Parser $parser)
    {
        $this->exprs = [];

        $lexer = $parser->getLexer();
        $parser->match(\Doctrine\ORM\Query\TokenType::T_IDENTIFIER);
        $parser->match(\Doctrine\ORM\Query\TokenType::T_OPEN_PARENTHESIS);
        $this->exprs[] = $parser->ArithmeticPrimary();

        while (\Doctrine\ORM\Query\TokenType::T_COMMA === $lexer->lookahead['type']) {
            $parser->match(\Doctrine\ORM\Query\TokenType::T_COMMA);
            $this->exprs[] = $parser->ArithmeticPrimary();
        }

        $parser->match(\Doctrine\ORM\Query\TokenType::T_CLOSE_PARENTHESIS);
    }
}
