src/Security/AttachmentVoter.php line 12

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Security;
  4. use App\Entity\Attachment;
  5. use App\Entity\User;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class AttachmentVoter extends Voter
  9. {
  10.     public const EDIT = 'ATTACHMENT_EDIT';
  11.     public function supportsAttribute(string $attribute): bool
  12.     {
  13.         return $attribute === self::EDIT;
  14.     }
  15.     public function supportsType(string $subjectType): bool
  16.     {
  17.         return is_a($subjectType, Attachment::class, true);
  18.     }
  19.     protected function supports(string $attribute, mixed $subject): bool
  20.     {
  21.         return $subject instanceof Attachment && $this->supportsAttribute($attribute);
  22.     }
  23.     protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
  24.     {
  25.         /** @var Attachment $subject */
  26.         $user = $token->getUser();
  27.         return $user instanceof User && $this->isOwner($subject, $user);
  28.     }
  29.     private function isOwner(Attachment $attachment, User $user): bool
  30.     {
  31.         $owner = $attachment->createdBy;
  32.         return $owner instanceof User && $owner->getId()->equals($user->getId());
  33.     }
  34. }