<?php
namespace App\Security\Voter\Api;
use App\Entity\File;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class FileVoter extends Voter
{
public const VIEW = 'view';
public const EDIT = 'edit';
public const DOWNLOAD = 'download';
protected function supports(string $attribute, $subject): bool
{
return in_array($attribute, [self::VIEW, self::EDIT, self::DOWNLOAD])
&& $subject instanceof File;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return false;
}
return match ($attribute) {
self::VIEW, self::EDIT => $subject->getOwner() === $user->getProfile(),
self::DOWNLOAD => $this->canDownload($subject, $user),
default => false,
};
}
private function canDownload(
File $subject,
User $user
) {
if (in_array("ROLE_COACH", $user->getRoles())){
$obj = $user->getProfile()->getCoach();
}
$company = array_filter($obj?->getCompanies()->toArray(), function ($companie) use ($subject){
return $companie->getKBIS()->getId() === $subject->getId();
});
return match (true){
$obj?->getAPADiploma()?->getId() === $subject->getId() => true,
$obj?->getSAPDiploma()?->getId() === $subject->getId() => true,
!empty($company) => true,
default => false,
};
}
}