<?php
namespace App\Security\Voter;
use App\Entity\Company;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class CompanyVoter extends Voter
{
public const USER_EDIT = 'USER_EDIT';
public const USER_DELETE = 'USER_DELETE';
public const COMPANY_SHOW = 'COMPANY_SHOW';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::USER_DELETE, self::USER_EDIT,self::COMPANY_SHOW])
&& ( $subject instanceof User || $subject instanceof Company);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
//utilisateur connecté
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::USER_EDIT:
return $this->canUserEdit($subject, $user);
case self::USER_DELETE:
return $this->canUserDelete($subject, $user);
case self::COMPANY_SHOW:
return $this->canCompanyShow( $subject, $user);
}
return false;
}
private function canUserEdit(User $userTarget, UserInterface $user): bool
{
if($this->security->isGranted('ROLE_ADMIN')){
return true;
}
if($this->security->isGranted('ROLE_RH')){
if($userTarget->getCompany() === $user->getCompany()){
return true;
}
}
return false;
}
private function canUserDelete(User $userTarget, UserInterface $user): bool
{
if($this->security->isGranted('ROLE_ADMIN')){
return true;
}
if($this->security->isGranted('ROLE_RH')){
if($userTarget->getCompany() === $user->getCompany()){
return true;
}
}
return false;
}
private function canCompanyShow(Company $company, UserInterface $user): bool
{
if($this->security->isGranted('ROLE_ADMIN')){
return true;
}
if($this->security->isGranted('ROLE_RH')){
if($company === $user->getCompany()){
return true;
}
}
return false;
}
}