src/AppBundle/Security/Voter/AddressVoter.php line 10

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Security\Voter;
  3. use AppBundle\Entity\Address;
  4. use AppBundle\Entity\Customer;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class AddressVoter extends Voter
  8. {
  9.     // these consts are the action that are voted on
  10.     public const EDIT 'edit';
  11.     protected function supports($attribute$subject)
  12.     {
  13.         // if the attribute isn't one we support, return false
  14.         if (!in_array($attribute, [self::EDIT])) {
  15.             return false;
  16.         }
  17.         // only vote on Address objects inside this voter
  18.         if (!$subject instanceof Address) {
  19.             return false;
  20.         }
  21.         return true;
  22.     }
  23.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  24.     {
  25.         $customer $token->getUser();
  26.         if (!$customer instanceof Customer) {
  27.             // the customer must be logged in; if not, deny access
  28.             return false;
  29.         }
  30.         // you know $subject is a Address object, thanks to supports
  31.         /** @var Address $address */
  32.         $address $subject;
  33.         return $this->canEdit($address$customer);
  34.         throw new \LogicException('This code should not be reached!');
  35.     }
  36.     private function canEdit(Address $addressCustomer $customer)
  37.     {
  38.         // check if the customer is associated with the address
  39.         // and is therefore able to edit it
  40.         if ($address->getId()) {
  41.             return $customer === $address->getCustomer();
  42.         }
  43.         return true;
  44.     }
  45. }