<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Translation;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\Expr\Andx;
use Doctrine\ORM\Query\Expr\Base;
use Doctrine\ORM\Query\Expr\Comparison;
use Doctrine\ORM\QueryBuilder;

/**
 * Query builder that adds a certain set of fixed expression to each query no matter what someone does
 * with that query. Helpful, when adding global restrictions to all queries.
 */
class QueryBuilderWithFixedExpression extends QueryBuilder
{

    /** @var bool */
    private $isBuildingQuery = false;

    /** @var Base */
    private $fixedExpression;

    public function __construct(EntityManagerInterface $em)
    {
        parent::__construct($em);
        $this->resetFixedExpression();
    }

    public function resetFixedExpression(): void
    {
        $this->fixedExpression = new Andx();
    }

    /**
     * @param Base|Comparison $languageExpression
     */
    public function addFixedExpression($languageExpression): void
    {
        $this->fixedExpression->add($languageExpression);
    }

    public function getDQL(): string
    {
        $this->isBuildingQuery = true;
        $dql = parent::getDQL();
        $this->isBuildingQuery = false;
        return $dql;
    }

    public function getDQLPart($queryPartName)
    {
        if ($queryPartName === 'where' && $this->isBuildingQuery && $this->fixedExpression->count() > 0) {
            return new Andx(
                [
                    parent::getDQLPart('where'),
                    $this->fixedExpression,
                ]
            );
        }

        return parent::getDQLPart($queryPartName);
    }
}
