<?php
namespace App\Security\Voter\GarageOwners;
use App\Entity\Garages\GarageOwner;
use App\Entity\User;
use App\Enum\MenuRolesAssociatedEnum;
use App\Enum\UserRolesEnum;
use App\Enum\VotersEnum;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
final class GarageOwnerVoter extends Voter
{
private Security $security;
private array $voters;
public function __construct(Security $security)
{
$this->security = $security;
$this->voters = [
VotersEnum::LIST_GARAGE_OWNER,
VotersEnum::LIST_GARAGE_OWNER_ASSOCIATED,
VotersEnum::MEET_YOUR_PEERS_ASSOCIATED,
VotersEnum::VIEW_YOUR_PEER_ASSOCIATED,
VotersEnum::EXPORT_GARAGE_OWNER,
];
}
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 GarageOwner) {
// 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_GARAGE_OWNER:
return $this->canList();
case VotersEnum::LIST_GARAGE_OWNER_ASSOCIATED:
return $this->canListAssociated();
case VotersEnum::MEET_YOUR_PEERS_ASSOCIATED:
return $this->canMeetYourPeersAssociated();
case VotersEnum::VIEW_YOUR_PEER_ASSOCIATED:
return $this->canViewYourPeerAssociated();
case VotersEnum::EXPORT_GARAGE_OWNER:
return $this->canExport();
}
throw new \LogicException('This code should not be reached!');
}
private function canList(): bool
{
return $this->isAdminUser();
}
private function canListAssociated(): bool
{
return $this->isAssociatedUser();
}
private function canMeetYourPeersAssociated(): bool
{
return $this->isAdminUser() || $this->isAssociatedUser();
}
private function canViewYourPeerAssociated(): bool
{
return $this->isAdminUser() || $this->isAssociatedUser();
}
private function canExport(): bool
{
return $this->isAdminUser();
}
private function isAdminUser(): bool
{
return $this->security->isGranted(UserRolesEnum::ROLE_ADMIN_LONG);
}
private function isAssociatedUser(): bool
{
return $this->security->isGranted(MenuRolesAssociatedEnum::ROLE_MENU_GARAGE_OWNER_ASSOCIATED);
}
}