<?php
namespace App\Voter;
use App\Entity\User;
use App\Model\Message;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class MessageVoter extends Voter
{
public const DISCARD = 'discard';
public const ACTION = 'action';
/**
* Determines if the attribute and subject are supported by this voter.
*
* @param string $attribute An attribute
* @param mixed $subject The subject to secure, e.g. an object the user wants to access or any other PHP type
*
* @return bool True if the attribute and subject are supported, false otherwise
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::DISCARD, self::ACTION])) {
return false;
}
// only vote on Message objects inside this voter
if (!$subject instanceof \App\Entity\Message) {
return false;
}
return true;
}
/**
* Perform a single access check operation on a given attribute, subject and token.
* It is safe to assume that $attribute and $subject already passed the "supports()" method check.
*
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/**
* User
*/
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
$message = new Message();
$message->setEntity($subject);
switch ($attribute) {
case self::DISCARD:
return $message->canBeDiscardedBy($user);
case self::ACTION:
return $message->canBeActionedBy($user);
}
throw new LogicException('This code should not be reached!');
}
}