<?php
namespace App\Security\Voter;
use App\Entity\Building\Building;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class BuildingVoter extends Voter
{
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
/**
* @var Security
*/
private Security $security;
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
public function __construct(Security $security, EntityManagerInterface $entityManager)
{
$this->security = $security;
$this->entityManager = $entityManager;
}
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, self::DELETE], true)) {
return false;
}
// only vote on `Building` objects
if (!$subject instanceof Building) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a Post object, thanks to `supports()`
/** @var Building $targetBuilding */
$targetBuilding = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canSee($targetBuilding, $loggedUser);
case self::EDIT:
case self::DELETE:
return $this->canDealWith($targetBuilding, $loggedUser);
}
throw new \LogicException('This code should not be reached!');
}
/**
* @param Building $targetBuilding
* @param User $loggedUser
* @return bool
*/
private function canDealWith(Building $targetBuilding, User $loggedUser): bool
{
if ($this->canSee($targetBuilding, $loggedUser) && $this->security->isGranted('ROLE_CAN_EDIT_BUILDING')) {
return true;
}
return false;
}
/**
* @param Building $targetBuilding
* @param User $loggedUser
* @return bool
*/
private function canSee(Building $targetBuilding, User $loggedUser): bool
{
// sanity check (different client than logged user client)
if ($targetBuilding->getClient()->getId() !== $loggedUser->getClient()->getId()) {
return false;
}
// after sanity check - this building is from logged user client
if ($this->security->isGranted('ROLE_CAN_SEE_ALL_BUILDINGS')) {
return true;
}
foreach ($loggedUser->getBuildings() as $building) {
if ($building->getId() === $targetBuilding->getId()) {
return true;
}
}
return false;
}
}