<?php
namespace App\Security;
use App\Entity\CBRCArticle;
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 ArticleVoter extends Voter
{
private $security;
// these strings are just invented: you can use anything
const EDIT = 'delete';
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 CBRCArticle) {
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->getAuthor();
throw new \LogicException('This code should not be reached!');
}
}
?>