<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Company;
use App\Entity\Team;
use App\Entity\Teamplay;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
/**
* POST /api/teams (créer une team) : la team est toujours créée dans l'entreprise de l'utilisateur
* (le champ « company » du corps est ignoré) et son challenge doit appartenir à cette entreprise.
* Le compte d'une entreprise (back-office manager, sans fiche client) crée pour la sienne : une autre entreprise
* dans le corps est refusée. PATCH par ce compte : le challenge doit aussi appartenir à son entreprise.
* L'admin n'est pas concerné.
*/
class TeamCreateSubscriber implements EventSubscriberInterface
{
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['checkCreate', EventPriorities::PRE_VALIDATE],
];
}
public function checkCreate(ViewEvent $event): void
{
$team = $event->getControllerResult();
if (!$team instanceof Team || $this->security->isGranted(User::ROLE_ADMIN)) {
return;
}
$attributes = $event->getRequest()->attributes;
$user = $this->security->getUser();
$managedCompany = $user instanceof User && $this->security->isGranted(User::ROLE_COMPANY) ? $user->getCompany() : null;
if ('patch' === $attributes->get('_api_item_operation_name')) {
if (null !== $managedCompany) {
$this->assertTeamplayOfCompany($team, $managedCompany);
}
return;
}
if ('post' !== $attributes->get('_api_collection_operation_name')) {
return;
}
if (null !== $managedCompany && null !== $team->getCompany() && $team->getCompany()->getId() !== $managedCompany->getId()) {
throw new AccessDeniedHttpException('Cette entreprise n\'est pas la vôtre.');
}
$company = $managedCompany ?? ($user instanceof User && $user->getClient() ? $user->getClient()->getCompany() : null);
if (null === $company) {
throw new AccessDeniedHttpException('Aucune entreprise rattachée à votre compte.');
}
$team->setCompany($company);
$this->assertTeamplayOfCompany($team, $company);
}
private function assertTeamplayOfCompany(Team $team, Company $company): void
{
$teamplay = $team->getTeamplay();
if ($teamplay instanceof Teamplay && (null === $teamplay->getCompany() || $teamplay->getCompany()->getId() !== $company->getId())) {
throw new AccessDeniedHttpException('Ce challenge n\'appartient pas à votre entreprise.');
}
}
}