src/Security/InvoiceVoter.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Booking;
  4. use App\Entity\Invoice;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  7. use Symfony\Component\Security\Core\Authorization\Voter\Voter;
  8. class InvoiceVoter extends Voter
  9. {
  10.     public const DOWNLOAD 'download';
  11.     /**
  12.      * @var EntityManagerInterface
  13.      */
  14.     protected $entityManager;
  15.     public function __construct(EntityManagerInterface $entityManager)
  16.     {
  17.         $this->entityManager $entityManager;
  18.     }
  19.     protected function supports($attribute$subject): bool
  20.     {
  21.         return self::DOWNLOAD === $attribute && $subject instanceof Invoice;
  22.     }
  23.     protected function voteOnAttribute($attribute$subjectTokenInterface $token)
  24.     {
  25.         if (!$subject instanceof Invoice) {
  26.             return false;
  27.         }
  28.         /** @var Booking|null $booking */
  29.         $booking $this->entityManager->getRepository(Booking::class)
  30.             ->findByInvoiceId($subject->getId());
  31.         if (!$booking) {
  32.             return false// Invoice not related to a booking, shouldn't be accessible
  33.         }
  34.         return $booking->getUser() === $token->getUser();
  35.     }
  36. }