<?php
declare(strict_types=1);
namespace App\Platform\Security;
use App\Bundles\FavoritesBundle\Entity\Favourite;
use App\Bundles\UserBundle\Entity\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class FavouritesVoter extends Voter
{
public const VIEW = 'view';
public const CREATE = 'create';
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::CREATE])) {
return false;
}
// only vote on `SavedSearch` objects
if (!$subject instanceof Favourite) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a SavedSearch object, thanks to `supports()`
/** @var Favourite $favorites */
$favorites = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($favorites, $user);
case self::CREATE:
return $this->canCreate($favorites, $user);
}
throw new LogicException('This code should not be reached!');
}
private function canView(Favourite $favorites, User $user): bool
{
return $this->canCreate($favorites, $user);
}
private function canCreate(Favourite $favorites, User $user): bool
{
// TODO: Add check user
return true;
}
}