Lines 80.25% 309 / 385
Methods 75.00% 48 / 64
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 toProcessListByTime 100.00% 8 / 8 100.00% 1 / 1 4
 withRequest 100.00% 5 / 5 100.00% 1 / 1 3
 sortByScopeName 0.00% 0 / 7 0.00% 0 / 1 2
 sortByAppointmentDate 100.00% 4 / 4 100.00% 1 / 1 1
 sortByArrivalTime 0.00% 0 / 4 0.00% 0 / 1 2
 sortByEstimatedWaitingTime 100.00% 4 / 4 100.00% 1 / 1 1
 sortByClientName 100.00% 7 / 7 100.00% 1 / 1 1
 sortByTimeKey 100.00% 4 / 4 100.00% 1 / 1 1
 toProcessListByStatusList 0.00% 0 / 5 0.00% 0 / 1 12
 toConflictListByDay 95.23% 20 / 21 0.00% 0 / 1 5
 getScopeList 100.00% 5 / 5 100.00% 1 / 1 3
 getRequestList 100.00% 5 / 5 100.00% 1 / 1 3
 getAppointmentList 100.00% 6 / 6 100.00% 1 / 1 4
 setTempAppointmentToProcess 100.00% 12 / 12 100.00% 1 / 1 5
 toQueueList 100.00% 6 / 6 100.00% 1 / 1 2
 withAvailability 100.00% 5 / 5 100.00% 1 / 1 3
 withAvailabilityStrict 100.00% 6 / 6 100.00% 1 / 1 3
 withDepartmentHasMailFrom 0.00% 0 / 6 0.00% 0 / 1 12
 setConflictAmendment 100.00% 8 / 8 100.00% 1 / 1 3
 withOutAvailability 100.00% 1 / 1 100.00% 1 / 1 1
 getCalculatedSlotCountByAvailability 100.00% 1 / 1 100.00% 1 / 1 1
 getAvailabilitySlotUsage 100.00% 44 / 44 100.00% 1 / 1 14
 getAppointmentSlotOptions 100.00% 6 / 6 100.00% 1 / 1 3
 selectAppointmentSlots 100.00% 14 / 14 100.00% 1 / 1 4
 preferredSlotKey 100.00% 1 / 1 100.00% 1 / 1 3
 withUniqueScope 100.00% 11 / 11 100.00% 1 / 1 4
 withAccess 0.00% 0 / 6 0.00% 0 / 1 12
 withScopeId 100.00% 5 / 5 100.00% 1 / 1 3
 withOutScopeId 100.00% 5 / 5 100.00% 1 / 1 3
 withOutProcessId 100.00% 5 / 5 100.00% 1 / 1 3
 withoutExpiredAppointmentDate 0.00% 0 / 5 0.00% 0 / 1 12
 withinExactDate 0.00% 0 / 5 0.00% 0 / 1 12
 withoutDublicatedConflicts 0.00% 0 / 5 0.00% 0 / 1 12
 testProcessListLength 100.00% 7 / 7 100.00% 1 / 1 4
 withoutProcessByStatus 100.00% 5 / 5 100.00% 1 / 1 3
 withTimeRangeByAppointment 0.00% 0 / 7 0.00% 0 / 1 30
 [BO\Zmsentities\Collection\Base] __construct 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] getFirst 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] getLast 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] sortByName 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] sortByContactName 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] sortByCustomKey 100.00% 4 / 4 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] sortByCustomStringKey 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] __clone 100.00% 2 / 2 100.00% 1 / 1 2
 [BO\Zmsentities\Collection\Base] hasEntity 100.00% 4 / 4 100.00% 1 / 1 4
 [BO\Zmsentities\Collection\Base] getEntity 100.00% 4 / 4 100.00% 1 / 1 4
 [BO\Zmsentities\Collection\Base] addEntity 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] offsetSet 100.00% 9 / 9 100.00% 1 / 1 3
 [BO\Zmsentities\Collection\Base] addData 91.66% 11 / 12 0.00% 0 / 1 5.01
 [BO\Zmsentities\Collection\Base] addList 100.00% 3 / 3 100.00% 1 / 1 2
 [BO\Zmsentities\Collection\Base] getIds 100.00% 4 / 4 100.00% 1 / 1 2
 [BO\Zmsentities\Collection\Base] getIdsCsv 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] getCsvForProperty 0.00% 0 / 5 0.00% 0 / 1 12
 [BO\Zmsentities\Collection\Base] getCsvForPropertyList 100.00% 11 / 11 100.00% 1 / 1 6
 [BO\Zmsentities\Collection\Base] withValueFor 0.00% 0 / 4 0.00% 0 / 1 6
 [BO\Zmsentities\Collection\Base] withLessData 100.00% 4 / 4 100.00% 1 / 1 2
 [BO\Zmsentities\Collection\Base] setJsonCompressLevel 0.00% 0 / 2 0.00% 0 / 1 6
 [BO\Zmsentities\Collection\Base] getAsArray 0.00% 0 / 4 0.00% 0 / 1 6
 [BO\Zmsentities\Collection\Base] jsonSerialize 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] __toString 100.00% 4 / 4 100.00% 1 / 1 2
 [BO\Zmsentities\Collection\Base] getResolveLevel 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] setResolveLevel 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsentities\Collection\Base] withResolveLevel 100.00% 5 / 5 100.00% 1 / 1 2
 [BO\Zmsentities\Collection\Base] chunk 0.00% 0 / 9 0.00% 0 / 1 12
