<?php

namespace App\Shared\Doctrine;

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

/**
 * JSON_EXTRACT(json_doc, path) DQL function for MariaDB/MySQL.
 * Usage: WHERE JSON_EXTRACT(ws.setting, '$.meta.online_booking_enabled') != 'false'
 */
class JsonExtract extends FunctionNode
{
    private Node $jsonDoc;
    private Node $path;

    public function parse(Parser $parser): void
    {
        $parser->match(TokenType::T_IDENTIFIER);
        $parser->match(TokenType::T_OPEN_PARENTHESIS);
        $this->jsonDoc = $parser->StringPrimary();
        $parser->match(TokenType::T_COMMA);
        $this->path = $parser->StringPrimary();
        $parser->match(TokenType::T_CLOSE_PARENTHESIS);
    }

    public function getSql(SqlWalker $sqlWalker): string
    {
        return sprintf(
            'JSON_EXTRACT(%s, %s)',
            $this->jsonDoc->dispatch($sqlWalker),
            $this->path->dispatch($sqlWalker)
        );
    }
}
