<?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\Parser;
use Doctrine\ORM\Query\SqlWalker;

/**
 * Return an aggregation of values in a json representation, as a string.
 *
 * Internally, this function use the postgresql `jsonb_agg` function. Using
 * json allow to aggregate data from different types without have to cast them.
 */
class JsonAggregate extends FunctionNode
{
    private ?\Doctrine\ORM\Query\AST\Node $expr = null;

    public function getSql(SqlWalker $sqlWalker)
    {
        return sprintf('jsonb_agg(%s)', $this->expr->dispatch($sqlWalker));
    }

    public function parse(Parser $parser)
    {
        $parser->match(\Doctrine\ORM\Query\TokenType::T_IDENTIFIER);
        $parser->match(\Doctrine\ORM\Query\TokenType::T_OPEN_PARENTHESIS);
        $this->expr = $parser->StringPrimary();
        $parser->match(\Doctrine\ORM\Query\TokenType::T_CLOSE_PARENTHESIS);
    }
}
