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