<?php
namespace App\Security\Voter;
use App\Entity\FreematicaReport;
use App\Entity\ContractLine;
use App\Entity\User;
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 FreematicaReportVoter extends Voter
{
public const EDIT = 'edit_freematica_report';
public const SHOW = 'show_freematica_report';
/** @var Security $security */
private $security;
/**
* FreematicaReportVoter constructor.
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @inheritDoc
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT, self::SHOW])) {
return false;
}
// only vote on ContractLine objects inside this voter
if (!$subject instanceof ContractLine && !$subject instanceof FreematicaReport) {
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::EDIT:
return $this->canEdit($subject);
case self::SHOW:
return $this->canShow();
}
throw new LogicException('This code should not be reached!');
}
/**
* @param FreematicaReport $report
* @return bool
*/
private function canEdit(FreematicaReport $report): bool
{
$collectiveLine = $report->getContractLine();
return ($this->security->isGranted('ROLE_ATCLIENTE') && $collectiveLine->getEnabledRelevantPeriod());
}
/**
* @return bool
*/
private function canShow(): bool
{
return $this->security->isGranted('ROLE_ATCLIENTE');
}
}