<?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_CONTAINS(json_doc, candidate) DQL function for MariaDB/MySQL.
 * Usage: WHERE JSON_CONTAINS(b.tags, :tag) = 1
 */
class JsonContains extends FunctionNode
{
    private Node $jsonDoc;
    private Node $candidate;

    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->candidate = $parser->StringPrimary();
        $parser->match(TokenType::T_CLOSE_PARENTHESIS);
    }

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