Lines 100.00% 22 / 22
Methods 100.00% 3 / 3
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 replace 100.00% 13 / 13 100.00% 1 / 1 5
 update 100.00% 8 / 8 100.00% 1 / 1 5
17final readonly class DoneBannerSync
18{
19    public function __construct(
20        private DoneBannerRepository $doneBannerRepository,
21        private EntityManagerInterface $entityManager,
22    ) {
23    }
24
25    /**
26     * @param list<array{id: string, title: string, missions: int, picture?: string|null, startLatitude?: float|int|null, startLongitude?: float|int|null, eventStartDate?: string|null}> $banners newest first
27     */
28    public function replace(User $user, array $banners): void
29    {
30        $stored = [];
31        foreach ($this->doneBannerRepository->findByOwner($user) as $banner) {
32            $stored[$banner->bannerId] = $banner;
33        }
34
35        foreach ($banners as $position => $synced) {
36            $banner = $stored[$synced['id']] ?? new DoneBanner();
37            unset($stored[$synced['id']]);
38            if (null === $banner->id) {
39                $banner->owner = $user;
40                $banner->bannerId = $synced['id'];
41                $this->entityManager->persist($banner);
42            }
43
44            $this->update($banner, $synced, $position);
45        }
46
47        foreach ($stored as $banner) {
48            $this->entityManager->remove($banner);
49        }
50    }
51
52    /**
53     * @param array{id: string, title: string, missions: int, picture?: string|null, startLatitude?: float|int|null, startLongitude?: float|int|null, eventStartDate?: string|null} $synced
54     */
55    private function update(DoneBanner $banner, array $synced, int $position): void
56    {
57        $banner->title = $synced['title'];
58        $banner->missions = $synced['missions'];
59        $banner->picture = $synced['picture'] ?? null;
60        $banner->startLatitude = isset($synced['startLatitude']) ? (float) $synced['startLatitude'] : null;
61        $banner->startLongitude = isset($synced['startLongitude']) ? (float) $synced['startLongitude'] : null;
62        $banner->position = $position;
63        if (!$banner->doneAt instanceof \DateTimeImmutable && isset($synced['eventStartDate'])) {
64            $banner->doneAt = new \DateTimeImmutable($synced['eventStartDate']);
65        }
66    }
67}