<?php
namespace App\Security\Voter;
use App\Entity\ContractPrice\Contract;
use App\Entity\User;
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\Security;
class ContractPriceVoter extends Voter
{
const EDIT = 'edit';
const DELETE = 'delete';
public function __construct(
protected Security $security,
protected EntityManagerInterface $entityManager
) {
}
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT, self::DELETE], true)) {
return false;
}
// only vote on `Contract` objects
if (!$subject instanceof Contract) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$loggedUser = $token->getUser();
if (!$loggedUser instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
switch ($attribute) {
case self::EDIT:
return $this->canEdit($loggedUser);
case self::DELETE:
return $this->canDelete($loggedUser);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit(User $loggedUser): bool
{
if (!$this->security->isGranted('ROLE_CAN_VIEW_CONTRACTS')) {
return false;
}
if ($this->security->isGranted('ROLE_CAN_EDIT_CONTRACT')) {
return true;
}
return false;
}
private function canDelete(User $loggedUser): bool
{
if (!$this->security->isGranted('ROLE_CAN_VIEW_CONTRACTS')) {
return false;
}
if ($this->security->isGranted('ROLE_CAN_DELETE_CONTRACT')) {
return true;
}
return false;
}
}