<?php declare(strict_types=1);
namespace App\Security\Voter\Favorite;
use App\Doctrine\Cache\CacheDecider;
use App\Entity\Tag;
use App\Entity\User;
use App\Repository\FavoriteRepository;
use App\Security\Voter\AbstractUserAwareVoter;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class AddFavoriteVoter extends AbstractUserAwareVoter
{
public const ATTRIBUTE = 'ADD_FAVORITE';
private FavoriteRepository $favoriteRepository;
private CacheDecider $cacheDecider;
public function __construct(FavoriteRepository $favoriteRepository, CacheDecider $cacheDecider)
{
$this->favoriteRepository = $favoriteRepository;
$this->cacheDecider = $cacheDecider;
}
/**
* @return array<int, string>
*/
protected function getSupportedAttributes(): array
{
return [self::ATTRIBUTE];
}
protected function supportsObject(?object $object = null): bool
{
return $object instanceof Tag;
}
protected function isGrantedForUser(object $object, User $user): bool
{
if (!$object instanceof Tag) {
throw new UnexpectedTypeException($object, Tag::class);
}
return null === $this->favoriteRepository->filterOneResult([
'user' => $user->getId(),
'tag' => $object->getId(),
], $this->cacheDecider);
}
}