<?php
namespace App\Security\Voter;
use App\DTO\Site\AddSite;
use App\Entity\User;
use App\Service\Manager\AccountManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class AddSiteVoter extends Voter
{
const ADD_SITE = 'ADD_SITE';
const EDIT_SITE = 'EDIT_SITE';
/**
* @var AccountManager
*/
private $accountManager;
public function __construct(AccountManager $accountManager)
{
$this->accountManager = $accountManager;
}
protected function supports($attribute, $subject): bool
{
if (!in_array($attribute, [self::ADD_SITE, self::EDIT_SITE])) {
return false;
}
if (!$subject instanceof AddSite) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param AddSite $subject
* @param TokenInterface $token
*
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if (null === $subject->account) {
return true;
}
if (null === $account = $this->accountManager->getAccountById($subject->account)) {
return false;
}
return $this->accountManager->hasEditPermission($account, $user);
}
}