<?php
namespace App\Security\Voters;
use App\Entity\Articles\Articles;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ArticlesVoter 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 `Article` objects
if (!$subject instanceof Articles) {
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 Article object, thanks to `supports()`
/** @var Articles $article */
$article = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($article, $user);
case self::EDIT:
return $this->canEdit($article, $user);
case self::DELETE:
return $this->canDelete($article, $user);
}
throw new \LogicException('This code should not be reached!');
}
/**
* @param Articles $article
* @param User $user
* @return bool
*/
private function canView(Articles $article, User $user): bool
{
// if they can edit, they can view
if ($this->canEdit($article, $user)) {
return true;
}
// the Article object could have, for example, a method `isPrivate()`
return !$article->getUser();
}
/**
* @param Articles $article
* @param User $user
* @return bool
*/
private function canEdit(Articles $article, User $user): bool
{
// this assumes that the Article object has a `getOwner()` method
return $user === $article->getUser();
}
/**
* @param Articles $article
* @param User $user
* @return bool
*/
private function canDelete(Articles $article, User $user): bool
{
// this assumes that the Article object has a `getOwner()` method
return $user === $article->getUser();
}
}