<?php
// src/Security/PostVoter.php
namespace App\Security;
use App\Entity\Nea;
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 DashboardVoter extends Voter
{
// these strings are just invented: you can use anything
public const CAN_VIEW_ELEVATOR = 'canViewElevator';
public const CAN_VIEW_NEA = 'canViewNea';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::CAN_VIEW_ELEVATOR, self::CAN_VIEW_NEA])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof Nea) {
return false;
}
return true;
}
protected function voteOnAttribute($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 Post object, thanks to `supports()`
/** @var Post $post */
$nea = $subject;
switch ($attribute) {
case self::CAN_VIEW_ELEVATOR:
return $this->canViewElevator($user);
case self::CAN_VIEW_NEA:
return $this->canViewNea($user);
}
throw new \LogicException('This code should not be reached!');
}
private function canViewElevator(User $user): bool
{
if (
in_array('ROLE_ELV', $user->getRoles())
&& (
$this->security->isGranted('ROLE_OPERATOR')
|| $this->security->isGranted('ROLE_CUSTODIAN')
|| $this->security->isGranted('ROLE_DL')
|| $this->security->isGranted('ROLE_SBS')
|| $this->security->isGranted('ROLE_LIFTMANAGER')
)
) {
return true;
}
return false;
}
private function canViewNea(User $user): bool
{
if (
in_array('ROLE_NEA', $user->getRoles())
&& (
$this->security->isGranted('ROLE_OPERATOR')
|| $this->security->isGranted('ROLE_CUSTODIAN')
|| $this->security->isGranted('ROLE_DL')
|| $this->security->isGranted('ROLE_SBS')
|| $this->security->isGranted('ROLE_LIFTMANAGER')
)
) {
return true;
}
return false;
}
}