src/Voters/ContactVoter.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\Voters;
  3. use App\Model\Contact\Contact;
  4. use App\Security\SecurityConfig;
  5. use App\Security\User;
  6. use LogicException;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  9. /**
  10.  * Class ContactVoter.
  11.  */
  12. final class ContactVoter extends Voter
  13. {
  14.     /**
  15.      * @param string  $attribute
  16.      * @param Contact $subject
  17.      *
  18.      * @return bool
  19.      */
  20.     protected function supports($attribute$subject)
  21.     {
  22.         if (!in_array($attribute, [SecurityConfig::CONTACT_SHOW,
  23.             SecurityConfig::CONTACT_CUD,
  24.             SecurityConfig::MY_CONTACT_BY_DEFAULT, ], true)) {
  25.             return false;
  26.         }
  27.         return true;
  28.     }
  29.     /**
  30.      * @param string         $attribute
  31.      * @param Contact        $subject
  32.      * @param TokenInterface $token
  33.      *
  34.      * @return bool
  35.      */
  36.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  37.     {
  38.         $user $token->getUser();
  39.         if (!$user instanceof User) {
  40.             return false;
  41.         }
  42.         switch ($attribute) {
  43.             case SecurityConfig::CONTACT_SHOW:
  44.                 return $this->canViewContact($user);
  45.             case SecurityConfig::CONTACT_CUD:
  46.                 return $this->canCudContact($user);
  47.             case SecurityConfig::MY_CONTACT_BY_DEFAULT:
  48.                 return $this->hasHisContactByDefault($user);
  49.         }
  50.         throw new LogicException('This code should not be reached!');
  51.     }
  52.     /**
  53.      * @param User $user
  54.      *
  55.      * @return bool
  56.      */
  57.     private function canViewContact(User $user)
  58.     {
  59.         if ($user->isAdmin()) {
  60.             return true;
  61.         }
  62.         return in_array(SecurityConfig::CONTACT_SHOW$user->getRoles(), true);
  63.     }
  64.     /**
  65.      * @param User $user
  66.      *
  67.      * @return bool
  68.      */
  69.     private function canCudContact(User $user)
  70.     {
  71.         if ($user->isAdmin()) {
  72.             return true;
  73.         }
  74.         return in_array(SecurityConfig::CONTACT_CUD$user->getRoles(), true);
  75.     }
  76.     /**
  77.      * @param User $user
  78.      *
  79.      * @return bool
  80.      */
  81.     private function hasHisContactByDefault(User $user)
  82.     {
  83.         return in_array(SecurityConfig::MY_CONTACT_BY_DEFAULT$user->getRoles(), true);
  84.     }
  85. }