<?php
declare(strict_types=1);
namespace App\Security\Voter;
use App\Entity\TeamUser;
use App\Entity\User;
use App\Repository\TeamUserRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
/**
* #3905 — TEAM_USER_VIEW : lire la fiche d'un participant (profil d'un autre membre dans l'app).
* Accordé à l'admin, au participant lui-même, à un participant du même challenge (classement, équipe)
* et au compte de l'entreprise qui organise le challenge. Refusé sinon (autre challenge, autre entreprise).
*/
class TeamUserVoter extends Voter
{
public const VIEW = 'TEAM_USER_VIEW';
private Security $security;
private TeamUserRepository $teamUserRepository;
public function __construct(Security $security, TeamUserRepository $teamUserRepository)
{
$this->security = $security;
$this->teamUserRepository = $teamUserRepository;
}
protected function supports(string $attribute, $subject): bool
{
return self::VIEW === $attribute && $subject instanceof TeamUser;
}
/**
* @param TeamUser $subject
*/
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if ($this->security->isGranted(User::ROLE_ADMIN)) {
return true;
}
$user = $token->getUser();
if (!$user instanceof User || null === $user->getId()) {
return false;
}
$owner = $subject->getUser();
if ($owner instanceof User && $owner->getId() === $user->getId()) {
return true;
}
$teamplay = $subject->getTeamplay();
if (null === $teamplay || null === $teamplay->getId()) {
return false;
}
if ($this->security->isGranted(User::ROLE_COMPANY)
&& null !== $user->getCompany()
&& null !== $teamplay->getCompany()
&& $user->getCompany()->getId() === $teamplay->getCompany()->getId()) {
return true;
}
// count() : pas d'hydratation, donc pas de calcul de stats au postLoad du lecteur
return $this->teamUserRepository->count(['teamplay' => $teamplay, 'user' => $user]) > 0;
}
}