<?php
namespace App\Voter;
use App\Entity\Supplier;
use App\Entity\User as UserEntity;
use App\Model\SupplierFactory;
use App\Model\User\User;
use Exception;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class SupplierVoter extends Voter
{
public const CREATE_GUEST_SUPPLIER = 'create_guest_supplier';
public const MANAGE_GUEST_SUPPLIER = 'manage_guest_supplier';
public const DECLARE_SUPPLIER_ACCOUNT = 'declare_supplier_account';
public const VIEW_SUPPLIER = 'view_supplier';
private $user;
/**
* @var SupplierFactory
*/
private $supplierFactory;
public function __construct(User $user, SupplierFactory $supplierFactory)
{
$this->user = $user;
$this->supplierFactory = $supplierFactory;
}
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (! in_array($attribute, [
self::CREATE_GUEST_SUPPLIER,
self::MANAGE_GUEST_SUPPLIER,
self::DECLARE_SUPPLIER_ACCOUNT,
self::VIEW_SUPPLIER
])) {
return false;
}
// only vote on Supplier objects inside this voter
if (! $subject instanceof Supplier) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param Supplier $entity
*
* @return bool
* @throws Exception
*/
protected function voteOnAttribute($attribute, $entity, TokenInterface $token): bool
{
$userEntity = $token->getUser();
if (! $userEntity instanceof UserEntity) {
// the user must be logged in; if not, deny access
return false;
}
switch ($attribute) {
case self::CREATE_GUEST_SUPPLIER:
return $this->user->canManageCurrentShopGuestSuppliers();
case self::MANAGE_GUEST_SUPPLIER:
$supplier = $this->supplierFactory->createModel();
$supplier->setEntity($entity);
return $supplier->canBeManagedBy($this->user);
case self::DECLARE_SUPPLIER_ACCOUNT:
$supplier = $this->supplierFactory->createModel();
$supplier->setEntity($entity);
return $supplier->accountCanBeDeclaredBy($this->user);
case self::VIEW_SUPPLIER:
$supplier = $this->supplierFactory->createModel();
$supplier->setEntity($entity);
return $supplier->canBeViewedBy($this->user);
}
return false;
}
}