<?php
namespace App\Security\Voter;
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 everyone
if (in_array('ROLE_ADMIN', $currentUser->getRoles(), true)) {
return true;
}
if (in_array('ROLE_COMMERCIAL', $currentUser->getRoles(), true)) {
return true;
}
// 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 only view orders they created themselves
if (in_array('ROLE_B2B_AGENT', $currentUser->getRoles(), true)) {
return $order->getUser() === $currentUser;
}
return false;
}
}