src/Security/Voter/PostVoter.php line 13
<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\User\User;
use App\Entity\Wiki\Post;
use App\Helper\UserHelper;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class PostVoter extends Voter
{
const VIEW = 'VIEW';
const DELETE = 'DELETE';
const EDIT = 'EDIT';
protected function supports(string $attribute, mixed $subject): bool
{
if (!\in_array($attribute, [self::VIEW, self::DELETE, self::EDIT])) {
return false;
}
if (!$subject instanceof Post) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
/** @var Post $post */
$post = $subject;
return match ($attribute) {
self::VIEW => $this->canView($user, $post),
self::DELETE => UserHelper::isAdmin($user),
self::EDIT => $this->canEdit($user, $post),
default => throw new \LogicException('This code should not be reached!'),
};
}
private function canView(User $user, Post $post): bool
{
if (UserHelper::isAdmin($user)) {
return true;
}
if (Post::STATUS__PUBLISHED === $post->getStatus()) {
return true;
}
if ($user->getId() === $post->author()->getId()) {
return true;
}
return false;
}
private function canEdit(User $user, Post $post): bool
{
if (UserHelper::isAdmin($user)) {
return true;
}
if ($user->getId() === $post->author()->getId()) {
return true;
}
return false;
}
}