<?php
declare(strict_types=1);
namespace App\Security\Voter\Voter;
use App\Entity\Job;
use App\Entity\Person;
use App\Entity\User;
use App\Security\Voter\AbstractVoter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
class PersonVoter extends AbstractVoter
{
/**
* @param string $attribute
* @param $subject
* @return bool
*/
protected function supports(string $attribute, $subject): bool
{
$cond1 = $subject instanceof Person;
$cond2 = in_array($attribute, [self::EDIT]);
return $cond1 && $cond2;
}
/**
* @param string $attribute
* @param $subject
* @param TokenInterface $token
* @return bool
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
return false;
}
if ($user->hasRole(User::ROLE_ADMIN)) {
return true;
}
switch ($attribute) {
case self::EDIT:
return $this->canEdit($subject, $user);
}
return false;
}
private function canEdit(Person $person, User $user): bool
{
if (!$user->hasRole(User::ROLE_ORGANIZATION_REDACTOR)) {
return false;
}
$cond1 = $user->getId() === $person->getCreatedBy()->getId();
$cond2 = false;
/** @var Job $job */
foreach ($person->getJobs() as $job) {
if ($user->getOrganization()->getId() === $job->getOrganization()->getId()) {
$cond2 = true;
}
}
return $cond1 || $cond2;
}
}