<?php
namespace App\Security\Content;
use App\Entity\Content\BlogComment;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class BlogCommentVoter extends Voter
{
const VIEW = 'BLOG_COMMENT_VIEW';
const VIEW_ANY = 'BLOG_COMMENT_VIEW_ANY';
const APPROVE = 'BLOG_COMMENT_APPROVE';
const DENY = 'BLOG_COMMENT_DENY';
const DELETE = 'BLOG_COMMENT_DELETE';
/**
* UserVoter constructor.
*/
public function __construct(private readonly AccessDecisionManagerInterface $decisionManager)
{
}
/**
* @param string $attribute
* @param mixed $subject
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [
self::VIEW,
self::VIEW_ANY,
self::APPROVE,
self::DENY,
self::DELETE,
], true)) {
return false;
}
// only vote on Property objects inside this voter
return !($subject && !$subject instanceof BlogComment);
}
/**
* @param string $attribute
* @param mixed $subject
*
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
if ($this->decisionManager->decide($token, ['ROLE_SUPER_ADMIN'])) {
return true;
}
$user = $token->getUser();
if (!$user instanceof UserInterface) {
// the user must be logged in; if not, deny access
return false;
}
return match ($attribute) {
self::VIEW_ANY => $this->canViewAny($user),
self::VIEW => $this->canView($user),
self::APPROVE => $this->canApprove($user),
self::DENY => $this->canDeny($user),
self::DELETE => $this->canDelete($user),
default => throw new \LogicException('This code should not be reached!'),
};
}
/**
* Check if logged in User can view Property
*/
private function canView(UserInterface $user): bool
{
if ($this->canApprove($user)) {
return true;
}
if ($this->canDeny($user)) {
return true;
}
return $user->hasRole('ROLE_ADMIN');
}
/**
* Check if logged in User can view Property
*
*
*/
private function canViewAny(UserInterface $user): bool
{
if ($user->hasRight(self::VIEW_ANY)) {
return true;
}
return $user->hasRole('ROLE_ADMIN');
}
/**
* Check if logged in User can create Property
*
*
*/
private function canApprove(UserInterface $user): bool
{
if ($user->hasRight(self::APPROVE)) {
return true;
}
return $user->hasRole('ROLE_ADMIN');
}
/**
* Check if logged in User can edit Property
*/
private function canDeny(UserInterface $user): bool
{
if ($user->hasRight(self::DENY)) {
return true;
}
return $user->hasRole('ROLE_ADMIN');
}
/**
* Check if logged in User can delete Property
*/
private function canDelete(UserInterface $user): bool
{
if ($user->hasRight(self::DELETE)) {
return true;
}
return $user->hasRole('ROLE_ADMIN');
}
}