Lines 77.77% 7 / 9
Functions and Methods 50.00% 1 / 2
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AgentStatService 77.77% 7 / 9 50.00% 1 / 2 4.18 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 create 75.00% 6 / 8 0.00% 0 / 1 3.14
1<?php
2
3declare(strict_types=1);
4
5namespace App\Service;
6
7use App\Dto\AgentStatInput;
8use App\Entity\AgentStat;
9use App\Entity\User;
10use App\Exception\StatsAlreadyAddedException;
11use App\Repository\AgentStatRepository;
12use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
13use Doctrine\ORM\EntityManagerInterface;
14
15class AgentStatService
16{
17    public function __construct(
18        private readonly EntityManagerInterface $entityManager,
19        private readonly AgentStatRepository $agentStatRepository,
20    ) {
21    }
22
23    /**
24     * @throws StatsAlreadyAddedException if the owner already imported stats with this datetime
25     */
26    public function create(User $owner, AgentStatInput $input): AgentStat
27    {
28        $agentStat = new AgentStat($owner, $input);
29
30        if ($this->agentStatRepository->has($owner, $agentStat->datetime)) {
31            throw new StatsAlreadyAddedException('Stat entry already added!');
32        }
33
34        $this->entityManager->persist($agentStat);
35
36        try {
37            $this->entityManager->flush();
38        } catch (UniqueConstraintViolationException $uniqueConstraintViolationException) {
39            // Same stats sent twice at the same moment
40            throw new StatsAlreadyAddedException('Stat entry already added!', $uniqueConstraintViolationException->getCode(), previous: $uniqueConstraintViolationException);
41        }
42
43        return $agentStat;
44    }
45}