src/Security/Voter/MediaVoter.php line 9

Open in your IDE?
  1. <?php
  2. namespace App\Security\Voter;
  3. use App\Entity\Media\Media;
  4. use App\Entity\User;
  5. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  6. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  7. class MediaVoter extends Voter
  8. {
  9.     // these strings are just invented: you can use anything
  10.     const SHOW 'show';
  11.     const EDIT 'edit';
  12.     const DELETE 'delete';
  13.     const CHAT 'chat';
  14.     protected function supports(string $attribute$subject): bool
  15.     {
  16.         // if the attribute isn't one we support, return false
  17.         if (!in_array($attribute, [self::SHOWself::EDITself::DELETEself::CHAT])) {
  18.             return false;
  19.         }
  20.         // only vote on `Post` objects
  21.         if (!$subject instanceof Media) {
  22.             return false;
  23.         }
  24.         return true;
  25.     }
  26.     protected function voteOnAttribute(string $attribute$subjectTokenInterface $token): bool
  27.     {
  28.         $user $token->getUser();
  29.         if (!$user instanceof User) {
  30.             // the user must be logged in; if not, deny access
  31.             return false;
  32.         }
  33.         // you know $subject is a Post object, thanks to `supports()`
  34.         /** @var Media $media */
  35.         $media $subject;
  36.         switch ($attribute) {
  37.             case self::SHOW:
  38.                 return $this->canView($media$user);
  39.             case self::EDIT:
  40.                 return $this->canEdit($media$user);
  41.             case self::DELETE:
  42.                 return $this->canDelete($media$user);
  43.             case self::CHAT:
  44.                 return $this->canChat($media$user);
  45.         }
  46.         throw new \LogicException('This code should not be reached!');
  47.     }
  48.     private function canView(Media $mediaUser $user): bool
  49.     {
  50.         // if they can edit, they can view
  51.         /*if ($this->canEdit($media, $user)) {
  52.             return true;
  53.         }*/
  54.         // the Post object could have, for example, a method `isPrivate()`
  55.         return $media->getCreatedBy() === $user;
  56.     }
  57.     private function canEdit(Media $mediaUser $user): bool
  58.     {
  59.         return $media->getCreatedBy() === $user;
  60.         // this assumes that the Post object has a `getOwner()` method
  61.         //return $user === $post->getOwner();
  62.     }
  63.     private function canDelete(Media $mediaUser $user): bool
  64.     {
  65.         return $media->getCreatedBy() === $user;
  66.     }
  67.     private function canChat(Media $mediaUser $user): bool
  68.     {
  69.         return $media->getCreatedBy() === $user;
  70.     }
  71. }