<?php
namespace App\Security\Voter;
use App\Entity\Booking;
use App\Entity\BookingInterval;
use App\Entity\User;
use App\Service\BookingService;
use App\Service\SolicitationService;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class BookingIntervalVoter extends Voter
{
public const CREATE = 'create_booking_interval';
public const EDIT = 'edit_booking_interval';
public const SHOW = 'show_booking_interval';
/** @var Security $security */
private $security;
/** @var SolicitationService $solicitationService */
private $bookingService;
/**
* BookingIntervalVoter constructor.
* @param Security $security
* @param BookingService $bookingService
*/
public function __construct(Security $security, BookingService $bookingService)
{
$this->security = $security;
$this->bookingService = $bookingService;
}
/**
* @inheritDoc
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::CREATE, self::EDIT, self::SHOW])) {
return false;
}
if (!$subject instanceof Booking && !$subject instanceof BookingInterval) {
return false;
}
return true;
}
/**
* @inheritDoc
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
switch ($attribute) {
case self::CREATE:
return $this->canCreate($subject);
case self::EDIT:
return $this->canEdit($subject);
case self::SHOW:
return $this->canShow();
}
throw new LogicException('This code should not be reached!');
}
/**
* @param Booking $booking
* @return bool
*/
private function canCreate(Booking $booking): bool
{
$beneficiary = $booking->getSolicitation()->getBeneficiary();
$collectiveLine = $booking->getSolicitation()->getContractLine();
// Quantity 0 is unlimited, so we can create another solicitation
$availableQuantities = $this->bookingService->getAvailableQuantity($collectiveLine, $beneficiary, null);
return (
$collectiveLine->getEnabledRelevantPeriod() &&
$this->security->isGranted('ROLE_ATCLIENTE') &&
$availableQuantities
);
}
/**
* @param BookingInterval $bookingInterval
* @return bool
*/
private function canEdit(BookingInterval $bookingInterval): bool
{
$serviceBag = $bookingInterval->getBooking()->getSolicitation()->getContractLine();
// Quantity 0 is unlimited, so we can create another solicitation
return ($serviceBag->getEnabledRelevantPeriod() && $this->security->isGranted('ROLE_ATCLIENTE'));
}
/**
* @return bool
*/
private function canShow(): bool
{
return $this->security->isGranted('ROLE_ATCLIENTE');
}
}