|
11 | 11 | use App\Entity\Tenant\Playlist; |
12 | 12 | use App\Entity\Tenant\PlaylistScreenRegion; |
13 | 13 | use App\Entity\Tenant\Screen; |
| 14 | +use App\Entity\Tenant\ScreenGroup; |
14 | 15 | use App\Repository\PlaylistRepository; |
15 | 16 | use App\Repository\PlaylistScreenRegionRepository; |
16 | 17 | use App\Repository\ScreenGroupRepository; |
@@ -125,16 +126,48 @@ protected function fromInput(mixed $object, Operation $operation, array $uriVari |
125 | 126 | } |
126 | 127 | } |
127 | 128 |
|
| 129 | + // Maps ids of existing groups |
128 | 130 | 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) { |
132 | 150 | $groupToSave = $this->groupRepository->findOneBy(['id' => $group]); |
| 151 | + |
133 | 152 | if (is_null($groupToSave)) { |
134 | 153 | throw new InvalidArgumentException('Unknown group resource'); |
135 | 154 | } |
| 155 | + |
136 | 156 | $screen->addScreenGroup($groupToSave); |
137 | 157 | } |
| 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 | + } |
138 | 171 | } |
139 | 172 |
|
140 | 173 | if (!empty($object->layout)) { |
|
0 commit comments