<?php
namespace App\Security\Voter;
use App\Entity\CompanyDemand;
use App\Entity\DemandFile;
use App\Entity\File;
use App\Entity\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class FileVoter extends Voter
{
protected function supports(string $attribute, $subject): bool
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, ['FILE_DOWNLOAD', 'FILE_REMOVE'], true)
&& $subject instanceof File;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof User) {
return false;
}
/** @var File $file */
$file = $subject;
switch ($attribute) {
case 'FILE_REMOVE':
return $file->getUser() === $user;
case 'FILE_DOWNLOAD':
if ($file->getUser() === $user) {
return true;
}
if (in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return true;
}
// at this stage, we already know that the current user is a company who is trying to download a demand file
if ($file->getDemandFile()) {
$demand = $file->getDemandFile()->getDemand();
if ($file->getDemandFile()->getType() === DemandFile::USER_PROOF_TYPE) {
return false;
}
return $demand->getCompanyDemands()->exists(function (int $key, CompanyDemand $companyDemand) use ($user): bool {
return $companyDemand->getCompany() === $user->getCompanies()->first();
});
}
if ($file->getDemandTree()) {
$demand = $file->getDemandTree()->getDemand();
return $demand->getCompanyDemands()->exists(function (int $key, CompanyDemand $companyDemand) use ($user): bool {
return $companyDemand->getCompany() === $user->getCompanies()->first();
});
}
throw new LogicException('Unexpected case.');
}
return false;
}
}