<?php
namespace App\Security\Voter;
use App\Entity\Beneficiary;
use App\Entity\ContractLine;
use App\Entity\Solicitation;
use App\Entity\User;
use App\Service\BookingService;
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 SolicitationVoter extends Voter
{
public const CREATE = 'create_solicitation';
public const EDIT = 'edit_solicitation';
public const SHOW = 'show_solicitation';
/** @var Security $security */
private $security;
/** @var BookingService $bookingService */
private $bookingService;
/**
* SolicitationVoter 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;
}
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 $subject
* @return bool
*/
private function canCreate($subject): bool
{
/** @var Beneficiary $beneficiary */
$beneficiary = $subject['beneficiary'];
/** @var ContractLine $ontractLine */
$ontractLine = $subject['contractLine'];
// Quantity 0 is unlimited, so we can create another solicitation
$availableQuantities = $this->bookingService->getAvailableQuantity($ontractLine, $beneficiary, null);
return (
$ontractLine->getEnabledRelevantPeriod() &&
$this->security->isGranted('ROLE_ATCLIENTE') &&
$availableQuantities
);
}
/**
* @param Solicitation $solicitation
* @return bool
*/
private function canEdit(Solicitation $solicitation): bool
{
$ontractLine = $solicitation->getContractLine();
// Quantity 0 is unlimited, so we can create another solicitation
return ($ontractLine->getEnabledRelevantPeriod() && $this->security->isGranted('ROLE_ATCLIENTE'));
}
/**
* @return bool
*/
private function canShow(): bool
{
return $this->security->isGranted('ROLE_ATCLIENTE');
}
}