<?php
/**
* Created by PhpStorm.
* User: sebastien.nexon
* Date: 26/01/2018
* Time: 11:30
*/
namespace App\Security;
use App\Entity\Admin;
use App\Entity\Planning;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class PlanningVoter extends Voter
{
const VIEW = 'planning_index';
private $decisionManager;
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $decisionManager;
}
protected function supports($attribute, $subject)
{
if(!in_array($attribute, array(self::VIEW))) {
return false;
}
if(!$subject instanceof Planning) {
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;
}
$planning = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($planning, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canView( Planning $planning, Admin $admin)
{
$customer = $planning->getJob()->getContract()->getCustomer();
$authorizedUsers = array_merge($customer->getAdmins()->toArray(), $customer->getViewers()->toArray());
foreach ($authorizedUsers as $authorizedUser) {
if($admin === $authorizedUser) {
return true;
}
}
return false;
}
}