<?php
// src/Security/PostVoter.php
namespace App\Security;
use App\Entity\Nea;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class NeaVoter extends Voter
{
// these strings are just invented: you can use anything
public const EDIT = 'edit';
public const VIEW = 'view';
public const DELETE = 'delete';
public const REFURBISHMENT = 'refurbishment';
public const ZUES = 'zues';
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
protected function supports($attribute, $subject): bool
{
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::EDIT, self::VIEW, self::DELETE, self::REFURBISHMENT, self::ZUES])) {
return false;
}
// only vote on `Post` objects
if (!$subject instanceof Nea) {
return false;
}
return true;
}
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 Post $post */
$nea = $subject;
switch ($attribute) {
case self::REFURBISHMENT:
return $this->canSetRefurbishment($nea, $user);
case self::ZUES:
return $this->canSetZues($nea, $user);
}
throw new \LogicException('This code should not be reached!');
}
private function canSetRefurbishment(Nea $nea, User $user): bool
{
if ($this->security->isGranted('ROLE_CUSTODIAN')) {
return true;
}
return false;
}
private function canSetZues(Nea $nea, User $user): bool
{
// this assumes that the Post object has a `getOwner()` method
if (
$this->security->isGranted('ROLE_CUSTODIAN')
|| $this->security->isGranted('ROLE_ZUES')
) {
return true;
}
return false;
}
private function canView(Nea $nea, User $user): bool
{
if (
$this->security->isGranted('ROLE_CUSTODIAN')
|| $this->security->isGranted('ROLE_DL')
|| $this->security->isGranted('ROLE_ZUES')
) {
return true;
}
return false;
}
}