<?php
namespace App\Security\Voters;
use App\Entity\Posts\Posts;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class PostsVoter extends Voter
{
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT = 'edit';
const DELETE = 'delete';
/**
* @param string $attribute
* @param mixed $subject
* @return bool
*/
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT, self::DELETE])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof Posts) {
return false;
}
return true;
}
/**
* @param string $attribute
* @param mixed $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a Post object, thanks to `supports()`
/** @var Posts $post */
$post = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($post, $user);
case self::EDIT:
return $this->canEdit($post, $user);
case self::DELETE:
return $this->canDelete($post, $user);
}
throw new \LogicException('This code should not be reached!');
}
/**
* @param Posts $post
* @param User $user
* @return bool
*/
private function canView(Posts $post, User $user): bool
{
// if they can edit, they can view
if ($this->canEdit($post, $user)) {
return true;
}
// the Post object could have, for example, a method `isPrivate()`
return !$post->getUser();
}
/**
* @param Posts $post
* @param User $user
* @return bool
*/
private function canEdit(Posts $post, User $user): bool
{
// this assumes that the Post object has a `getOwner()` method
return $user === $post->getUser();
}
/**
* @param Posts $post
* @param User $user
* @return bool
*/
private function canDelete(Posts $post, User $user): bool
{
// this assumes that the Post object has a `getOwner()` method
return $user === $post->getUser();
}
}