<?php
// src/Security/HotelVoter.php
namespace App\Security;
use App\Entity\Hotel;
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 HotelVoter extends Voter
{
const VIEW = 'view';
const EDIT = 'edit';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
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;
}
// only vote on `Hotel` objects
if (!$subject instanceof Hotel) {
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 Hotel object, thanks to `supports()`
/** @var Hotel $hotel */
$hotel = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($hotel, $user);
case self::EDIT:
return $this->canEdit();
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Hotel $hotel, User $user): bool
{
$hotel_users = $hotel->getHotelUsers();
foreach($hotel_users as $hu){
if($hu->getUser() == $user){
return true;
}
}
// the Hotel object could have, for example, a method `isPrivate()`
return false;
}
private function canEdit(): bool
{
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
return false;
}
}