<?php
declare(strict_types=1);
namespace App\Platform\Security;
use App\Bundles\SavedSearchBundle\Entity\SavedSearch;
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 SavedSearchVoter extends Voter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const DELETE = 'delete';
/**
* @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::EDIT, self::DELETE])) {
return false;
}
// only vote on `SavedSearch` objects
if (!$subject instanceof SavedSearch) {
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 SavedSearch $savedSearch */
$savedSearch = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($savedSearch, $user);
case self::EDIT:
return $this->canEdit($savedSearch, $user);
case self::DELETE:
return $this->canDelete($savedSearch, $user);
}
throw new LogicException('This code should not be reached!');
}
private function canView(SavedSearch $savedSearch, User $user): bool
{
return $this->canEdit($savedSearch, $user);
}
private function canEdit(SavedSearch $savedSearch, User $user): bool
{
return $user === $savedSearch->getUser();
}
private function canDelete(SavedSearch $savedSearch, User $user): bool
{
return $user === $savedSearch->getUser();
}
}