<?php
namespace AppBundle\Security\Voter;
use AppBundle\Entity\Address;
use AppBundle\Entity\Customer;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class AddressVoter extends Voter
{
// these consts are the action that are voted on
public const EDIT = 'edit';
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT])) {
return false;
}
// only vote on Address objects inside this voter
if (!$subject instanceof Address) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$customer = $token->getUser();
if (!$customer instanceof Customer) {
// the customer must be logged in; if not, deny access
return false;
}
// you know $subject is a Address object, thanks to supports
/** @var Address $address */
$address = $subject;
return $this->canEdit($address, $customer);
throw new \LogicException('This code should not be reached!');
}
private function canEdit(Address $address, Customer $customer)
{
// check if the customer is associated with the address
// and is therefore able to edit it
if ($address->getId()) {
return $customer === $address->getCustomer();
}
return true;
}
}