src/Security/Voter/Customer/WorkContractVoter.php line 14
<?php
namespace App\Security\Voter\Customer;
use App\Entity\Customer\WorkContract;
use App\Dto\Customer\ContractDto;
use App\Entity\Admin\CustomerUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\SecurityBundle\Security;
class WorkContractVoter extends Voter
{
final public const EDIT = 'CONTRACT_ENTITY_EDIT';
final public const VIEW = 'CONTRACT_ENTITY_VIEW';
final public const DELETE = 'CONTRACT_ENTITY_DELETE';
public function __construct(
private readonly Security $security)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
if(!in_array($attribute, [self::EDIT, self::VIEW, self::DELETE])){
return false;
}
if (!$subject instanceof WorkContract and !$subject instanceof ContractDto) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
if (!$this->security->isGranted('ROLE_STAFF')){
return false;
}
// ... (check conditions and return true to grant permission) ...
return match($attribute) {
self::VIEW => $this->canView((array) $subject, $user),
self::EDIT => $this->canEdit(),
self::DELETE => $this->canDelete($subject, $user),
default => throw new \LogicException('This code should not be reached!')
};
}
private function canView($entity, CustomerUser $user): bool
{
if ($entity['staff'] == $user->getStaff()) {
return true;
}
return false;
}
private function canEdit(): bool
{
return $this->security->isGranted('ROLE_ADMIN');
}
}