<?php
namespace App\Security\Voter;
use App\Entity\Groupement;
use App\Entity\UserAccess;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class GroupementVoter extends AbstractVoter
{
public const CREATE = 'Groupement:Create';
public const VIEW = 'Groupement:View';
public const EDIT = 'Groupement:Edit';
public const DELETE = 'Groupement:Delete';
public const CREATE_MAGASIN = 'Groupement:Create-Magasin';
private ?Groupement $groupement = null;
protected function supports(string $attribute, mixed $subject): bool
{
if ($attribute === self::CREATE) {
return true;
}
return in_array($attribute, [
self::EDIT,
self::VIEW,
self::DELETE,
self::CREATE_MAGASIN,
])
&& $subject instanceof Groupement;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$this->user = $token->getUser();
$this->groupement = $subject;
return match ($attribute) {
self::CREATE => $this->canCreate(),
self::VIEW => $this->canView(),
self::EDIT => $this->canEditGroupement(),
self::DELETE => $this->canDelete(),
self::CREATE_MAGASIN => $this->canCreateMagasin(),
default => false,
};
}
private function canCreate(): bool
{
return $this->isSuperAdmin();
}
private function canView(): bool
{
// Read-only superadmins can view all groupements
if ($this->isReadOnlySuperAdmin()) {
return true;
}
if ($this->isSuperAdmin()) {
return true;
}
return $this->isAdmin()
&& $this->user->canAccessResource($this->groupement, [UserAccess::ROLE_ADMIN]);
}
private function canEditGroupement(): bool
{
// Only full superadmins can edit, not read-only
return parent::canEdit();
}
public function canDelete(): bool
{
// Only full superadmins can delete, not read-only
return parent::canEdit()
&& $this->groupement->getId()
&& $this->groupement->getMagasins()->isEmpty();
}
public function canCreateMagasin(): bool
{
// Only full superadmins can create, not read-only
return parent::canEdit();
}
}