src/Security/UserVoter.php line 15

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\User;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. /**
  10.  * Class UserVoter.
  11.  */
  12. class UserVoter extends Voter
  13. {
  14.     const SHOW 'show';
  15.     const NEW = 'new';
  16.     const EDIT 'edit';
  17.     const DELETE 'delete';
  18.     /**
  19.      * Supports.
  20.      *
  21.      * @param string $attribute
  22.      * @param object $subject
  23.      *
  24.      * @return bool
  25.      */
  26.     protected function supports($attribute$subject)
  27.     {
  28.         // if the attribute isn't one we support, return false
  29.         if (!in_array($attribute, [self::SHOWself::NEW, self::EDITself::DELETE])) {
  30.             return false;
  31.         }
  32.         if (!$subject instanceof User) {
  33.             return false;
  34.         }
  35.         return true;
  36.     }
  37.     /**
  38.      * Vote on attribute.
  39.      *
  40.      * @param string         $attribute
  41.      * @param User           $subject
  42.      * @param TokenInterface $token
  43.      *
  44.      * @return bool
  45.      */
  46.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  47.     {
  48.         $user $token->getUser();
  49.         if (!$user instanceof User) {
  50.             return false;
  51.         }
  52.         if ($user->hasRole('ROLE_ADMIN')) {
  53.             return true;
  54.         }
  55.         if (!$user->hasRole('ROLE_CUSTOMER')) {
  56.             return false;
  57.         }
  58.         if (in_array($attribute, [self::SHOWself::NEW])) {
  59.             return $user->hasRole('ROLE_USER');
  60.         }
  61.         if (!$user->getActiveCustomer() || !$subject->getActiveCustomer()) {
  62.             return false;
  63.         }
  64.         if ($subject->getActivatedAt() && $subject->hasRole('ROLE_CUSTOMER')) {
  65.             return false;
  66.         }
  67.         return $subject->getActiveCustomer()->getId() === $user->getActiveCustomer()->getId();
  68.     }
  69. }