<?php
namespace App\Security\Voter;
use App\Entity\Scp\Document;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class DocumentVoter 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 Document) {
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(Document $document, User $user): bool
{
if ($user->isMainAccount()) {
return $document->getCustomerNumber() === $user->getCustomerNumber();
}
return in_array($document->getContractNumber(), $user->getContactInformation()->getContractNumbers());
}
}