18class ProcessList extends Base
19{
20    public const string ENTITY_CLASS = '\BO\Zmsentities\Process';
21
22    private const int APPOINTMENT_SLOT_MINUTES = 5;
23
24    public function toProcessListByTime(string|null $format = null): self
25    {
26        $list = new self();
27        foreach ($this as $process) {
28            $appointment = $process->getFirstAppointment();
29            $formattedDate = $appointment['date'];
30            if ($format !== null && $format !== '') {
31                $formattedDate = $appointment->toDateTime()->format($format);
32            }
33            $list[$formattedDate][] = clone $process;
34        }
35        return $list;
36    }
37
38    public function withRequest(mixed $requestId): self
39    {
40        $list = new self();
41        foreach ($this as $process) {
42            if ($process->requests->hasEntity($requestId)) {
43                $list->addEntity(clone $process);
44            }
45        }
46        return $list;
47    }
48
49    public function sortByScopeName(): static
50    {
51        $this->uasort(function ($a, $b) {
52            return strcmp(
53                Sorter::toSortableString(ucfirst($a->scope['contact']['name'] ?? '')),
54                Sorter::toSortableString(ucfirst($b->scope['contact']['name'] ?? ''))
55            );
56        });
57        return $this;
58    }
59
60    public function sortByAppointmentDate(): static
61    {
62        $this->uasort(function ($a, $b) {
63            return ((int) $a->getFirstAppointment()->date - (int) $b->getFirstAppointment()->date);
64        });
65        return $this;
66    }
67
68    public function sortByArrivalTime(): static
69    {
70        $this->uasort(function ($a, $b): mixed {
71            return ($a->queue['arrivalTime'] - $b->queue['arrivalTime']);
72        });
73        return $this;
74    }
75
76    public function sortByEstimatedWaitingTime(): static
77    {
78        $this->uasort(function ($a, $b): mixed {
79            return ($a->queue['waitingTimeEstimate'] - $b->queue['waitingTimeEstimate']);
80        });
81        return $this;
82    }
83
84    public function sortByClientName(): static
85    {
86        $this->uasort(function ($a, $b) {
87            return strcmp(
88                Sorter::toSortableString($a->getFirstClient()['familyName']),
89                Sorter::toSortableString($b->getFirstClient()['familyName'])
90            );
91        });
92        return $this;
93    }
94
95    public function sortByTimeKey(): static
96    {
97        $this->uksort(function ($a, $b): mixed {
98            return ((int) $a - (int) $b);
99        });
100        return $this;
101    }
102
103    public function toProcessListByStatusList(array $statusList): self
104    {
105        $collection = new self();
106        foreach ($this as $process) {
107            if (in_array($process->getStatus(), $statusList)) {
108                $collection->addEntity($process);
109            }
110        }
111        return $collection;
112    }
113
114    /**
115     * @return ((mixed|null)[][]|mixed)[][][]
116     *
117     */
118    public function toConflictListByDay(): array
119    {
120        $list = [];
121        $oldList = clone $this;
122        foreach ($oldList as $process) {
123            $appointmentList = [];
124            if (!isset($list[$process->getFirstAppointment()->getStartTime()->format('Y-m-d')])) {
125                $list[$process->getFirstAppointment()->getStartTime()->format('Y-m-d')] = [];
126            }
127            foreach ($process->getAppointments() as $appointment) {
128                $availability = $appointment->getAvailability();
129                $availabilityId = $availability->getId()
130                    ? $availability->getId()
131                    : ($availability['tempId'] ?? null);
132                $appointmentList[] = [
133                    'startTime' => $appointment->getStartTime()->format('H:i'),
134                    'endTime' => $appointment->getEndTime()->format('H:i'),
135                    'availability' => $availabilityId
136                ];
137            }
138            $list[$process->getFirstAppointment()->getStartTime()->format('Y-m-d')][] = [
139                'message' => $process->amendment,
140                'appointments' => $appointmentList
141            ];
142        }
143        return $list;
144    }
145
146    public function getScopeList(): \BO\Zmsentities\Collection\ScopeList
147    {
148        $list = new ScopeList();
149        foreach ($this as $process) {
150            if (Property::__keyExists('scope', $process)) {
151                $list[] = new \BO\Zmsentities\Scope($process['scope']);
152            }
153        }
154        return $list->withUniqueScopes();
155    }
156
157    public function getRequestList(): \BO\Zmsentities\Collection\RequestList
158    {
159        $list = new RequestList();
160        foreach ($this as $process) {
161            if (Property::__keyExists('requests', $process)) {
162                $list->addList($process->getRequests());
163            }
164        }
165        return $list->withUniqueRequests();
166    }
167
168    public function getAppointmentList(): AppointmentList
169    {
170        $appointmentList = new AppointmentList();
171        foreach ($this as $process) {
172            if (Property::__keyExists('appointments', $process)) {
173                foreach ($process["appointments"] as $appointment) {
174                    $appointmentList->addEntity(new \BO\Zmsentities\Appointment($appointment));
175                }
176            }
177        }
178        return $appointmentList;
179    }
180
181    public function setTempAppointmentToProcess(mixed $dateTime, mixed $scopeId): static
182    {
183        $addedAppointment = false;
184        $appointment = (new \BO\Zmsentities\Appointment())->addDate($dateTime->getTimestamp())->addScope($scopeId);
185        foreach ($this as $process) {
186            if ($process->hasAppointment($dateTime->getTimestamp(), $scopeId) && !$addedAppointment) {
187                $entity = clone $process;
188                $this->addEntity($entity);
189                $addedAppointment = true;
190            }
191        }
192        if (!$addedAppointment) {
193            $entity = new \BO\Zmsentities\Process();
194            $entity->addAppointment($appointment);
195            $this->addEntity($entity);
196        }
197        return $this;
198    }
199
200    public function toQueueList(mixed $now): QueueList
201    {
202        $queueList = new QueueList();
203        foreach ($this as $process) {
204            $queue = $process->toQueue($now);
205            $queueList->addEntity($queue);
206        }
207        $queueList->setTransferedProcessList(true);
208        return $queueList;
209    }
210
211    public function withAvailability(\BO\Zmsentities\Availability $availability): static
212    {
213        $processList = new static();
214        foreach ($this as $process) {
215            if ($availability->hasAppointment($process->getFirstAppointment())) {
216                $processList[] = clone $process;
217            }
218        }
219        return $processList;
220    }
221
222    public function withAvailabilityStrict(\BO\Zmsentities\Availability $availability): static
223    {
224        $processList = new static();
225        $slotList = $availability->getSlotList();
226        foreach ($this as $process) {
227            if ($slotList->removeAppointment($process->getFirstAppointment())) {
228                $processList[] = clone $process;
229            }
230        }
231        return $processList;
232    }
233
234    public function withDepartmentHasMailFrom(): static
235    {
236        $processList = new static();
237        foreach ($this as $process) {
238            if ($process->getCurrentScope()->hasEmailFrom()) {
239                $entity = clone $process;
240                $processList->addEntity($entity);
241            }
242        }
243        return $processList;
244    }
245
246
247
248    public function setConflictAmendment(): static
249    {
250        foreach ($this as $process) {
251            $process->amendment = 'Die Slots für diesen Zeitraum wurden Ã¼berbucht';
252            if (! $process->getFirstAppointment()->availability->hasId()) {
253                $process->amendment = sprintf(
254                    'Der Vorgang (%s) befindet sich außerhalb der Ã–ffnungszeit!',
255                    $process->getId()
256                );
257            }
258        }
259        return $this;
260    }
261
262    public function withOutAvailability(AvailabilityList $availabilityList): static
263    {
264        return $this->getAvailabilitySlotUsage($availabilityList)['conflicts'];
265    }
266
267    /**
268     * @return array<int|string, int>
269     */
270    public function getCalculatedSlotCountByAvailability(AvailabilityList $availabilityList): array
271    {
272        return $this->getAvailabilitySlotUsage($availabilityList)['busySlots'];
273    }
274
275    /**
276     * Count booked five-minute steps per availability and report missing or full slots as conflicts.
277     * The graph tracks the booked interval even if some steps cannot be allocated.
278     * The graph passes one day; occupiedByTime totals matching clock times if given multiple days.
279     *
280     * @return array{busySlots: array<int|string, int>, occupiedByTime: array<string, int>, conflicts: static}
281     */
282    public function getAvailabilitySlotUsage(AvailabilityList $availabilityList): array
283    {
284        $busySlots = array_fill_keys(array_keys($availabilityList->getSortedByDuration()), 0);
285        $occupiedByTime = [];
286        $conflicts = new static();
287        foreach ($this->toProcessListByTime('Y-m-d') as $processListByDate) {
288            $dateTime = $processListByDate[0]->getFirstAppointment()->toDateTime();
289            $dayEnd = $dateTime->modify('tomorrow midnight');
290            $availabilities = $availabilityList->withType('appointment')->withDateTime($dateTime)->getSortedByDuration();
291            $slotsByTime = [];
292            foreach ($availabilities as $key => $availability) {
293                foreach ($availability->getSlotList() as $slot) {
294                    $slotsByTime[$slot->getTimeString()][$key] = $slot;
295                }
296            }
297            // Sweep booking starts and ends together with the graph's configured slot times.
298            $demandChanges = array_fill_keys(array_keys($slotsByTime), 0);
299            foreach ($processListByDate as $process) {
300                $appointment = $process->getFirstAppointment();
301                $bookedAvailability = $appointment->getAvailability();
302                $bookedKey = $bookedAvailability->id ?: ($bookedAvailability->tempId ?? null);
303                $start = $appointment->getStartTime();
304                $startClock = $start->format('H:i');
305                $slotCount = max(1, (int) $appointment->getSlotCount());
306                $end = $start->add(new \DateInterval('PT' . ($slotCount * self::APPOINTMENT_SLOT_MINUTES) . 'M'));
307                $endClock = $end < $dayEnd ? $end->format('H:i') : '24:00';
308                $demandChanges[$startClock] = ($demandChanges[$startClock] ?? 0) + 1;
309                $demandChanges[$endClock] = ($demandChanges[$endClock] ?? 0) - 1;
310
311                $options = static::getAppointmentSlotOptions($start, $slotCount, $dayEnd, $slotsByTime);
312                $hasConflict = count($options) !== $slotCount;
313                foreach (static::selectAppointmentSlots($options, $bookedKey) as $time => $key) {
314                    if ($key === null) {
315                        $hasConflict = true;
316                        continue;
317                    }
318                    $busySlots[$key] = ($busySlots[$key] ?? 0) + 1;
319                    $slot = $options[$time][$key];
320                    if ($slot->intern > 0) {
321                        $slot->removeAppointment();
322                    } else {
323                        $hasConflict = true;
324                    }
325                }
326                if ($hasConflict) {
327                    $process->amendment = '';
328                    $conflicts[] = $process;
329                }
330            }
331            ksort($demandChanges);
332            $demand = 0;
333            foreach ($demandChanges as $time => $change) {
334                $demand += $change;
335                if ($demand > 0 && isset($slotsByTime[$time])) {
336                    $occupiedByTime[$time] = ($occupiedByTime[$time] ?? 0) + $demand;
337                }
338            }
339        }
340        return ['busySlots' => $busySlots, 'occupiedByTime' => $occupiedByTime, 'conflicts' => $conflicts];
341    }
342
343    /**
344     * @param array<string, array<int|string, Slot>> $slotsByTime
345     * @return array<string, array<int|string, Slot>> candidates for each required slot time
346     */
347    protected static function getAppointmentSlotOptions(
348        \DateTimeImmutable $start,
349        int $slotCount,
350        \DateTimeImmutable $dayEnd,
351        array $slotsByTime
352    ): array {
353        $interval = new \DateInterval('PT' . self::APPOINTMENT_SLOT_MINUTES . 'M');
354        $options = [];
355        for ($step = 0, $time = $start; $step < $slotCount && $time < $dayEnd; $step++, $time = $time->add($interval)) {
356            $clock = $time->format('H:i');
357            $options[$clock] = $slotsByTime[$clock] ?? [];
358        }
359        return $options;
360    }
361
362    /**
363     * Prefer a single availability for the whole booking, then choose a slot at each required time.
364     * Keep full slots in the result so they still count toward the availability's booked total.
365     *
366     * @param array<string, array<int|string, Slot>> $options
367     * @return array<string, int|string|null> availability by slot time, null for a missing slot
368     */
369    protected static function selectAppointmentSlots(array $options, int|string|null $bookedKey): array
370    {
371        $covering = $freeEverywhere = reset($options) ?: [];
372        $free = [];
373        foreach ($options as $time => $slots) {
374            $free[$time] = array_filter($slots, static fn (Slot $slot) => $slot->intern > 0);
375            $freeEverywhere = array_intersect_key($freeEverywhere, $free[$time]);
376            $covering = array_intersect_key($covering, $slots);
377        }
378        $previousKey = static::preferredSlotKey($freeEverywhere, $bookedKey) ?? $bookedKey;
379        $coveringKey = static::preferredSlotKey($covering, $bookedKey);
380        $selected = [];
381        foreach ($options as $time => $slots) {
382            $selected[$time] = static::preferredSlotKey($free[$time], $previousKey)
383                ?? static::preferredSlotKey($slots, $coveringKey ?? $previousKey);
384            $previousKey = $selected[$time] ?? $previousKey;
385        }
386        return $selected;
387    }
388
389    /** @param array<int|string, Slot> $slots */
390    protected static function preferredSlotKey(array $slots, int|string|null $preferred): int|string|null
391    {
392        return ($preferred !== null && isset($slots[$preferred])) ? $preferred : array_key_first($slots);
393    }
394
395    public function withUniqueScope(bool $oncePerHour = false): static
396    {
397        $processList = new static();
398        $scopeKeyList = [];
399        foreach ($this as $process) {
400            $scopeKey = $process->scope['id'] . '-';
401            if ($oncePerHour) {
402                $scopeKey .= $process->getFirstAppointment()->toDateTime()->format('H');
403            } else {
404                $scopeKey .= $process->getFirstAppointment()->toDateTime()->format('H:i');
405            }
406            if (!in_array($scopeKey, $scopeKeyList)) {
407                $processList[] = clone $process;
408                $scopeKeyList[] = $scopeKey;
409            }
410        }
411        return $processList;
412    }
413
414    public function withAccess(\BO\Zmsentities\Useraccount $useraccount): static
415    {
416        $list = new static();
417        foreach ($this as $process) {
418            $process = clone $process;
419            if ($process->getCurrentScope()->hasAccess($useraccount)) {
420                $list[] = $process;
421            }
422        }
423        return $list;
424    }
425
426    /** @psalm-api */
427    public function withScopeId(int|string $scopeId): static
428    {
429        $processList = new static();
430        foreach ($this as $process) {
431            if ($scopeId == $process->getScopeId()) {
432                $processList[] = clone $process;
433            }
434        }
435        return $processList;
436    }
437
438    /** @psalm-api */
439    public function withOutScopeId(int|string $scopeId): static
440    {
441        $processList = new static();
442        foreach ($this as $process) {
443            if ($scopeId != $process->getScopeId()) {
444                $processList[] = clone $process;
445            }
446        }
447        return $processList;
448    }
449
450    public function withOutProcessId(mixed $processId): static
451    {
452        $processList = new static();
453        foreach ($this as $process) {
454            if ($processId != $process->getId()) {
455                $processList[] = clone $process;
456            }
457        }
458        return $processList;
459    }
460
461    public function withoutExpiredAppointmentDate(\DateTimeInterface $now): self
462    {
463        $conflictList = new self();
464        foreach ($this as $process) {
465            if ($process->getFirstAppointment()->date > $now->getTimestamp()) {
466                $conflictList->addEntity(clone $process);
467            }
468        }
469        return $conflictList;
470    }
471
472    public function withinExactDate(\DateTimeInterface $now): self
473    {
474        $processList = new self();
475        foreach ($this as $process) {
476            if ($process->getFirstAppointment()->toDateTime()->format('Y-m-d') == $now->format('Y-m-d')) {
477                $processList->addEntity(clone $process);
478            }
479        }
480        return $processList;
481    }
482
483    public function withoutDublicatedConflicts(): self
484    {
485        $collection = new self();
486        foreach ($this as $conflict) {
487            if (! $collection->getAppointmentList()->hasAppointment($conflict->getFirstAppointment())) {
488                $collection->addEntity(clone $conflict);
489            }
490        }
491        return $collection;
492    }
493
494    /**
495     * @param Process|self $processList
496     */
497    public function testProcessListLength(self|Process $processList, bool $isEmptyAllowed = false): ProcessList
498    {
499        if ($processList instanceof Process) {
500            $collection = new self();
501            $collection->addEntity($processList);
502        } else {
503            $collection = $processList;
504        }
505
506        if (0 === $collection->count() && ! $isEmptyAllowed) {
507            throw new \BO\Zmsentities\Exception\ProcessListEmpty();
508        }
509        return $collection;
510    }
511
512    public function withoutProcessByStatus(Process $process, string $status): static
513    {
514        $collection = clone $this;
515        $collection = (1 <= $collection->count() && ! Messaging::isEmptyProcessListAllowed($status)) ?
516            $collection->withOutProcessId($process->getId()) :
517            $collection;
518        return $collection;
519    }
520
521    /*
522    * reduce process list to items with appointment time in range of given appointment
523    */
524    public function withTimeRangeByAppointment(\BO\Zmsentities\Appointment $appointment): self
525    {
526        $processList = new self();
527        if ($this->count()) {
528            foreach ($this as $process) {
529                if (
530                    $appointment->getEndTime() > $process->getFirstAppointment()->getStartTime() &&
531                    $appointment->getStartTime() < $process->getFirstAppointment()->getEndTime()
532                ) {
533                    $processList->addEntity(clone $process);
534                }
535            }
536        }
537        return $processList;
538    }
539}

