<?php
namespace App\Security\Voter;
use App\Entity\Company;
use App\Service\VoterSecurityService;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class CompanyVoter extends Voter
{
public const EDIT = 'EDIT'; // infos and employee
public const VIEW = 'VIEW';
public const VIEW_PREMIUM = 'VIEW_PREMIUM';
public const VIEW_CHILDREN = 'VIEW_CHILDREN';
public const ADD_CHILDREN = 'ADD_CHILDREN'; // add company child
public function __construct(private readonly VoterSecurityService $voterSecurityService)
{
}
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [
self::EDIT, self::VIEW,
self::VIEW_CHILDREN, self::ADD_CHILDREN, self::VIEW_PREMIUM,
])
&& $subject instanceof Company;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$this->voterSecurityService->isUserAllowed($user)) {
return false;
}
$this->voterSecurityService->isUserInElement($user, $subject);
if (!$this->voterSecurityService->isUserInElement($user, $subject)) {
return false;
}
return match ($attribute) {
self::VIEW => true,
self::VIEW_PREMIUM => $user->isPremium(),
self::EDIT => $this->voterSecurityService->allowedEditElement($subject),
self::VIEW_CHILDREN => $subject->isParent(), // check if is isParent === true in Company,
self::ADD_CHILDREN => $subject->isPremium() && $subject->isParent() &&
$this->voterSecurityService->isUserManagerCompany(),
default => false,
};
}
}