<?php
namespace App\Security\Voter\Purchase;
use App\Entity\Purchase\PurchaseRequestItem;
use App\Entity\Security\User;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class PurchaseRequestItemVoter extends Voter
{
private $session;
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
protected function supports($attribute, $subject)
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
if (!in_array($attribute, [
'ROLE_PURCHASE_REQUEST_ITEM_CREATE',
'ROLE_PURCHASE_REQUEST_ITEM_EDIT',
'ROLE_PURCHASE_REQUEST_ITEM_DELETE'
])) {
return false;
}
// only vote on `Activity` objects
if (!$subject instanceof PurchaseRequestItem) {
return false;
}
return true;
}
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;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'ROLE_PURCHASE_REQUEST_ITEM_CREATE':
return $this->canCreate($subject, $user);
break;
case 'ROLE_PURCHASE_REQUEST_ITEM_EDIT':
return $this->canEdit($subject, $user);
break;
case 'ROLE_PURCHASE_REQUEST_ITEM_DELETE':
return $this->canDelete($subject, $user);
break;
}
return false;
}
private function canCreate(PurchaseRequestItem $purchaseRequestItem, User $user)
{
if (in_array('ROLE_PURCHASE_REQUEST_ITEM_CREATE', $this->session->get('privileges'))) {
return true;
}
return false;
}
private function canEdit(PurchaseRequestItem $purchaseRequestItem, User $user)
{
if (in_array('ROLE_PURCHASE_REQUEST_ITEM_EDIT', $this->session->get('privileges'))) {
return true;
}
return false;
}
private function canDelete(PurchaseRequestItem $purchaseRequestItem, User $user)
{
if (in_array('ROLE_PURCHASE_REQUEST_ITEM_DELETE', $this->session->get('privileges'))) {
return true;
}
return false;
}
}