<?php
namespace App\Security\Voter;
use App\Entity\SupportTicket;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class SupportTicketVoter extends Voter
{
const REPLY = 'reply';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [self::REPLY])) {
return false;
}
if (!$subject instanceof SupportTicket) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var SupportTicket $ticket */
$ticket = $subject;
if ($this->security->isGranted(User::ROLE_SUPER_ADMIN)) {
return true;
}
switch ($attribute) {
case self::REPLY:
return $this->canReply($ticket, $user, $token);
}
throw new \LogicException('This code should not be reached!');
}
private function canReply(SupportTicket $ticket, User $user, TokenInterface $token)
{
return in_array($ticket->getStatus(), SupportTicket::STATUS_USER_CAN_REPLY);
}
}