<?php
declare(strict_types=1);
namespace App\Bundles\OrganizationBundle\Security\Voter;
use App\Bundles\OrganizationBundle\Entity\Organization;
use App\Bundles\OrganizationBundle\Enum\UserOrganizationResponsibleLevelEnum;
use App\Bundles\OrganizationBundle\Exception\UserOrganizationNotFoundException;
use App\Bundles\OrganizationBundle\Repository\OrganizationRepository;
use App\Bundles\OrganizationBundle\Service\UserOrganization\UserOrganizationProvider;
use App\Bundles\OrganizationBundle\Service\UserOrganization\UserOrganizationResponsibleLevelResolver;
use App\Bundles\UserBundle\Enum\SystemPermissionEnum;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class OrganizationVoter extends Voter
{
public function __construct(
private readonly UserOrganizationProvider $userOrganizationProvider,
private readonly UserOrganizationResponsibleLevelResolver $levelResolver,
private readonly OrganizationRepository $organizationRepository,
) {
}
protected function supports(string $attribute, $subject): bool
{
return $attribute === SystemPermissionEnum::SPECIFIC_ORGANIZATION_VIEW->value;
}
/** @param Organization $subject
* @throws UserOrganizationNotFoundException
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if (
$this->levelResolver->resolve() === UserOrganizationResponsibleLevelEnum::NATIONAL_LEVEL->value
) {
return true;
}
return $this->organizationRepository->withinAvailableOrganization(
$subject,
$this->userOrganizationProvider->provideFromSession()->getOrganization()
);
}
}