<?php
namespace App\Security;
use App\Entity\Collaborator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\Translation\TranslatorInterface;
class CollaboratorVoter extends Voter
{
const VIEW = 'view';
const EDIT_PROFIL_LIGHT = 'edit_profil_light';
const EDIT_INTERVIEW = 'edit_interview';
const NEW = 'new';
private $security;
private $translator;
public function __construct(Security $security,TranslatorInterface $translator)
{
$this->security = $security;
$this->translator=$translator;
}
protected function supports(string $attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT_PROFIL_LIGHT,self::EDIT_INTERVIEW,self::NEW])) {
return false;
}
// only vote on `Collaborator` objects
if (!$subject instanceof Collaborator) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$collaborator_connected = $token->getUser()->getCollaborator();
if (!$collaborator_connected instanceof Collaborator) {
return false;
}
// you know $subject is a Collaborator object, thanks to `supports()`
/** @var Collaborator $collaborator */
$collaborator = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($collaborator,$collaborator_connected);
case self::NEW:
return $this->canNew($collaborator,$collaborator_connected);
case self::EDIT_PROFIL_LIGHT:
return $this->canEditProfileLight($collaborator,$collaborator_connected);
case self::EDIT_INTERVIEW:
return $this->canEditInterview($collaborator,$collaborator_connected);
}
throw new \LogicException('This code should not be reached!');
}
private function canNew(Collaborator $collaborator,Collaborator $collaborator_connected): bool
{
return $this->isGranted('ROLE_ASSISTANT_RH');
}
private function canView(Collaborator $collaborator,Collaborator $collaborator_connected): bool
{
if(
!$this->isGranted('ROLE_ASSISTANT_RH')
and $collaborator_connected!=$collaborator
and !in_array($collaborator,$collaborator_connected->getAllListNMoins()->toArray())
){
return false;
}
return true;
}
private function canEditProfileLight(Collaborator $collaborator,Collaborator $collaborator_connected)
{
return $this->isGranted('ROLE_ASSISTANT_RH') or $collaborator->getId()==$collaborator_connected->getId();
}
private function canEditInterview(Collaborator $collaborator,Collaborator $collaborator_connected)
{
return $this->isGranted('ROLE_ASSISTANT_RH') or in_array($collaborator,$collaborator_connected->getAllListNMoins()->toArray());
}
private function isGranted($role)
{
return $this->security->isGranted($role);
}
}