|
@@ -0,0 +1,58 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace App\Security\Voter;
|
|
|
+
|
|
|
+use App\Entity\Article;
|
|
|
+use App\Entity\User;
|
|
|
+use Symfony\Bundle\SecurityBundle\Security;
|
|
|
+use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
|
|
|
+use Symfony\Component\Security\Core\Authorization\Voter\Voter;
|
|
|
+
|
|
|
+final class ArticleVoter extends Voter
|
|
|
+{
|
|
|
+ public const EDIT = 'edit';
|
|
|
+ public const VIEW = 'view';
|
|
|
+
|
|
|
+ public function __construct(
|
|
|
+ private readonly Security $security
|
|
|
+ )
|
|
|
+ {
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ protected function supports(string $attribute, mixed $subject): bool
|
|
|
+ {
|
|
|
+ // replace with your own logic
|
|
|
+ // https://symfony.com/doc/current/security/voters.html
|
|
|
+ return in_array($attribute, [self::EDIT, self::VIEW])
|
|
|
+ && $subject instanceof \App\Entity\Article;
|
|
|
+ }
|
|
|
+
|
|
|
+ protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
|
|
|
+ {
|
|
|
+ $user = $token->getUser();
|
|
|
+
|
|
|
+ // if the user is anonymous, do not grant access
|
|
|
+ if (!$user instanceof User) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ $article = $subject;
|
|
|
+
|
|
|
+ return match($attribute) {
|
|
|
+ self::VIEW => $this->canView($article, $user),
|
|
|
+ self::EDIT => $this->canEdit($article, $user),
|
|
|
+ default => throw new \LogicException('This code should not be reached!')
|
|
|
+ };
|
|
|
+ }
|
|
|
+
|
|
|
+ private function canView(Article $article, User $user): bool
|
|
|
+ {
|
|
|
+ return $this->canEdit($article, $user);
|
|
|
+ }
|
|
|
+
|
|
|
+ private function canEdit(Article $article, User $user): bool
|
|
|
+ {
|
|
|
+ return $user === $article->getAuthor() || $this->security->isGranted('ROLE_ADMIN');
|
|
|
+ }
|
|
|
+}
|