src/Security/Chat/MessageFileVoter.php line 11

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