<?php
/**
* Created by PhpStorm.
* User: sebastien.nexon
* Date: 26/01/2018
* Time: 11:30
*/
namespace App\Security;
use App\Entity\Admin;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class AdminVoter extends Voter
{
const VIEW = 'admin_show';
const EDIT = 'admin_edit';
const ADMIN_VIEW = 'ADMIN_VIEW';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $subject)
{
if(!in_array($attribute, array(self::VIEW,self::EDIT))) {
return false;
}
if(!$subject instanceof Admin) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if ($this->decisionManager->decide($token, array('ROLE_SUPER_ADMIN'))) {
return true;
}
/** @var Admin $admin */
$admin = $subject;
if ($user->hasRole(Admin::ROLE_CUSTOMER)) {
return false;
}
switch ($attribute) {
case self::VIEW:
return $this->canView($user, $admin);
case self::EDIT:
return $this->canEdit($user, $admin);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Admin $user, Admin $admin)
{
if($this->canEdit($user, $admin)) {
return true;
}
return false;
}
private function canEdit( Admin $user, Admin $target)
{
if ($target === $user || $target->getAuthorizedAdmins()->contains($user)) {
return true;
}
return false;
}
}