<?php
namespace App\Voters;
use App\Model\Contact\Contact;
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 ContactVoter.
*/
final class ContactVoter extends Voter
{
/**
* @param string $attribute
* @param Contact $subject
*
* @return bool
*/
protected function supports($attribute, $subject)
{
if (!in_array($attribute, [SecurityConfig::CONTACT_SHOW,
SecurityConfig::CONTACT_CUD,
SecurityConfig::MY_CONTACT_BY_DEFAULT, ], true)) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param Contact $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::CONTACT_SHOW:
return $this->canViewContact($user);
case SecurityConfig::CONTACT_CUD:
return $this->canCudContact($user);
case SecurityConfig::MY_CONTACT_BY_DEFAULT:
return $this->hasHisContactByDefault($user);
}
throw new LogicException('This code should not be reached!');
}
/**
* @param User $user
*
* @return bool
*/
private function canViewContact(User $user)
{
if ($user->isAdmin()) {
return true;
}
return in_array(SecurityConfig::CONTACT_SHOW, $user->getRoles(), true);
}
/**
* @param User $user
*
* @return bool
*/
private function canCudContact(User $user)
{
if ($user->isAdmin()) {
return true;
}
return in_array(SecurityConfig::CONTACT_CUD, $user->getRoles(), true);
}
/**
* @param User $user
*
* @return bool
*/
private function hasHisContactByDefault(User $user)
{
return in_array(SecurityConfig::MY_CONTACT_BY_DEFAULT, $user->getRoles(), true);
}
}