<?php
namespace AppBundle\Security\Authorization\Voter;
use AppBundle\Entity\Participant;
use AppBundle\Entity\Plan;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class PlanVoter extends Voter
{
const VIEW = 'VIEW';
/**
* @inheritdoc
*/
protected function supports($attribute, $subject): bool
{
if ($subject instanceof Plan) {
return in_array($attribute, array(self::VIEW), true);
}
return false;
}
/**
* @inheritdoc
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
// make sure there is a user object (i.e. that the user is logged in)
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
$employer = $subject->getEmployer();
switch($attribute) {
case self::VIEW:
// Participants and employers can view a plan that belongs to the employer. Supervisors can view all plans.
return $user === $employer || ($user instanceof Participant && $user->getEmployer() === $employer) || in_array('ROLE_SUPERVISOR', $user->getRoles(), true);
}
return false;
}
}