<?php
declare(strict_types=1);
namespace App\Platform\Security;
use App\Bundles\FavoritesBundle\Entity\FavoritesList;
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 FavoritesListVoter extends Voter
{
public const VIEW = 'view';
public const CREATE = 'create';
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports(string $attribute, mixed $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 FavoritesList) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, mixed $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 FavoritesList $favoritesList */
$favoritesList = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($favoritesList, $user);
case self::CREATE:
return $this->canCreate($favoritesList, $user);
}
throw new LogicException('This code should not be reached!');
}
private function canView(FavoritesList $favoritesList, User $user): bool
{
return $this->canCreate($favoritesList, $user);
}
private function canCreate(FavoritesList $favoritesList, User $user): bool
{
// TODO: Add check user
return true;
}
}