← Back
Editing: ReportApiController.php
<?php namespace App\Controller\Api; use App\Entity\Report; use App\Entity\ReportItem; use App\Entity\User; use App\Enum\ReportStatusType; use App\Enum\ReportType; use App\Repository\ReportItemRepository; use App\Repository\ReportRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\ExpressionLanguage\Expression; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Http\Attribute\IsGranted; use Symfony\Component\Serializer\SerializerInterface; #[IsGranted(new Expression('is_granted("ROLE_AGENT") or is_granted("ROLE_MANAGER")'))] #[Route(path: '/api/report', name: 'api_report_')] class ReportApiController extends AbstractApiController { public function __construct( protected EntityManagerInterface $em ) { parent::__construct($em); } #[Route(path: '', name: 'add', methods: ['POST'])] public function report( Request $request, SerializerInterface $serializer, ReportRepository $reportRepository ): JsonResponse { $body = $request->getContent(); $currentUser = $this->getUser(); if (!$currentUser instanceof User) { throw new \UnexpectedValueException('Current user is not valid, cannot create report.'); } /** @var Report $data */ $data = $serializer->deserialize($body, Report::class, 'json'); if (ReportType::INCIVILITY === $data->getType()) { $data->setStatus(ReportStatusType::REPORT_STATUS_IN_PROGRESS); } // Fetch relations from Doctrine $item = $this->em->find(ReportItem::class, $data->getReportItem()->getId()); $data->setReportItem($item); $data->setAgent($currentUser); $data->setManager($currentUser->getManager() ?? $currentUser); $reportRepository->save($data, true); return $this->response($data, 'show_report'); } #[Route(path: '/{id}', name: 'get', requirements: ['id' => '\d+'], methods: ['GET'])] public function getAction(Report $report): JsonResponse { return $this->response($report, 'show_report'); } #[Route(path: '/items/{type}', name: 'items_from_type', methods: ['GET'])] public function getItemsFromTypesAction(ReportType $type, ReportItemRepository $reportItemRepository): JsonResponse { $items = $reportItemRepository->findBy(['type' => $type]); return $this->response($items, 'show_report_item'); } }
Save File
Cancel