<?php
namespace App\Voter;
use App\Entity\Customer;
use App\Model\User\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ShopVoter extends Voter
{
public const SWITCH_SHOP = 'switchShop';
public const BO_VIEW = 'bo_view';
public const VIEW = 'view';
public const EDIT = 'edit';
public const REMOVE_MEMBER = 'remove_member';
public const NEW = 'new';
/** @var User */
private $user;
public function __construct(User $user)
{
$this->user = $user;
}
protected function supports($attribute, $shopEntity): bool
{
// if the attribute isn't one we support, return false
if (! in_array($attribute, [
self::SWITCH_SHOP,
self::BO_VIEW,
self::VIEW,
self::EDIT,
self::NEW,
self::REMOVE_MEMBER
])
) {
return false;
}
if (! $shopEntity instanceof Customer) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $shopEntity, TokenInterface $token): bool
{
$userEntity = $token->getUser();
$this->user->setEntity($userEntity);
// Prestachef staff can do all of it
if ($this->user->isPrestachefStaff()) {
return true;
}
$shop = $this->user->getService('shopFactory')->createModel();
$shop->setEntity($shopEntity);
switch ($attribute) {
case self::VIEW:
return $this->user->canSeeShop($shop);
case self::EDIT:
return $this->user->canEditShop($shop);
case self::REMOVE_MEMBER:
return $this->user->canRemoveTeamMemberFromShop($shop);
case self::NEW:
return $this->user->canCreateShop();
case self::SWITCH_SHOP:
return $this->user->canSwitchToShop($shop);
case self::BO_VIEW:
// everybody see all customers
return $this->user->isPrestachefStaff();
}
throw new LogicException('This code should not be reached!');
}
}