<?php
namespace App\Security\Voter;
use App\Entity\Study;
use App\Entity\Survey;
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 EcohortVoter extends Voter
{
const ECOHORT_MANAGE = 'ECOHORT_MANAGE';
/**
* @var Security
*/
private $security;
/**
* UserVoter constructor.
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
return in_array($attribute, [self::ECOHORT_MANAGE])
&& ($subject instanceof Study || $subject instanceof Survey);
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
/** @var User $user */
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof User) {
return false;
}
// if the user is anonymous, do not grant access
if (!in_array('ROLE_ADMIN', $user->getRoles()) || !in_array('ROLE_ECITY', $user->getRoles())) {
return false;
}
// get user permissions
$permissions = $user->getPermissions();
if( !is_array($permissions) ) {
return false;
}
switch ($attribute) {
case self::ECOHORT_MANAGE:
if (in_array('ECOHORT_MANAGE', $permissions)) {
return true;
}
break;
}
return false;
}
}