<?php
namespace App\Infrastructure\Security\Voter;
use App\Database\Domain\Entity\Sessions\ToastSessionSection;
use App\Database\Domain\Entity\User\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ToastSessionSectionVoter extends Voter
{
public const ACCESS_BY_ROLE = 'toast_session_section.access_by_role';
public const ACCESS = 'toast_session_section.access';
public const ACCESS_BY_IDS = 'toast_session_section.access_by_ids';
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::ACCESS, self::ACCESS_BY_ROLE, self::ACCESS_BY_IDS]);
}
/**
* @param ToastSessionSection $subject
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($attribute === self::ACCESS_BY_ROLE) {
return $user->isFullUser() || $user->isPartialUser();
}
if ($attribute === self::ACCESS) {
return $user->getId() === $subject->getUser()->getId();
}
if ($attribute === self::ACCESS_BY_IDS) {
$userSections = array_map(
static fn (ToastSessionSection $item) => $item->getId(),
$user->getSections()->toArray()
);
foreach ($subject as $uuid) {
if (!in_array($uuid, $userSections)) { // Checking if all sessions belong to the user
return false;
}
}
return true;
}
return false;
}
}