<?php
namespace App\Security\Voter;
use App\Entity\User;
use App\Service\Manager\AccountManager;
use App\Service\Manager\SitePermissionManager;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class AccountVoter extends Voter
{
const VIEW = 'ACCOUNT_VIEW';
const EDIT = 'ACCOUNT_EDIT';
private $accountManager;
private $sitePermissionManager;
public function __construct(AccountManager $accountManager, SitePermissionManager $sitePermissionManager)
{
$this->accountManager = $accountManager;
$this->sitePermissionManager = $sitePermissionManager;
}
protected function supports($attribute, $subject): bool
{
if (!in_array($attribute, [self::VIEW, self::EDIT])) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
if (null === $account = $this->accountManager->getAccountById($subject)) {
return false;
}
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if ($this->isViewAction($attribute)) {
return $this->sitePermissionManager->hasAccountViewPermission($account, $user);
}
if ($this->isEditAction($attribute)) {
return $this->sitePermissionManager->hasAccountEditPermission($account, $user);
}
return false;
}
protected function isViewAction(string $attribute): bool
{
return self::VIEW === $attribute;
}
protected function isEditAction(string $attribute): bool
{
return self::EDIT === $attribute;
}
}