<?php
namespace App\Security;
use App\Entity\Action;
use App\Entity\ActionAnswers;
use App\Entity\Beneficiary;
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 BeneficiaryVoter 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 Beneficiary and !$subject instanceof Action and !$subject instanceof ActionAnswers) {
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') || $this->security->isGranted('ROLE_ADMIN')) {
return true;
}
if ($attribute == self::EDIT) {
return $this->canEdit($subject, $user);
}
throw new \LogicException('Unhandled attribute. Please check supports() method.');
}
private function canEdit(Beneficiary $subject, User $user): bool
{
//dd($this->security->isGranted('ROLE_ADMIN'));
if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_PILOT') || $subject->getUser()->getId() === $user->getId()) {
return true;
}
if ($this->security->isGranted('ROLE_SPEAKER') || $this->security->isGranted('ROLE_SUPPORT')) {
return (!$subject->getPromotion() && $subject->getCreatedBy()?->getId() == $user->getId()) || $subject->getPromotion()?->getStructure()->getId() === $user->getContact()?->getStructure()->getId();
}
return false;
}
}