<?php
namespace App\Security;
use App\Entity\Item;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ItemVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT])) {
return false;
}
if (!$subject instanceof Item) {
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;
}
/** @var Item $item */
$item = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($item, $user);
case self::EDIT:
return $this->canEdit($item, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Item $item, User $user): bool
{
return $item->getUser() === $user;
}
private function canEdit(Item $item, User $user): bool
{
return null === $item->getId() || $this->canView($item, $user);
}
}