Skip to content

Commit e1fa07e

Browse files
author
Sine Jespersen
committed
2314: avoid deleting all groups and readding
1 parent 2caf3a8 commit e1fa07e

File tree

1 file changed

+36
-3
lines changed

1 file changed

+36
-3
lines changed

src/State/ScreenProcessor.php

Lines changed: 36 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use App\Entity\Tenant\Playlist;
1212
use App\Entity\Tenant\PlaylistScreenRegion;
1313
use App\Entity\Tenant\Screen;
14+
use App\Entity\Tenant\ScreenGroup;
1415
use App\Repository\PlaylistRepository;
1516
use App\Repository\PlaylistScreenRegionRepository;
1617
use App\Repository\ScreenGroupRepository;
@@ -125,16 +126,48 @@ protected function fromInput(mixed $object, Operation $operation, array $uriVari
125126
}
126127
}
127128

129+
// Maps ids of existing groups
128130
if (isset($object->groups) && isset($screen)) {
129-
$screen->removeAllScreenGroup();
130-
131-
foreach ($object->groups as $group) {
131+
$existingGroups = array_map(function ($group) {
132+
if (!is_null($group)) {
133+
return $group->getId();
134+
}
135+
}, iterator_to_array($screen->getScreenGroups()));
136+
137+
// Ids of groups inputted
138+
$newGroupsId = array_map(
139+
/**
140+
* @param string $group
141+
*
142+
* @return Ulid
143+
*/
144+
fn ($group): Ulid => Ulid::fromString($group), $object->groups);
145+
146+
// This diff finds the groups to be saved
147+
$newGroups = array_diff($newGroupsId, $existingGroups);
148+
// ... and saves them.
149+
foreach ($newGroups as $group) {
132150
$groupToSave = $this->groupRepository->findOneBy(['id' => $group]);
151+
133152
if (is_null($groupToSave)) {
134153
throw new InvalidArgumentException('Unknown group resource');
135154
}
155+
136156
$screen->addScreenGroup($groupToSave);
137157
}
158+
159+
// This diff finds the groups to be deleted
160+
$deleteGroups = array_diff($existingGroups, $newGroupsId);
161+
// ... and deletes them.
162+
foreach ($deleteGroups as $group) {
163+
$groupToDelete = $this->groupRepository->findOneBy(['id' => $group]);
164+
165+
if (is_null($groupToDelete)) {
166+
throw new InvalidArgumentException('Unknown group resource');
167+
}
168+
169+
$screen->removeScreenGroup($groupToDelete);
170+
}
138171
}
139172

140173
if (!empty($object->layout)) {

0 commit comments

Comments
 (0)