<?php
namespace App\Voter;
use App\Entity\Supplier;
use App\Entity\SupplierCustomer;
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 SupplierCustomerVoter extends Voter
{
public const DECLARE_ACCOUNT = 'declare_account';
public const EDIT_ACCOUNT = 'edit_account';
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::DECLARE_ACCOUNT,
self::EDIT_ACCOUNT
])) {
return false;
}
// only vote on Supplier objects inside this voter
if (! $subject instanceof SupplierCustomer) {
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;
}
$this->user->setEntity($userEntity);
switch ($attribute) {
case self::DECLARE_ACCOUNT:
$supplierEntity = $entity->getSupplier();
$supplier = $this->supplierFactory->createModel();
$supplier->setEntity($supplierEntity);
return $supplier->accountCanBeDeclaredBy($this->user);
case self::EDIT_ACCOUNT:
$supplierEntity = $entity->getSupplier();
$supplier = $this->supplierFactory->createModel();
$supplier->setEntity($supplierEntity);
return $supplier->accountCanBeModifiedBy($entity, $this->user);
}
return false;
}
}