src/Security/Voters/UserVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voters;
  3. use App\Entity\Manufacturer;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. use Symfony\Component\Security\Core\Security;
  8. class UserVoter extends Voter
  9. {
  10.     private Security $security;
  11.     public const IF_USER_AGREED_CONDITIONS  'user.can_access';
  12.     public const IS_APP_CUSTOMER  'user.is_app_customer';
  13.     public const IS_MANUFACTURER 'user.is_manufacturer';
  14.     private const ATTRIBUTES = [
  15.         self::IF_USER_AGREED_CONDITIONS,
  16.         self::IS_MANUFACTURER,
  17.         self::IS_APP_CUSTOMER,
  18.     ];
  19.     public function __construct(Security $security)
  20.     {
  21.         $this->security $security;
  22.     }
  23.     protected function supports($attribute$subject): bool
  24.     {
  25.         return in_array($attributeself::ATTRIBUTES);
  26.     }
  27.     protected function voteOnAttribute($attribute$subjectTokenInterface $token): bool
  28.     {
  29.         switch ($attribute) {
  30.             case self::IF_USER_AGREED_CONDITIONS:
  31.                 return $this->canAccess($subject);
  32.             case self::IS_APP_CUSTOMER:
  33.                 return $this->isAppCustomer($subject);
  34.             case self::IS_MANUFACTURER:
  35.                 return $this->isManufacturer($subject);
  36.         }
  37.         throw new \LogicException('Invalid attribute: '.$attribute);
  38.     }
  39.     private function canAccess($subject) : bool
  40.     {
  41.         if ( !$this->security->getUser() ) {
  42.             return false;
  43.         }
  44.         if ( $this->security->isGranted('user.is_manufacturer') ) {
  45.             return false;
  46.         }
  47.         return true;
  48.     }
  49.     private function isAppCustomer(?User $user): bool
  50.     {
  51.         // return (bool)$this->security->getUser()->getCustomer(); // please use me --- TODO
  52.         if (!$user) {
  53.             return false;
  54.         }
  55.         return (bool)$user->getCustomer();
  56.     }
  57.     private function isManufacturer(): bool
  58.     {
  59.         if ( !$user $this->security->getUser()) {
  60.             return false;
  61.         }
  62.         return $user->getManufacturer() instanceof Manufacturer;
  63.     }
  64. }