<?php
namespace App\Controller\External;
use App\Entity\Report;
use App\Form\NewReportFormType;
use App\Message\Report as ReportMessage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
class WebImpactCalculatorController extends AbstractController
{
/**
* @Route("/web-impact-calculator", name="app_web_impact_calculator", priority="10")
*/
public function index(): Response
{
if ($this->isGranted('ROLE_USER')) {
return $this->redirectToRoute('app_user_dashboard');
}
return $this->redirectToRoute('app_index');
}
/**
* @Route("/web-impact-calculator/estimate/{hash}/waiting", name="app_web_impact_calculator_estimate_waiting")
*/
public function waiting(Report $report): Response
{
return $this->render(
'external/web_impact_calculator/waiting.html.twig', [
'report' => $report,
]
);
}
/**
* @Route("/web-impact-calculator/estimate/new", name="app_web_impact_calculator_estimate_new")
*/
public function new(Request $request, EntityManagerInterface $entityManager, MessageBusInterface $bus): Response
{
$report = new Report();
$form = $this->createForm(NewReportFormType::class, $report);
if ($formData = $request->get('new_report_form')) {
$form->submit($formData);
} else {
$form->handleRequest($request);
}
if ($form->isSubmitted() && $form->isValid()) {
$existingAnonymousReport = $entityManager->getRepository(Report::class)->findOneBy(
[
'user' => null,
'domain' => $report->getDomain(),
]
);
if (null !== $existingAnonymousReport) {
$report = $existingAnonymousReport;
} else {
$entityManager->persist($report);
$entityManager->flush();
}
$bus->dispatch(
new ReportMessage(
$report->getId()
)
);
return $this->redirectToRoute('app_web_impact_calculator_estimate_waiting', [
'hash' => $report->getHash(),
]);
}
$formErrors = [];
/** @var FormError $error */
foreach ($form->getErrors(true) as $error) {
$formErrors[] = $error->getMessage();
}
$this->addFlash('error', implode(',', $formErrors));
return $this->redirectToRoute('app_web_impact_calculator');
}
}