src/Security/CustomerVoter.php line 17

Open in your IDE?
  1. <?php
  2. /**
  3.  * @license SILK SOFTWARE HOUSE SP Z O O
  4.  */
  5. namespace App\Security;
  6. use App\Entity\Customer;
  7. use App\Entity\User;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  10. use LogicException;
  11. /**
  12.  * Class CustomerVoter.
  13.  */
  14. class CustomerVoter extends Voter
  15. {
  16.     const SHOW 'show';
  17.     const NEW = 'new';
  18.     const EDIT 'edit';
  19.     const DELETE 'delete';
  20.     /**
  21.      * Supports.
  22.      *
  23.      * @param string $attribute
  24.      * @param object $subject
  25.      *
  26.      * @return bool
  27.      */
  28.     protected function supports($attribute$subject)
  29.     {
  30.         // if the attribute isn't one we support, return false
  31.         if (!in_array($attribute, [self::SHOWself::NEW, self::EDITself::DELETE])) {
  32.             return false;
  33.         }
  34.         if (!$subject instanceof Customer) {
  35.             return false;
  36.         }
  37.         return true;
  38.     }
  39.     /**
  40.      * Vote on attribute.
  41.      *
  42.      * @param string         $attribute
  43.      * @param Customer       $subject
  44.      * @param TokenInterface $token
  45.      *
  46.      * @return bool
  47.      */
  48.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  49.     {
  50.         $user $token->getUser();
  51.         if (!$user instanceof User) {
  52.             // the user must be logged in; if not, deny access
  53.             return false;
  54.         }
  55.         if ($user->hasRole('ROLE_ADMIN')) {
  56.             return true;
  57.         }
  58.         return 'show' === $attribute && $user->getActiveCustomer() && $user->getActiveCustomer()->getId() === $subject->getId();
  59.     }
  60. }