src/Modules/Chat/Security/ChatVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Modules\Chat\Security;
  3. use App\Modules\Chat\Entity\Chat;
  4. use App\Modules\User\Entity\UserContract;
  5. use Symfony\Component\Security\Core\Security;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class ChatVoter extends Voter
  9. {
  10.     const GET_ACCESS 'get_access';
  11.     static $access = [
  12.         self::GET_ACCESS
  13.     ];
  14.     private $security;
  15.     public function __construct(Security $security)
  16.     {
  17.         $this->security $security;
  18.     }
  19.     /**
  20.      * Determines if the attribute and subject are supported by this voter.
  21.      *
  22.      * @param string $attribute An attribute
  23.      * @param mixed  $subject   The subject to secure, e.g. an object the user wants to access or any other PHP type
  24.      *
  25.      * @return bool True if the attribute and subject are supported, false otherwise
  26.      */
  27.     protected function supports($attribute$subject)
  28.     {
  29.         if (!in_array($attributeself::$access)) {
  30.             return false;
  31.         }
  32.         return true;
  33.     }
  34.     /**
  35.      * Perform a single access check operation on a given attribute, subject and token.
  36.      * It is safe to assume that $attribute and $subject already passed the "supports()" method check.
  37.      *
  38.      * @param string         $attribute
  39.      * @param mixed          $subject
  40.      *
  41.      * @param TokenInterface $token
  42.      *
  43.      * @return bool
  44.      */
  45.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  46.     {
  47.         $user $token->getUser();
  48.         if (!$user instanceof UserContract) {
  49.             // the user must be logged in; if not, deny access
  50.             return false;
  51.         }
  52.         $chat $subject;
  53.         switch ($attribute) {
  54.             case self::GET_ACCESS:
  55.                 return $this->canAccess($chat$user);
  56.         }
  57.     }
  58.     private function canAccess(Chat $chatUserContract $user)
  59.     {
  60.         if ($chat->hasParticipant($user)) {
  61.             return true;
  62.         }
  63.         return false;
  64.     }
  65. }