src/Security/Voter/UserVoter.php line 9
<?php
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class UserVoter extends Voter
{
const VIEW = 'VIEW';
const CREATE = 'CREATE';
const EDIT = 'EDIT';
const DELETE = 'DELETE';
protected function supports(string $attribute, mixed $subject): bool
{
$attributeArray = [self::VIEW, self::CREATE, self::EDIT, self::DELETE];
if (!in_array($attribute, $attributeArray))
return false;
if (!$subject instanceof User)
return false;
return true;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User)
return false;
return match ($attribute) {
self::VIEW => $this->canView($subject, $user),
self::CREATE => $this->canCreate($subject, $user),
self::EDIT => $this->canEdit($subject, $user),
self::DELETE => $this->canDelete($subject, $user),
default => throw new \LogicException('This code should not be reached!')
};
}
private function canCreate(User $supposedUser, User $user): bool
{
return in_array(User::ROLE_SUPER_ADMIN, $user->getRoles());
}
private function canDelete(User $supposedUser, User $user): bool
{
if ($user->getId() === $supposedUser->getId()) {
return false;
}
return $this->canCreate($supposedUser, $user);
}
public function canView(User $supposedUser, User $user): bool
{
return true;
}
public function canEdit(User $supposedUser, User $user): bool
{
if ($this->canCreate($supposedUser, $user) || $user->getId() === $supposedUser->getId()) {
return true;
}
return false;
}
}