<?php
namespace App\Security;
use App\Entity\BFFestival;
use App\Entity\BFUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class BFFestivalVoter extends Voter
{
private $security;
// these strings are just invented: you can use anything
const EDIT = 'edit';
const EDITNOTSUPER = 'editnotsuper';
const DELETE = 'delete';
const PAY = 'pay';
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject)
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT, self::DELETE, self::EDITNOTSUPER])) {
return false;
}
// only vote on `BFFestival` objects
if (!$subject instanceof BFFestival) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if($attribute!=self::EDITNOTSUPER && $this->security->isGranted('ROLE_SUPER_ADMIN'))
{
return true;
}
$user = $token->getUser();
if (!$user instanceof BFUser) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a BFFestival object, thanks to `supports()`
/** @var Post $post */
$bffestival = $subject;
switch ($attribute) {
case self::EDIT:
return $this->canEdit($bffestival, $user);
case self::EDITNOTSUPER:
return $this->canEdit($bffestival, $user);
case self::DELETE:
return $this->canDelete($bffestival, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canEdit(BFFestival $bffestival, BFUser $user)
{
// if they can edit, they can view
if ($this->canDelete($bffestival, $user)) {
return true;
}
return $bffestival->getAdministrators()->contains($user);
}
private function canDelete(BFFestival $bffestival, BFUser $user)
{
return $user==$bffestival->getOwner();
}
}
?>