<?php
namespace App\Security\Voter;
use App\Entity\DemandTree;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class DemandTreeVoter extends Voter
{
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, ['DEMAND_TREE_FILE_UPLOAD'], true)
&& $subject instanceof DemandTree;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof User) {
return false;
}
/** @var DemandTree $demandTreeFile */
$demandTreeFile = $subject;
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'DEMAND_TREE_FILE_UPLOAD':
return ($demandTreeFile->getDemand()->getUser() === $user)
|| in_array('ROLE_ADMIN', $user->getRoles(), true);
}
return false;
}
}