<?php
namespace App\Voters;
use App\Model\Prospect\Prospect;
use App\Security\SecurityConfig;
use App\Security\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Class ProspectVoter.
*/
final class ProspectVoter extends Voter
{
/**
* @param string $attribute
* @param Prospect $subject
*
* @return bool
*/
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [SecurityConfig::PROSPECT_SHOW,
SecurityConfig::PROSPECT_CUD,
SecurityConfig::MY_PROSPECT_BY_DEFAULT, ], true)) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param Prospect $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
switch ($attribute) {
case SecurityConfig::PROSPECT_SHOW:
return $this->canViewProspect($user);
case SecurityConfig::PROSPECT_CUD:
return $this->canCudProspect($user);
case SecurityConfig::MY_PROSPECT_BY_DEFAULT:
return $this->hasHisProspectByDefault($user);
}
throw new LogicException('This code should not be reached!');
}
/**
* @param User $user
*
* @return bool
*/
private function canViewProspect(User $user)
{
if ($user->isAdmin()) {
return true;
}
return in_array(SecurityConfig::PROSPECT_SHOW, $user->getRoles(), true);
}
/**
* @param User $user
*
* @return bool
*/
private function canCudProspect(User $user)
{
if ($user->isAdmin()) {
return true;
}
return in_array(SecurityConfig::PROSPECT_CUD, $user->getRoles(), true);
}
/**
* @param User $user
*
* @return bool
*/
private function hasHisProspectByDefault(User $user)
{
return in_array(SecurityConfig::MY_PROSPECT_BY_DEFAULT, $user->getRoles(), true);
}
}