<?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';
/**
* @var AccessDecisionManagerInterface
*/
private $decisionManager;
/**
* CartVoter constructor.
*
* @param AccessDecisionManagerInterface $decisionManager
*/
public function __construct(AccessDecisionManagerInterface $decisionManager)
{
$this->decisionManager = $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, array(
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
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $individualOrder, TokenInterface $token)
{
if ($this->decisionManager->decide($token, array('ROLE_SUPER_ADMIN'))) {
return true;
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
switch ($attribute) {
case self::CREATE:
return $this->canCreate($user);
case self::VIEW:
return $this->canView($individualOrder, $user);
case self::EDIT:
return $this->canEdit($individualOrder, $user);
case self::DELETE:
return $this->canDelete($individualOrder, $user);
}
throw new \LogicException('This code should not be reached!');
}
/**
* @param User $user
*
* @return bool
*/
private function canCreate(User $user)
{
if ($user->hasRole('ROLE_GUEST')) {
return false;
}
return true;
}
/**
* @param Cart $cart
* @param User $user
*
* @return bool
*/
private function canView(Cart $cart, User $user)
{
if ($this->canEdit($cart, $user)) {
return true;
}
return false;
}
/**
* @param Cart $cart
* @param UserInterface $user
*
* @return bool
*/
private function canEdit(Cart $cart, UserInterface $user)
{
if (!$cart->isCheckedOut()) {
return $user === $cart->getUser();
}
return false;
}
/**
* @param Cart $cart
* @param UserInterface $user
*
* @return bool
*/
private function canDelete($cart, $user)
{
return false;
}
}