<?php
namespace App\Security\Voter;
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 NewsVoter extends Voter
{
/**
* @var Security
*/
private $security;
/**
* EmailingVoter constructor.
* @param Security $security
*/
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, ['CAN_EDIT_NEWS', 'CAN_ADD_NEWS']);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'CAN_EDIT_NEWS':
if (!$subject instanceof \App\Entity\Actualitecabinet) {
return false;
}
if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}
return $user->getAccountingFirm() === $subject->getAccountingFirm();
case 'CAN_ADD_NEWS':
return true;
}
return false;
}
}