<?php
namespace App\Security;
use App\Entity\Reservation;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ReservationVoter extends Voter
{
private $security;
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof Reservation) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a Reservation object, thanks to `supports()`
/** @var Reservation $reservation */
$reservation = $subject;
if ($this->security->isGranted(User::ROLE_ADMIN) || $this->security->isGranted(User::ROLE_MANAGER)) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($reservation, $user);
case self::EDIT:
return $this->canEdit($reservation, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Reservation $reservation, User $user)
{
// if they can edit, they can view
if ($this->canEdit($reservation, $user)) {
return true;
}
}
private function canEdit(Reservation $reservation, User $user)
{
// this assumes that the Reservation object has a `getOwner()` method
return $user->getId() === $reservation->getUserId();
}
}