<?php
namespace App\Voter;
use App\Entity\User;
use App\RegisterBundle\Entity\Registration;
use App\RegisterBundle\Model\RegistrationFactory;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class RegistrationVoter extends Voter
{
public const EDIT = 'edit';
private $factory;
public function __construct(RegistrationFactory $factory)
{
$this->factory = $factory;
}
/**
* 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::EDIT ])) {
return false;
}
// only vote on Message objects inside this voter
if (! $subject instanceof Registration) {
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;
}
$registration = $this->factory->createModel($subject);
switch ($attribute) {
case self::EDIT:
return $registration->canBeEdited();
}
throw new LogicException('This code should not be reached!');
}
}