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