<?php
namespace App\Security;
use App\Entity\Promotion;
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 PromotionVoter extends Voter
{
const EDIT = 'edit';
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
if (!$subject instanceof Promotion) {
return false;
}
return $attribute == self::EDIT;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof User) {
return false;
}
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
if ($attribute == self::EDIT) {
return $this->canEdit($subject, $user);
}
throw new \LogicException('Unhandled attribute. Please check supports() method.');
}
private function canEdit(Promotion $subject, User $user): bool
{
if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_PILOT')) {
return true;
}
if ($this->security->isGranted('ROLE_SPEAKER') || $this->security->isGranted('ROLE_SUPPORT')) {
return $subject->getStructure()->getId() === $user->getContact()->getStructure()->getId();
}
return false;
}
}