Lines 100.00% 19 / 19
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Create 100.00% 19 / 19 100.00% 2 / 2 10 100.00% 1 / 1
 __invoke 100.00% 10 / 10 100.00% 1 / 1 5
 import 100.00% 9 / 9 100.00% 1 / 1 5
1<?php
2
3declare(strict_types=1);
4
5namespace App\Controller\AgentStat;
6
7use App\Controller\BaseController;
8use App\Entity\AgentStat;
9use App\Enum\UserRole;
10use App\Exception\InvalidStatsException;
11use App\Exception\StatsAlreadyAddedException;
12use App\Form\AgentStatImportType;
13use App\Service\AgentStatService;
14use App\Service\IngressStatsParser;
15use Symfony\Component\Form\FormError;
16use Symfony\Component\Form\FormInterface;
17use Symfony\Component\HttpFoundation\Request;
18use Symfony\Component\HttpFoundation\Response;
19use Symfony\Component\Routing\Attribute\Route;
20use Symfony\Component\Security\Http\Attribute\IsGranted;
21
22#[Route('/agent-stats/new', name: 'app_agent_stat_new', methods: ['GET', 'POST'])]
23#[IsGranted(UserRole::USER->value)]
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}