<?php
namespace App\Security\Voter;
use App\Entity\CompanyDemand;
use App\Entity\Demand;
use App\Entity\DemandFile;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class DemandFileVoter 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, ['DEMAND_FILE_REMOVE'], true)
&& $subject instanceof DemandFile;
}
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 DemandFile $demandFile */
$demandFile = $subject;
$demand = $demandFile
->getDemand()
;
/** @var CompanyDemand|null
* $companyDemandSelected
*/
$companyDemandSelected = $demand->getCompanyDemands()->filter(function (CompanyDemand $companyDemand): bool {
return $companyDemand->getSelected() === true;
})->first();
/** @var CompanyDemand $companyAssigned */
$companyAssigned = $demand->getCompanyDemands()->filter(function (CompanyDemand $companyDemand) use ($user): bool {
return $companyDemand->getCompany() === $user->getCompanies()->first();
})->first();
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case 'DEMAND_FILE_REMOVE':
// logic to determine if the user can VIEW
// return true or false
if ($demand->getUser() === $user) {
if (
$demand->getStatus() <= Demand::IN_PENDING_STATUS ||
$demand->getStatus() === Demand::ON_GOING_STATUS ||
$demand->getStatus() === Demand::COMPANY_POSTED_FEEDBACK_STATUS ||
$demand->getStatus() === Demand::COMPLETE_STATUS
) {
return true;
}
}
if (in_array('ROLE_ADMIN', $user->getRoles(), true)) {
return true;
}
if ($companyAssigned->getCompany()->getUser() === $user) {
if (
$demand->getStatus() === Demand::INTERVENTION_CONFIRMATION_STATUS ||
$demand->getStatus() === Demand::SELECTED_COMPANY_STATUS
) {
return true;
}
}
if ($companyDemandSelected?->getCompany()?->getUser() === $user) {
if (
$demand->getStatus() === Demand::ON_GOING_STATUS ||
$demand->getStatus() === Demand::INTERVENTION_CONFIRMATION_STATUS ||
$demand->getStatus() === Demand::SELECTED_COMPANY_STATUS ||
$demand->getStatus() === Demand::USER_POSTED_FEEDBACK_STATUS ||
$demand->getStatus() === Demand::COMPLETE_STATUS
) {
return true;
}
}
return false;
}
return false;
}
}