<?php
declare(strict_types=1);
namespace App\Security;
use App\Entity\Contact;
use App\Entity\SalesRep;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ContactVoter extends Voter
{
const EDIT = 'edit';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, mixed $subject): bool
{
if (!in_array($attribute, [self::EDIT])) {
return false;
}
if (!$subject instanceof Contact) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof SalesRep) {
return false;
}
return match($attribute) {
self::EDIT => $this->canEdit($subject, $user),
default => throw new \LogicException('This code should not be reached!')
};
}
private function canEdit(Contact $contact, SalesRep $user): bool
{
$ownerId = null !== $contact->getSalesRep()
? $contact->getSalesRep()->getId()
: null
;
if (
false === $this->security->isGranted('ROLE_ADMIN')
&& false === $this->security->isGranted('ROLE_UPDATER')
&& false === $this->security->isGranted('ROLE_INSIDE_USER')
&& false === $this->security->isGranted('ROLE_EX_UPDATE')
&& $ownerId !== $user->getId()
) {
return false;
}
return true;
}
}