<?php
namespace App\Security\Voter;
use App\Entity\FormLeadData;
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 FormLeadDataVoter extends Voter
{
public const EDIT_BY_ADMIN = 'EDIT_BY_ADMIN';
/** @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_BY_ADMIN]) && ($subject instanceof FormLeadData);
}
/**
* @param string $attribute
* @param $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($this->security->isGranted('ROLE_SUPERADMIN')) {
return true;
}
switch ($attribute) {
case self::EDIT_BY_ADMIN:
return $this->editByAdmin($user, $subject);
}
return false;
}
/**
* @param User $user
* @param FormLeadData $leadData
* @return bool
*/
private function editByAdmin(User $user, FormLeadData $leadData): bool
{
return $user->getCompanies()->contains($leadData->getFormLead()->getCampaign()->getCompany());
}
}