<?php
namespace App\Security\Voter;
use App\Entity\Form;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class FormVoter extends Voter
{
public const EDIT = 'EDIT';
public const VIEW = 'VIEW';
/** @var Security */
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::EDIT, self::VIEW]) && ($subject instanceof Form || is_null($subject));
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if(is_null($subject)) {
return true;
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
if ($this->security->isGranted('ROLE_SUPERADMIN')) {
return true;
}
switch ($attribute) {
case self::EDIT:
case self::VIEW:
foreach ($user->getCompanies() as $company) {
foreach ($company->getCampaigns() as $campaign) {
if ($campaign->getForms()->contains($subject)) {
return true;
}
}
}
return false;
break;
}
return false;
}
}