<?php
namespace App\Security\Voter;
use App\Entity\CustomService;
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 OrderVoter extends Voter
{
public const VIEW = 'ORDER_VIEW';
public const EDIT = 'ORDER_EDIT';
/**
* @inheritDoc
*/
protected function supports(string $attribute, mixed $subject): bool
{
// Only vote on User objects and supported attributes
return in_array($attribute, [self::VIEW, self::EDIT])
&& $subject instanceof Order;
}
/**
* @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 $order */
$order = $subject;
return match ($attribute) {
self::VIEW => $this->canView($order, $currentUser),
default => false,
};
}
private function canView(Order $order, 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($order, $currentUser);
}
if (in_array('ROLE_COMMERCIAL', $currentUser->getRoles(), true)) {
return $this->agentIsAuthorized($order, $currentUser);
}
// B2B Admins: can view orders of their own customer
if (in_array('ROLE_B2B_ADMIN', $currentUser->getRoles(), true)) {
return $order->getCustomer() === $currentUser->getCustomer();
}
// B2B Agents can view their own orders. Custom services are created by
// the back office, so an agent may also view a custom-service order for
// the customer to which they are attached.
if (in_array('ROLE_B2B_AGENT', $currentUser->getRoles(), true)) {
return $order->getUser() === $currentUser
|| ($order->getCustomer() === $currentUser->getCustomer()
&& $this->containsCustomService($order));
}
if (in_array('ROLE_B2C', $currentUser->getRoles(), true)) {
return $order->getCustomer() === $currentUser->getCustomer();
}
return false;
}
private function containsCustomService(Order $order): bool
{
foreach ($order->getOrderLines() as $orderLine) {
if ($orderLine->getProduct() instanceof CustomService) {
return true;
}
}
return false;
}
private function agentIsAuthorized(Order $order, UserInterface $currentUser)
{
$personal = $currentUser->getPersonal();
if (!$personal) {
return false;
}
return $personal->getAuthAgencies()->contains($order->getAgency());
}
}