Inherited from BO\Zmsentities\Collection\Base

32    public function __construct(object|array $array = [], int $flags = 0, string $iteratorClass = "ArrayIterator")
33    {
34        /** @var class-string<\ArrayIterator> $iteratorClass */
35        parent::__construct($array, $flags, $iteratorClass);
36    }
41    public function getFirst()
42    {
43        $item = $this->getIterator()->current();
44        return $item;
45    }
51    public function getLast()
52    {
53        $copy = $this->getArrayCopy();
54        $item = end($copy);
55        return $item;
56    }
62    public function sortByName()
63    {
64        $this->uasort(function ($a, $b) {
65            return strcmp(
66                Sorter::toSortableString(ucfirst($a->name ?? '')),
67                Sorter::toSortableString(ucfirst($b->name ?? ''))
68            );
69        });
70        return $this;
71    }
73    public function sortByContactName(): static
74    {
75        $this->uasort(function ($a, $b) {
76            return strcmp(
77                Sorter::toSortableString(ucfirst($a->contact['name'] ?? '')),
78                Sorter::toSortableString(ucfirst($b->contact['name'] ?? ''))
79            );
80        });
81        return $this;
82    }
84    public function sortByCustomKey(string $key): static
85    {
86        $this->uasort(function ($a, $b) use ($key): mixed {
87            return ($a[$key] - $b[$key]);
88        });
89        return $this;
90    }
92    public function sortByCustomStringKey(mixed $key): static
93    {
94        $this->uasort(function ($a, $b) use ($key) {
95            return strcmp(
96                Sorter::toSortableString(ucfirst($a[$key] ?? '')),
97                Sorter::toSortableString(ucfirst($b[$key] ?? ''))
98            );
99        });
100        return $this;
101    }
103    public function __clone()
104    {
105        foreach ($this as $key => $property) {
106            $this[$key] = clone $property;
107        }
108    }
110    public function hasEntity(mixed $primary): bool
111    {
112        foreach ($this as $entity) {
113            if (isset($entity->{$entity::PRIMARY}) && $primary == $entity->{$entity::PRIMARY}) {
114                return true;
115            }
116        }
117        return false;
118    }
124    public function getEntity(string|int $primary)
125    {
126        foreach ($this as $entity) {
127            if (isset($entity->{$entity::PRIMARY}) && $primary == $entity->{$entity::PRIMARY}) {
128                return $entity;
129            }
130        }
131        return null;
132    }
134    public function addEntity(\BO\Zmsentities\Schema\Entity $entity): static
135    {
136        /** @var T $entity */
137        $this->append($entity);
138        return $this;
139    }
146    public function offsetSet(mixed $index, mixed $value): void
147    {
148        $className = $this::ENTITY_CLASS;
149        if (is_a($value, $className)) {
150            /** @var T $entity */
151            $entity = $value;
152            /** @psalm-suppress PossiblyNullArgument */
153            parent::offsetSet($index, $entity);
154        } elseif (is_array($value)) {
155            /** @var T $entity */
156            $entity = new $className($value);
157            /** @psalm-suppress PossiblyNullArgument */
158            parent::offsetSet($index, $entity);
159        } else {
160            $given = get_debug_type($value);
161            throw new \Exception('Invalid entity ' . $given . ' for collection ' . __CLASS__);
162        }
163    }
165    public function addData(mixed $mergeData): static
166    {
167        foreach ($mergeData as $item) {
168            if ($item instanceof Entity) {
169                if (null === $item->getResolveLevel()) {
170                    $item->setResolveLevel($this->getResolveLevel());
171                }
172                $this->addEntity($item);
173            } else {
174                $className = $this::ENTITY_CLASS;
175                $entity = new $className($item);
176                if (!$entity instanceof Entity) {
177                    throw new \Exception('Invalid entity ' . get_debug_type($entity) . ' for collection ' . __CLASS__);
178                }
179                $entity->setResolveLevel($this->getResolveLevel());
180                $this->addEntity($entity);
181            }
182        }
183        return $this;
184    }
189    public function addList(Base $list): static
190    {
191        foreach ($list as $item) {
192            $this->addEntity($item);
193        }
194        return $this;
195    }
201    public function getIds()
202    {
203        $list = [];
204        foreach ($this as $entity) {
205            $list[] = $entity->id;
206        }
207        return $list;
208    }
210    public function getIdsCsv(): string
211    {
212        return implode(',', $this->getIds());
213    }
215    public function getCsvForProperty(mixed $propertyName, string $csvSeperator = ','): string
216    {
217        $list = [];
218        foreach ($this as $entry) {
219            if ($entry->hasProperty($propertyName)) {
220                $list[] = $entry->getProperty($propertyName);
221            }
222        }
223        return implode($csvSeperator, $list);
224    }
226    public function getCsvForPropertyList(array $propertyList, string $propertySeperator = '', string $csvSeperator = ','): string
227    {
228        $list = [];
229        foreach ($this as $entry) {
230            $propertyConcat = '';
231            foreach ($propertyList as $propertyName) {
232                if ($entry->hasProperty($propertyName)) {
233                    if ($propertyConcat) {
234                        $propertyConcat .= $propertySeperator;
235                    }
236                    $propertyConcat .= $entry->getProperty($propertyName);
237                }
238            }
239            if ($propertyConcat) {
240                $list[] = $propertyConcat;
241            }
242        }
243        return implode($csvSeperator, $list);
244    }
250    public function withValueFor(mixed $param, mixed $newValue): static
251    {
252        /** @psalm-suppress UnsafeGenericInstantiation */
253        $list = new static();
254        foreach ($this as $entry) {
255            $list[] = $entry->withProperty($param, $newValue);
256        }
257        return $list;
258    }
266    public function withLessData(array $keepArray = [])
267    {
268        /** @psalm-suppress UnsafeGenericInstantiation */
269        $list = new static();
270        foreach ($this as $key => $item) {
271            /** @psalm-suppress TooManyArguments */
272            $list[$key] = $item->withLessData($keepArray);
273        }
274        return $list;
275    }
277    public function setJsonCompressLevel(mixed $jsonCompressLevel): void
278    {
279        foreach ($this as $item) {
280            $item->setJsonCompressLevel($jsonCompressLevel);
281        }
282    }
288    public function getAsArray(): array
289    {
290        $array = [];
291        foreach ($this as $item) {
292            $array[] = $item;
293        }
294
295        return $array;
296    }
299    public function jsonSerialize(): mixed
300    {
301        return $this->getArrayCopy();
302    }
304    public function __toString()
305    {
306        $list = [];
307        foreach ($this as $item) {
308            $list[] = $item->__toString();
309        }
310        return "[" . implode(',', $list) . "]";
311    }
316    public function getResolveLevel()
317    {
318        return $this->resolveLevel;
319    }
325    public function setResolveLevel($resolveLevel)
326    {
327        $this->resolveLevel = $resolveLevel;
328        return $this;
329    }
335    public function withResolveLevel($resolveLevel)
336    {
337        /** @psalm-suppress UnsafeGenericInstantiation */
338        $collection = new static();
339        foreach ($this as $entity) {
340            $reduced = $entity->withResolveLevel($resolveLevel);
341            $collection[] = $reduced;
342        }
343        return $collection;
344    }
350    public function chunk(mixed $length): array
351    {
352        /** @psalm-suppress UnsafeGenericInstantiation */
353        $chunks = [new static()];
354        $id = 0;
355        foreach ($this as $entry) {
356            $chunkIndex = (int) floor($id / $length);
357            if (! isset($chunks[$chunkIndex])) {
358                /** @psalm-suppress UnsafeGenericInstantiation */
359                $chunks[$chunkIndex] = new static();
360            }
361
362            $chunks[$chunkIndex][] = $entry;
363
364            $id++;
365        }
366
367        return $chunks;
368    }