src/Security/Voters/SubscriptionVoter.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voters;
  3. use App\Entity\CPSUser;
  4. use App\Entity\Subscription;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. use Symfony\Component\Security\Core\Security;
  9. class SubscriptionVoter extends Voter
  10. {
  11.   const EDIT 'edit';
  12.   const VIEW 'view';
  13.   private $security;
  14.   public function __construct(Security $security)
  15.   {
  16.     $this->security $security;
  17.   }
  18.   protected function supports($attribute$subject)
  19.   {
  20.     // if the attribute isn't one we support, return false
  21.     if (!in_array($attribute, [self::EDITself::VIEW])) {
  22.       return false;
  23.     }
  24.     // only vote on `Subscription` objects
  25.     if ($subject && !$subject instanceof Subscription) {
  26.       return false;
  27.     }
  28.     return true;
  29.   }
  30.   protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  31.   {
  32.     $user $token->getUser();
  33.     if (!$user instanceof User) {
  34.       // the user must be logged in; if not, deny access
  35.       return false;
  36.     }
  37.     // you know $subject is a Subscription object, thanks to `supports()`
  38.     /** @var Subscription $subscription */
  39.     $subscription $subject;
  40.     switch ($attribute) {
  41.       case self::EDIT:
  42.         return $this->canEdit($subscription$user);
  43.       case self::VIEW:
  44.         return $this->canView($subscription$user);
  45.     }
  46.     throw new \LogicException('This code should not be reached!');
  47.   }
  48.   private function canView(Subscription $subscriptionUser $user)
  49.   {
  50.     // if they can edit, they can view
  51.     if ($this->canEdit($subscription$user)) {
  52.       return true;
  53.     }
  54.     /** @var CPSUser $user */
  55.     return in_array($user->getCodiceFiscale(), array_merge([$subscription->getSubscriber()->getFiscalCode()], $subscription->getRelatedCFs()));
  56.   }
  57.   private function canEdit(Subscription $subscriptionUser $user)
  58.   {
  59.     if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_OPERATORE')) {
  60.       return true;
  61.     }
  62.     return false;
  63.   }
  64. }