<?php
declare(strict_types=1);

namespace App\Doctrine\Access;

use App\Doctrine\AbstractExtension;
use App\Entity\Access\PersonalizedList;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Class CurrentUserPersonalizedListExtension : Filtre de sécurité par défaut pour une resource PersonalizedList
 * @package App\Doctrine\Access
 */
final class CurrentUserPersonalizedListExtension extends AbstractExtension
{
    public function __construct(private Security $security)
    { }

    protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
    {
        if (PersonalizedList::class !== $resourceClass) {
            return;
        }

        /** @var PersonalizedList $currentUser */
        $currentUser = $this->security->getUser();
        $rootAlias = $queryBuilder->getRootAliases()[0];
        $queryBuilder->andWhere(sprintf('%s.access = :current_access', $rootAlias));
        $queryBuilder->setParameter('current_access', $currentUser);
    }
}