<?php
namespace App\Security\Voter;
use App\Entity\Beneficiary;
use App\Entity\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class BeneficiaryVoter extends Voter
{
public const EDIT = 'beneficiary-edit';
public const ADD_ASSOCIATED = 'beneficiary-add-associated';
public const SHOW = 'beneficiary-show';
/**
* @inheritDoc
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT, self::ADD_ASSOCIATED, self::SHOW])) {
return false;
}
// only vote on `Beneficiary` objects
if (!$subject instanceof Beneficiary) {
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;
}
/** @var Beneficiary $beneficiary */
$beneficiary = $subject;
switch ($attribute) {
case self::EDIT:
return $this->canEdit($beneficiary, $user);
case self::ADD_ASSOCIATED:
return $this->canAddAssociated($beneficiary, $user);
case self::SHOW:
return $this->canShow($beneficiary, $user);
}
throw new LogicException('This code should not be reached!');
}
/**
* @param Beneficiary $beneficiary
* @param User $user
* @return bool
*/
private function canEdit(Beneficiary $beneficiary, User $user): bool
{
return $this->canShow($beneficiary, $user);
}
/**
* @param Beneficiary $beneficiary
* @param User $user
* @return bool
*/
private function canAddAssociated(Beneficiary $beneficiary, User $user): bool
{
$beneficiary->getCollective()->getProtectedPeople();
return ($this->canShow($beneficiary, $user) &&
$beneficiary->getBeneficiaryRelationMode()->getIsDefault() &&
$beneficiary->getCollective()->allowAssociatedBeneficiaries()
);
}
/**
* @param Beneficiary $beneficiary
* @param User $user
* @return bool
*/
private function canShow(Beneficiary $beneficiary, User $user): bool
{
return ($user->hasRole('ROLE_ATCLIENTE') && $beneficiary->getIsActive());
}
}