<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\SaasBundle\Doctrine\Filter;

use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
use Serenity\CoreBundle\Saas\SerenitySaasContext;
use Serenity\CoreBundle\Shared\Feature\SerenitySaasInterface;

class SerenitySaasFilter extends SQLFilter
{
    public function addFilterConstraint(ClassMetadata $targetEntity, string $targetTableAlias): string
    {
        if (!\in_array(SerenitySaasInterface::class, class_implements($targetEntity->getName()), true)) {
            return '';
        }

        if (null === SerenitySaasContext::$identifierSerenityId) {
            return \sprintf('%s.saasIdentifier IS NULL', $targetTableAlias);
        }

        return \sprintf("%s.saasIdentifier = '%s'", $targetTableAlias, SerenitySaasContext::$identifierSerenityId);
    }
}
