<?php
namespace App\Security\ECommerce;
use App\Entity\ECommerce\IndividualOrder;
use App\Entity\App\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Class IndividualOrderVoter
*
* @package MDL\ECommerceBundle\Security
*/
class IndividualOrderVoter extends Voter
{
// these strings are just invented: you can use anything
const CREATE = 'INDIVIDUAL_ORDER_CREATE';
const VIEW = 'INDIVIDUAL_ORDER_VIEW';
const EDIT = 'INDIVIDUAL_ORDER_EDIT';
const DELETE = 'INDIVIDUAL_ORDER_DELETE';
/**
* IndividualOrderVoter constructor.
*/
public function __construct(private readonly AccessDecisionManagerInterface $decisionManager)
{
}
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [
self::CREATE,
self::VIEW,
self::EDIT,
self::DELETE,
])) {
return false;
}
// only vote on IndividualOrder objects inside this voter
if (!$subject instanceof IndividualOrder && $attribute !== self::CREATE) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param IndividualOrder $individualOrder
*
* @return bool
*/
protected function voteOnAttribute($attribute, $individualOrder, TokenInterface $token)
{
if ($this->decisionManager->decide($token, ['ROLE_SUPER_ADMIN'])) {
return true;
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
return match ($attribute) {
self::CREATE => $this->canCreate($user),
self::VIEW => $this->canView($user),
self::EDIT => $this->canEdit(),
self::DELETE => $this->canDelete(),
default => throw new \LogicException('This code should not be reached!'),
};
}
/**
* @param IndividualOrder $individualOrder
* @param UserInterface $user
*
* @return bool
*/
private function canCreate(?User $user=null): bool
{
return $user && $user->hasRole('ROLE_GUEST');
}
/**
*
* @return bool
*/
private function canView(User $user)
{
if ($user->hasRole('ROLE_GUEST')) {
return true;
}
return $this->canEdit();
}
private function canEdit(): bool
{
return false;
}
private function canDelete(): bool
{
return false;
}
}