<?php
namespace App\Security;
use App\Entity\System\Employee;
use App\Entity\System\Order;
use App\Entity\System\PaymentMethod;
use App\Entity\System\Role;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class OrderVoter extends Voter
{
public const SHOW = 'show';
public const PUBLISH = 'publish';
public const CHECK_PAYPAL = 'publish';
private AuthorizationCheckerInterface $authorizationChecker;
public function __construct(AuthorizationCheckerInterface $authorizationChecker)
{
$this->authorizationChecker = $authorizationChecker;
}
/**
* @param Order $subject
*/
protected function supports(string $attribute, $subject): bool
{
if (!(get_class($subject) === Order::class)) {
return false;
}
return $this->supportsAttribute($attribute);
}
public function supportsAttribute(string $attribute): bool
{
$voter = new \ReflectionClass(__CLASS__);
$allowedValues = $voter->getConstants();
if (!\array_key_exists($attribute, \array_flip($allowedValues))) {
return false;
}
return true;
}
/**
* @param Order $order
*/
protected function voteOnAttribute(string $attribute, $order, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof Employee) {
return false;
}
switch ($attribute) {
case self::SHOW:
return $this->showAllowed($order, $user);
case self::PUBLISH:
return $this->publishAllowed($order);
case self::CHECK_PAYPAL:
return $this->checkPayPal($order);
default:
throw new \LogicException('This code should not be reached!');
}
}
private function showAllowed(Order $order, Employee $user): bool
{
if ($this->authorizationChecker->isGranted(Role::ROLE_DEV)) {
return true;
}
return false;
}
private function publishAllowed(Order $order): bool
{
if (!$this->authorizationChecker->isGranted(Role::ROLE_DEV)) {
return false;
}
return $order->getA4bUuid() === null;
}
private function checkPayPal(Order $order): bool
{
if (
!$this->authorizationChecker->isGranted(Role::ROLE_DEV)
|| $order->getPaypalPayerEmail() !== null || $order->getTransactionId() === null
) {
return false;
}
return $order->getPayment() === PaymentMethod::PAYMENT_METHOD_PAYPAL;
}
}