<?php
namespace App\Security\Voter\JoinTheNetwork;
use App\Entity\JoinTheNetwork\JoinTheNetwork;
use App\Entity\User;
use App\Enum\UserRolesEnum;
use App\Enum\VotersEnum;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
class JoinTheNetworkVoter extends Voter
{
private Security $security;
private array $voters;
public function __construct(Security $security)
{
$this->security = $security;
$this->voters = [
VotersEnum::LIST_JOIN_THE_NETWORK,
VotersEnum::CREATE_JOIN_THE_NETWORK,
VotersEnum::READ,
VotersEnum::UPDATE,
VotersEnum::DELETE,
VotersEnum::EXPORT_JOIN_THE_NETWORK,
];
}
protected function supports(string $attribute, $subject): bool
{
// first check the $subject and last if the $attribute is supported,
// because there are attributes (with subject) used as well by other voters (like UPDATE, ...)
if ($subject && !$subject instanceof JoinTheNetwork) {
// only vote on these objects
return false;
}
if (in_array($attribute, $this->voters)) {
// if the attribute is one we support
return true;
}
return false;
}
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;
}
switch ($attribute) {
case VotersEnum::LIST_JOIN_THE_NETWORK:
return $this->canList();
case VotersEnum::CREATE_JOIN_THE_NETWORK:
return $this->canCreate();
case VotersEnum::READ:
return $this->canRead();
case VotersEnum::UPDATE:
return $this->canUpdate();
case VotersEnum::DELETE:
return $this->canDelete();
case VotersEnum::EXPORT_JOIN_THE_NETWORK:
return $this->canExport();
}
throw new LogicException('This code should not be reached!');
}
private function canList(): bool
{
return $this->isAdminUser();
}
private function canCreate(): bool
{
return $this->isAdminUser();
}
private function canRead(): bool
{
return $this->isAdminUser();
}
private function canUpdate(): bool
{
return $this->isAdminUser();
}
private function canDelete(): bool
{
return $this->isAdminUser();
}
private function canExport(): bool
{
return $this->isAdminUser();
}
private function isAdminUser(): bool
{
return $this->security->isGranted(UserRolesEnum::ROLE_ADMIN_LONG);
}
}