<?php
namespace App\Security\Voter;
use App\DataTransferObject\Contract;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ContractVoter extends Voter
{
public const VIEW = 'VIEW';
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function supports($attribute, $subject)
{
if ($attribute !== static::VIEW) {
return false;
}
if (!$subject instanceof Contract) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if (static::VIEW === $attribute) {
return $this->canView($subject, $user);
}
return false;
}
protected function canView(Contract $contract, User $user): bool
{
if ($user->isMainAccount()) {
return $contract->getCustomerNumber() === $user->getCustomerNumber();
}
return in_array($contract->getContractNumber(), $user->getContactInformation()->getContractNumbers());
}
}