<?php
namespace App\Security;
use App\Entity\CBRCArticleComment;
use App\Entity\CBRCUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class ArticleCommentVoter extends Voter
{
private $security;
// these strings are just invented: you can use anything
const EDIT = 'edit';
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT])) {
return false;
}
// only vote on `CBRCArticleComment` objects
if (!$subject instanceof CBRCArticleComment) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if($attribute!=self::EDIT && $this->security->isGranted('ROLE_ADMIN'))
{
return true;
}
$user = $token->getUser();
if (!$user instanceof CBRCUser) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a CBRCArticleComment object, thanks to `supports()`
/** @var Post $post */
return $user==$subject->getUSer();
throw new \LogicException('This code should not be reached!');
}
}
?>