<?php
namespace App\Security;
use App\Entity\Contact;
use App\Entity\Questionnaire;
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 ContactVoter 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 Contact and !$subject instanceof Questionnaire) {
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($subject, $user): bool
{
if ($this->security->isGranted('ROLE_ADMIN')
|| $this->security->isGranted('ROLE_PILOT')) {
return true;
}
if ($subject->getUser() == $user) {
return true;
}
return false;
}
}