<?php
namespace App\Security\ECommerce;
use App\Entity\ECommerce\Cart;
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 CartVoter
*
* @package MDL\ECommerceBundle\Security
*/
class CartVoter extends Voter
{
// these strings are just invented: you can use anything
const CREATE = 'CART_CREATE';
const VIEW = 'CART_VIEW';
const EDIT = 'CART_EDIT';
const DELETE = 'CART_DELETE';
/**
* CartVoter 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 Cart objects inside this voter
if (!$subject instanceof Cart && $attribute !== self::CREATE) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param Cart $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($individualOrder, $user),
self::EDIT => $this->canEdit($individualOrder, $user),
self::DELETE => $this->canDelete(),
default => throw new \LogicException('This code should not be reached!'),
};
}
private function canCreate(User $user): bool
{
return !$user->hasRole('ROLE_GUEST');
}
/**
*
* @return bool
*/
private function canView(Cart $cart, User $user)
{
return $this->canEdit($cart, $user);
}
/**
*
* @return bool
*/
private function canEdit(Cart $cart, UserInterface $user)
{
if (!$cart->isCheckedOut()) {
return $user === $cart->getUser();
}
return false;
}
private function canDelete(): bool
{
return false;
}
}