<?php
namespace App\Voter;
use App\Entity\Order;
use App\Model\OrderFactory;
use App\Model\User\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class OrderVoter extends Voter
{
public const VIEW = 'view';
public const BO_VIEW = 'bo_view';
public const EDIT = 'edit';
public const CANCEL = 'cancel';
public const BUY = 'buy';
private $orderFactory;
private $user;
public function __construct(OrderFactory $orderFactory, User $user)
{
$this->orderFactory = $orderFactory;
$this->user = $user;
}
protected function supports($attribute, $orderEntity): bool
{
// if the attribute isn't one we support, return false
if (! in_array($attribute, [
self::VIEW,
self::BO_VIEW,
self::EDIT,
self::CANCEL,
self::BUY,
])
) {
return false;
}
if (! $orderEntity instanceof Order) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $orderEntity, TokenInterface $token): bool
{
$roles = [];
$userEntity = $token->getUser();
if ($userEntity != 'anon.') {
$this->user->setEntity($userEntity);
$roles = $userEntity->getRoles();
}
$order = $this->orderFactory->createModel();
$order->setEntity($orderEntity);
if (in_array('ROLE_ADMIN', $roles)) {
return true;
}
switch ($attribute) {
case self::VIEW:
return $order->canBeViewedBy($this->user);
case self::EDIT:
return $order->canBeEditedBy($this->user);
case self::BO_VIEW:
return $order->canBeBoViewedBy($this->user);
case self::CANCEL:
return $order->canBeCancelledBy($this->user);
}
throw new LogicException('This code should not be reached!');
}
}