<?php
namespace App\Security;
use App\Entity\Booking;
use App\Entity\Invoice;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class InvoiceVoter extends Voter
{
public const DOWNLOAD = 'download';
/**
* @var EntityManagerInterface
*/
protected $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
protected function supports($attribute, $subject): bool
{
return self::DOWNLOAD === $attribute && $subject instanceof Invoice;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if (!$subject instanceof Invoice) {
return false;
}
/** @var Booking|null $booking */
$booking = $this->entityManager->getRepository(Booking::class)
->findByInvoiceId($subject->getId());
if (!$booking) {
return false; // Invoice not related to a booking, shouldn't be accessible
}
return $booking->getUser() === $token->getUser();
}
}