<?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 CreatedByVoter extends Voter
{
/**
* @var Security
*/
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
// Make sure the voter is used only if the role creator is used and if the subject has a "getCreatedBy" function
return in_array($attribute, ['ROLE_CREATOR'])
&& method_exists($subject, 'getCreatedBy')
;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// Allow admins
/*if ($this->security->isGranted('ROLE_ADMIN')) {
return true;
}*/
// Allow if user match
return $subject->getCreatedBy() === $user;
}
}