<?php
namespace App\Security\Voter;
use App\Entity\FormActionsSet;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class FormActionsSetVoter extends Voter
{
public const EDIT = 'EDIT';
public const VIEW = 'VIEW';
/** @var Security $security */
private $security;
/**
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
/**
* @param string $attribute
* @param $subject
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::EDIT, self::VIEW]) && ($subject instanceof FormActionsSet || is_null($subject));
}
/**
* @param string $attribute
* @param $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if (is_null($subject)) {
return true;
}
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($this->security->isGranted('ROLE_SUPERADMIN')) {
return true;
}
switch ($attribute) {
case self::EDIT:
return $this->canEdit($user, $subject);
case self::VIEW:
return $this->canView($user, $subject);
}
return false;
}
/**
* @param User $user
* @param FormActionsSet $actionsSet
* @return bool
*/
private function canView(User $user, FormActionsSet $actionsSet): bool
{
return $user->getCompanies()->contains($actionsSet->getForm()->getCampaign()->getCompany());
}
/**
* @param User $user
* @param FormActionsSet $actionsSet
* @return bool
*/
private function canEdit(User $user, FormActionsSet $actionsSet): bool
{
return $this->canView($user, $actionsSet);
}
}