<?php
namespace App\Security\Voter;
use App\Entity\Customer;
use App\Entity\CustomerMoral;
use App\Entity\CustomerPhysical;
use App\Entity\Order;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class CustomerVoter extends Voter
{
public const VIEW = 'CUSTOMER_VIEW';
/**
* @inheritDoc
*/
protected function supports(string $attribute, mixed $subject): bool
{
// Only vote on User objects and supported attributes
return in_array($attribute, [self::VIEW])
&& ($subject instanceof CustomerMoral or $subject instanceof CustomerPhysical);
}
/**
* @inheritDoc
*/
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$currentUser = $token->getUser();
if (!$currentUser instanceof UserInterface) {
return false; // not logged in
}
/** @var Order $Customer */
$customer = $subject;
return match ($attribute) {
self::VIEW => $this->canView($customer, $currentUser),
default => false,
};
}
private function canView(Customer $customer, UserInterface $currentUser): bool
{
// Admins can view every thing
if (in_array('ROLE_SUPER_ADMIN', $currentUser->getRoles(), true)) {
return true;
}
// Admins can view authorized orders
if (in_array('ROLE_ADMIN', $currentUser->getRoles(), true)) {
return $this->agentIsAuthorized($customer, $currentUser);
}
if (in_array('ROLE_COMMERCIAL', $currentUser->getRoles(), true)) {
return $this->agentIsAuthorized($customer, $currentUser);
}
if (in_array('ROLE_BRANCH', $currentUser->getRoles(), true)) {
return $this->agentIsAuthorized($customer, $currentUser);
}
return false;
}
private function agentIsAuthorized(Customer $customer, UserInterface $currentUser)
{
$personal = $currentUser->getPersonal();
if (!$personal) {
return false;
}
return $personal->getAuthAgencies()->contains($customer->getAgency());
}
}