<?php
/**
* Created by PhpStorm.
* User: sebastien.nexon
* Date: 26/01/2018
* Time: 11:30
*/
namespace App\Security;
use App\Entity\Admin;
use App\Entity\Customer;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class CustomerVoter extends Voter
{
const VIEW = 'customer_show';
const EDIT = 'customer_edit';
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 Customer) {
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;
}
$customer = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($customer, $user);
case self::EDIT:
return $this->canEdit($customer, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView(Customer $customer, Admin $admin)
{
if($this->canEdit($customer, $admin)) {
return true;
}
return false;
}
private function canEdit( Customer $customer, Admin $admin)
{
$admins = $customer->getAdmins();
foreach ($admins as $adminAct) {
if ($admin === $adminAct) {
return true;
}
}
return false;
}
}