Lines 100.00% 19 / 19
Methods 100.00% 2 / 2
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __invoke 100.00% 10 / 10 100.00% 1 / 1 5
 import 100.00% 9 / 9 100.00% 1 / 1 5
24final class Create extends BaseController
25{
26    public function __invoke(
27        Request $request,
28        IngressStatsParser $parser,
29        AgentStatService $agentStatService,
30    ): Response {
31        $form = $this->createForm(AgentStatImportType::class);
32        $form->handleRequest($request);
33
34        if ($form->isSubmitted() && $form->isValid()) {
35            $agentStat = $this->import($form, $parser, $agentStatService);
36
37            if ($agentStat instanceof AgentStat) {
38                $this->addFlash('success', 'Agent stats have been imported.');
39
40                return $this->redirectToRoute('app_agent_stat_show', ['id' => $agentStat->id], Response::HTTP_SEE_OTHER);
41            }
42        }
43
44        return $this->render('agent_stat/new.html.twig', [
45            'form' => $form,
46        ], new Response(status: $form->isSubmitted() ? Response::HTTP_UNPROCESSABLE_ENTITY : Response::HTTP_OK));
47    }
48
49    /**
50     * Imports the pasted stats; on failure adds the errors to the form and returns null.
51     *
52     * @param FormInterface<mixed> $form
53     */
54    private function import(FormInterface $form, IngressStatsParser $parser, AgentStatService $agentStatService): ?AgentStat
55    {
56        $stats = $form->get('stats')->getData();
57
58        try {
59            return $agentStatService->create($this->getUser(), $parser->parse(\is_string($stats) ? $stats : ''));
60        } catch (InvalidStatsException $invalidStatsException) {
61            $errors = $invalidStatsException->errors;
62        } catch (StatsAlreadyAddedException $statsAlreadyAddedException) {
63            $errors = [$statsAlreadyAddedException->getMessage()];
64        }
65
66        foreach ($errors as $error) {
67            $form->get('stats')->addError(new FormError($error));
68        }
69
70        return null;
71    }
72}