<?php
namespace App\Security\Voter;
use App\Entity\EnterpriseContactPosition;
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\User\UserInterface;
class RequestItemVoter extends Voter
{
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
protected function supports($attribute, $subject)
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, ['create', 'update','delete','view'])
&& $subject instanceof \App\Entity\RequestItem;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
$enterprises = $this->em->getRepository(EnterpriseContactPosition::class)->getEnterprises($user->getContact());
if ($user->getRoles()[0] == "ROLE_ADMIN") { return true;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'create':
if(in_array($subject->getRemovalRequest()->getCustomer(), $enterprises)) { return true;
}
break;
case 'update':
if(in_array($subject->getRemovalRequest()->getCustomer(), $enterprises)|| in_array($subject->getSupplier(), $enterprises) ) { return true;
}
break;
case 'delete':
return false;
break;
case 'view':
if(in_array($subject->getRemovalRequest()->getCustomer(), $enterprises)|| in_array($subject->getSupplier(), $enterprises) ) { return true;
}
break;
}
return false;
}
}