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