Lines 89.02% 819 / 920
Methods 72.61% 61 / 84
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 prepareCalendarAndDays 100.00% 4 / 4 100.00% 1 / 1 1
 buildDaysList 100.00% 8 / 8 100.00% 1 / 1 3
 buildDaysListFromCalendarDays 75.00% 9 / 12 0.00% 0 / 1 6.56
 readMinimalFreeProcessesFromCalendar 94.11% 16 / 17 0.00% 0 / 1 4.00
 getProcessDataHandle 100.00% 17 / 17 100.00% 1 / 1 6
 readFreeProcesses 100.00% 11 / 11 100.00% 1 / 1 1
 readPreparedFreeProcesses 100.00% 25 / 25 100.00% 1 / 1 3
 readFreeProcessesMinimalDeduplicated 0.00% 0 / 10 0.00% 0 / 1 12
 deduplicateWithRoundRobin 100.00% 29 / 29 100.00% 1 / 1 4
 uniqueCandidatesSortedByScopeId 90.00% 9 / 10 0.00% 0 / 1 2.00
 resolveRoundRobinGroupKey 100.00% 5 / 5 100.00% 1 / 1 3
 pickRoundRobinIndex 66.66% 2 / 3 0.00% 0 / 1 2.15
 extractProcessInfo 81.48% 22 / 27 0.00% 0 / 1 10.64
 createMinimalProcess 100.00% 24 / 24 100.00% 1 / 1 1
 readReservedProcesses 100.00% 15 / 15 100.00% 1 / 1 4
 writeEntityReserved 70.58% 12 / 17 0.00% 0 / 1 4.41
 writeEntityReservedAttempt 98.24% 56 / 57 0.00% 0 / 1 8
 resetWriteTransactionAfterDeadlock 0.00% 0 / 9 0.00% 0 / 1 20
 [BO\Zmsbackend\Process\Service\Process] readEntity 100.00% 11 / 11 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] readById 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readResolvedReferences 100.00% 7 / 7 100.00% 1 / 1 3
 [BO\Zmsbackend\Process\Service\Process] updateEntity 100.00% 16 / 16 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] updateEntityDisplayNumber 0.00% 0 / 9 0.00% 0 / 1 6
 [BO\Zmsbackend\Process\Service\Process] updateEntityWithSlots 90.00% 18 / 20 0.00% 0 / 1 6.04
 [BO\Zmsbackend\Process\Service\Process] redirectToScope 0.00% 0 / 15 0.00% 0 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readSlotCount 100.00% 11 / 11 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] writeEntityWithNewAppointment 100.00% 20 / 20 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] updateFollowingProcesses 53.84% 7 / 13 0.00% 0 / 1 5.57
 [BO\Zmsbackend\Process\Service\Process] updateReassignedRequests 100.00% 4 / 4 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] writeNewProcess 100.00% 22 / 22 100.00% 1 / 1 7
 [BO\Zmsbackend\Process\Service\Process] readNewProcessId 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readAuthKeyByProcessId 100.00% 9 / 9 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readList 90.90% 10 / 11 0.00% 0 / 1 4.01
 [BO\Zmsbackend\Process\Service\Process] readProcessesWithoutRequests 100.00% 5 / 5 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] attachAllRequestsInOneQuery 78.57% 11 / 14 0.00% 0 / 1 7.48
 [BO\Zmsbackend\Process\Service\Process] readEntityList 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readByWorkstation 100.00% 7 / 7 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readProcessListByScopesAndTime 100.00% 11 / 11 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readConflictListByScopeAndTime 100.00% 24 / 24 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] readProcessListByScopeAndStatus 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readProcessListByClusterAndTime 100.00% 6 / 6 100.00% 1 / 1 3
 [BO\Zmsbackend\Process\Service\Process] readProcessListCountByScope 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readProcessListByMailAddress 100.00% 11 / 11 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readListByMailAndStatusList 100.00% 10 / 10 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] updateProcessStatus 80.00% 4 / 5 0.00% 0 / 1 2.03
 [BO\Zmsbackend\Process\Service\Process] shouldUpdateDisplayNumber 62.50% 5 / 8 0.00% 0 / 1 6.32
 [BO\Zmsbackend\Process\Service\Process] writeDeletedEntity 100.00% 15 / 15 100.00% 1 / 1 4
 [BO\Zmsbackend\Process\Service\Process] deleteEntity 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] writeCanceledEntity 100.00% 12 / 12 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] writeBlockedEntity 100.00% 24 / 24 100.00% 1 / 1 6
 [BO\Zmsbackend\Process\Service\Process] writeRequestsToDb 100.00% 13 / 13 100.00% 1 / 1 7
 [BO\Zmsbackend\Process\Service\Process] deleteRequestsForProcessId 100.00% 6 / 6 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readExpiredProcessList 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readUnconfirmedProcessList 0.00% 0 / 8 0.00% 0 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readExpiredProcessListByStatus 100.00% 10 / 10 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readExpiredReservationsList 100.00% 8 / 8 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] newDeleteListQuery 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readDeleteList 100.00% 10 / 10 100.00% 1 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readEmailReminderProcessListByInterval 100.00% 11 / 11 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] readDeallocateProcessList 100.00% 9 / 9 100.00% 1 / 1 1
 [BO\Zmsbackend\Process\Service\Process] isAppointmentAllowedWithSameMail 94.44% 17 / 18 0.00% 0 / 1 10.02
 [BO\Zmsbackend\Process\Service\Process] isMailWhitelisted 90.00% 9 / 10 0.00% 0 / 1 6.04
 [BO\Zmsbackend\Process\Service\Process] readProcessWithSameDayAndDisplayNumber 0.00% 0 / 9 0.00% 0 / 1 2
 [BO\Zmsbackend\Process\Service\Process] readProcessListByExternalUserId 100.00% 14 / 14 100.00% 1 / 1 3
 [BO\Zmsbackend\Process\Service\Process] readAssignedWorkstationIdForUpdate 80.00% 4 / 5 0.00% 0 / 1 3.07
 [BO\Zmsbackend\Base] __construct 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] init 100.00% 2 / 2 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] getWriter 100.00% 4 / 4 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] getReader 100.00% 5 / 5 100.00% 1 / 1 3
 [BO\Zmsbackend\Base] fetchPreparedStatement 100.00% 9 / 9 100.00% 1 / 1 3
 [BO\Zmsbackend\Base] startExecute 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] pdoExceptionHandler 100.00% 13 / 13 100.00% 1 / 1 4
 [BO\Zmsbackend\Base] fetchStatement 100.00% 3 / 3 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchOne 100.00% 7 / 7 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] fetchRow 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchValue 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchAll 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchHandle 100.00% 5 / 5 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchList 100.00% 8 / 8 100.00% 1 / 1 2
 [BO\Zmsbackend\Base] writeItem 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] deleteItem 100.00% 1 / 1 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] perform 100.00% 7 / 7 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] fetchAffected 100.00% 8 / 8 100.00% 1 / 1 1
 [BO\Zmsbackend\Base] hashStringValue 50.00% 5 / 10 0.00% 0 / 1 8.12
11class ProcessStatusFree extends Process
12{
13    /**
14     * @return (\BO\Zmsbackend\Day\Service\Day|\BO\Zmsentities\Calendar|array)[]
15     *
16     */
17    private function prepareCalendarAndDays(
18        \BO\Zmsentities\Calendar $calendar,
19        \DateTimeInterface $now,
20        int|null $slotsRequired = null
21    ): array {
22        $calendar = (new \BO\Zmsbackend\Calendar\Service\Calendar())->readResolvedEntity($calendar, $now, true);
23        $dayquery = new \BO\Zmsbackend\Day\Service\Day();
24        $dayquery->writeTemporaryScopeList($calendar, $slotsRequired);
25
26        return [$calendar, $dayquery, $this->buildDaysList($calendar)];
27    }
28
29    private function buildDaysList(\BO\Zmsentities\Calendar $calendar): array
30    {
31        $selectedDate = $calendar->getFirstDay();
32        $days = [$selectedDate];
33        if ($calendar->getLastDay(false)) {
34            $days = [];
35            while ($selectedDate <= $calendar->getLastDay(false)) {
36                $days[] = $selectedDate;
37                $selectedDate = $selectedDate->modify('+1 day');
38            }
39        }
40
41        return $days;
42    }
43
44    /**
45     * Prefer concrete days already on the calendar (e.g. bookable days only).
46     * Falls back to the full firstDay→lastDay range when no days are set.
47     */
48    private function buildDaysListFromCalendarDays(\BO\Zmsentities\Calendar $calendar): array
49    {
50        if (!isset($calendar->days) || count($calendar->days) < 1) {
51            return $this->buildDaysList($calendar);
52        }
53
54        $daysByDate = [];
55        foreach ($calendar->days as $day) {
56            if (!$day instanceof \BO\Zmsentities\Day) {
57                $day = new \BO\Zmsentities\Day($day);
58            }
59            $dateTime = $day->toDateTime();
60            $daysByDate[$dateTime->format('Y-m-d')] = $dateTime;
61        }
62
63        if ($daysByDate === []) {
64            return $this->buildDaysList($calendar);
65        }
66
67        ksort($daysByDate);
68
69        return array_values($daysByDate);
70    }
71
72    public function readMinimalFreeProcessesFromCalendar(
73        \BO\Zmsentities\Calendar $calendar,
74        string $slotType = 'public',
75        ?int $slotsRequired = null,
76        bool $groupData = false
77    ): array {
78        $days = $this->buildDaysListFromCalendarDays($calendar);
79        if ($days === []) {
80            return [];
81        }
82
83        $processData = $this->getProcessDataHandle(
84            $days,
85            $slotType,
86            $slotsRequired,
87            $groupData,
88            true
89        );
90
91        $processInfos = [];
92        while ($item = $processData->fetch(\PDO::FETCH_ASSOC)) {
93            $processInfo = $this->extractProcessInfo($item, $calendar);
94            if ($processInfo) {
95                $processInfos[] = $processInfo;
96            }
97        }
98
99        $processData->closeCursor();
100
101        return $this->deduplicateWithRoundRobin($processInfos);
102    }
103
104    private function getProcessDataHandle(
105        array $days,
106        string $slotType,
107        int|null $slotsRequired,
108        bool $groupData,
109        bool $useAvailabilityQuery = false,
110        ?\DateTimeInterface $appointmentTime = null
111    ) {
112        $query = $useAvailabilityQuery
113            ? \BO\Zmsbackend\Process\Repository\ProcessStatusFree::QUERY_SELECT_PROCESSLIST_DAYS_AVAILABILITY
114            : \BO\Zmsbackend\Process\Repository\ProcessStatusFree::QUERY_SELECT_PROCESSLIST_DAYS;
115
116        $condition = \BO\Zmsbackend\Process\Repository\ProcessStatusFree::buildDaysCondition($days);
117        $params = [
118            'slotType' => $slotType,
119            'forceRequiredSlots' =>
120                ($slotsRequired === null || $slotsRequired < 1) ? 1 : intval($slotsRequired),
121        ];
122        if ($appointmentTime !== null) {
123            // Reserving only needs to verify the requested time, not every slot on that day.
124            $condition .= ' AND s.time = :appointmentTime';
125            $params['appointmentTime'] = $appointmentTime->format('H:i:s');
126        }
127
128        return $this->fetchHandle(
129            sprintf($query, $condition)
130            . ($groupData ? \BO\Zmsbackend\Process\Repository\ProcessStatusFree::GROUPBY_SELECT_PROCESSLIST_DAY : ''),
131            $params
132        );
133    }
134
135    public function readFreeProcesses(
136        \BO\Zmsentities\Calendar $calendar,
137        \DateTimeInterface $now,
138        string $slotType = 'public',
139        int|null $slotsRequired = null,
140        bool $groupData = false,
141        ?\DateTimeInterface $appointmentTime = null
142    ): Collection {
143        list($calendar, $dayquery, $days) = $this->prepareCalendarAndDays($calendar, $now, $slotsRequired);
144        $processList = $this->readPreparedFreeProcesses(
145            $calendar,
146            $days,
147            $slotType,
148            $slotsRequired,
149            $groupData,
150            $appointmentTime
151        );
152        unset($dayquery);
153        return $processList;
154    }
155
156    private function readPreparedFreeProcesses(
157        \BO\Zmsentities\Calendar $calendar,
158        array $days,
159        string $slotType,
160        int|null $slotsRequired,
161        bool $groupData,
162        ?\DateTimeInterface $appointmentTime
163    ): Collection {
164        $processData = $this->getProcessDataHandle(
165            $days,
166            $slotType,
167            $slotsRequired,
168            $groupData,
169            false,
170            $appointmentTime
171        );
172        $processList = new Collection();
173        $scopeList = [];
174        while ($item = $processData->fetch(\PDO::FETCH_ASSOC)) {
175            $process = new \BO\Zmsentities\Process($item);
176            $process->requests = $calendar->requests;
177            $process->appointments->getFirst()->setDateByString(
178                $process->appointments->getFirst()->date,
179                'Y-m-d H:i:s'
180            );
181
182            if (! isset($scopeList[$process->scope->id])) {
183                $scopeList[$process->scope->id] = $calendar->scopes->getEntity($process->scope->id);
184            }
185
186            $process->scope = $scopeList[$process->scope->id];
187            $process->queue['withAppointment'] = 1;
188            $process->appointments->getFirst()->scope = $process->scope;
189            $processList->addEntity($process);
190        }
191        $processData->closeCursor();
192        return $processList;
193    }
194
195    public function readFreeProcessesMinimalDeduplicated(
196        \BO\Zmsentities\Calendar $calendar,
197        \DateTimeInterface $now,
198        string $slotType = 'public',
199        ?int $slotsRequired = null,
200        bool $groupData = false
201    ): array {
202        list($calendar, $dayquery, $days) = $this->prepareCalendarAndDays($calendar, $now, $slotsRequired);
203        $processData = $this->getProcessDataHandle($days, $slotType, $slotsRequired, $groupData);
204
205        $processInfos = [];
206        while ($item = $processData->fetch(\PDO::FETCH_ASSOC)) {
207            $processInfo = $this->extractProcessInfo($item, $calendar);
208            if ($processInfo) {
209                $processInfos[] = $processInfo;
210            }
211        }
212
213        $processData->closeCursor();
214        unset($dayquery);
215
216        return $this->deduplicateWithRoundRobin($processInfos);
217    }
218
219    /**
220     * Keep one free process per round-robin group + timestamp.
221     *
222     * Default group is the provider id. When provider.data.sharedBookingOfficeIds
223     * is set, all peer providers share one group so the same wall-clock slot is
224     * offered once and successive timeslots round-robin across eligible scopes
225     * of every peer (ZMSKVR-1046). Scopes that cannot fit the slot never appear
226     * here, so fall-through is preserved.
227     *
228     * @param array<int, array<string, mixed>> $processInfos
229     * @return array<int, array<string, mixed>>
230     */
231    private function deduplicateWithRoundRobin(array $processInfos): array
232    {
233        // Composite key: round-robin group (provider or shared-office set) + slot timestamp.
234        $candidatesByGroupTimestampKey = [];
235        $groupTimestampKeyOrder = [];
236        foreach ($processInfos as $processInfo) {
237            $roundRobinGroupKey = self::resolveRoundRobinGroupKey(
238                (string) $processInfo['providerId'],
239                $processInfo['sharedBookingOfficeIds'] ?? null
240            );
241            $groupTimestampKey = $roundRobinGroupKey . '_' . $processInfo['date'];
242            if (!isset($candidatesByGroupTimestampKey[$groupTimestampKey])) {
243                $groupTimestampKeyOrder[] = $groupTimestampKey;
244                $candidatesByGroupTimestampKey[$groupTimestampKey] = [];
245            }
246            $candidatesByGroupTimestampKey[$groupTimestampKey][] = $processInfo;
247        }
248
249        $roundRobinIndexByGroup = [];
250        $deduplicatedProcesses = [];
251        foreach ($groupTimestampKeyOrder as $groupTimestampKey) {
252            $candidates = self::uniqueCandidatesSortedByScopeId(
253                $candidatesByGroupTimestampKey[$groupTimestampKey]
254            );
255            $roundRobinGroupKey = self::resolveRoundRobinGroupKey(
256                (string) $candidates[0]['providerId'],
257                $candidates[0]['sharedBookingOfficeIds'] ?? null
258            );
259            $roundRobinTimeslotIndex = $roundRobinIndexByGroup[$roundRobinGroupKey] ?? 0;
260            $chosenCandidate = $candidates[
261                self::pickRoundRobinIndex($roundRobinTimeslotIndex, count($candidates))
262            ];
263            $roundRobinIndexByGroup[$roundRobinGroupKey] = $roundRobinTimeslotIndex + 1;
264            $deduplicatedProcesses[] = $this->createMinimalProcess($chosenCandidate);
265        }
266
267        return $deduplicatedProcesses;
268    }
269
270    /**
271     * @param array<int, array<string, mixed>> $candidates
272     * @return array<int, array<string, mixed>>
273     */
274    private static function uniqueCandidatesSortedByScopeId(array $candidates): array
275    {
276        $candidatesByScopeId = [];
277        foreach ($candidates as $candidate) {
278            $candidatesByScopeId[(string) $candidate['scopeId']] = $candidate;
279        }
280        $uniqueCandidates = array_values($candidatesByScopeId);
281        usort(
282            $uniqueCandidates,
283            static fn (array $left, array $right): int =>
284                ((int) $left['scopeId']) <=> ((int) $right['scopeId'])
285        );
286
287        return $uniqueCandidates;
288    }
289
290    /**
291     * @internal Exposed for unit tests.
292     * @param array<int, int|string>|null $sharedBookingOfficeIds
293     */
294    public static function resolveRoundRobinGroupKey(
295        string $providerId,
296        ?array $sharedBookingOfficeIds
297    ): string {
298        if (!is_array($sharedBookingOfficeIds) || $sharedBookingOfficeIds === []) {
299            return $providerId;
300        }
301
302        $sortedSharedOfficeIds = array_map('intval', $sharedBookingOfficeIds);
303        sort($sortedSharedOfficeIds, SORT_NUMERIC);
304
305        return implode(',', $sortedSharedOfficeIds);
306    }
307
308    /**
309     * @internal Exposed for unit tests.
310     */
311    public static function pickRoundRobinIndex(int $timeslotIndex, int $candidateCount): int
312    {
313        if ($candidateCount < 1) {
314            throw new \InvalidArgumentException('candidateCount must be >= 1');
315        }
316
317        return $timeslotIndex % $candidateCount;
318    }
319
320    private function extractProcessInfo(array $item, \BO\Zmsentities\Calendar $calendar): ?array
321    {
322        $scopeId = $item['scope__id'] ?? null;
323        $dateString = $item['appointments__0__date'] ?? null;
324
325        if (!$scopeId || !$dateString) {
326            return null;
327        }
328
329        $date = strtotime($dateString);
330        if (!$date) {
331            return null;
332        }
333
334        $scope = $calendar->scopes->getEntity($scopeId);
335        if (!$scope) {
336            return null;
337        }
338
339        $providerId = $scope->getProviderId();
340        if (!$providerId) {
341            return null;
342        }
343
344        $sharedBookingOfficeIds = null;
345        $provider = $scope->getProvider();
346        if (
347            $provider
348            && isset($provider->data['sharedBookingOfficeIds'])
349            && is_array($provider->data['sharedBookingOfficeIds'])
350            && $provider->data['sharedBookingOfficeIds'] !== []
351        ) {
352            $sharedBookingOfficeIds = array_map('intval', $provider->data['sharedBookingOfficeIds']);
353        }
354
355        return [
356            'scopeId' => $scopeId,
357            'source' => $scope->getSource(),
358            'providerId' => $providerId,
359            'sharedBookingOfficeIds' => $sharedBookingOfficeIds,
360            'date' => $date
361        ];
362    }
363
364    private function createMinimalProcess(array $processInfo): array
365    {
366        return [
367            '$schema' => 'https://schema.berlin.de/queuemanagement/process.json',
368            'scope' => [
369                'id' => $processInfo['scopeId'],
370                'source' => $processInfo['source'],
371                'provider' => [
372                    'id' => $processInfo['providerId'],
373                    'source' => $processInfo['source'],
374                ]
375            ],
376            'appointments' => [
377                [
378                    'date' => (string)$processInfo['date'],
379                    'scope' => [
380                        'id' => $processInfo['scopeId'],
381                        'source' => $processInfo['source'],
382                        'provider' => [
383                            'id' => $processInfo['providerId'],
384                            'source' => $processInfo['source'],
385                        ]
386                    ]
387                ]
388            ]
389        ];
390    }
391
392    public function readReservedProcesses(int $resolveReferences = 2): Collection
393    {
394        $processList = new Collection();
395        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
396        $query
397            ->addResolvedReferences($resolveReferences)
398            ->addEntityMapping()
399            ->addConditionAssigned()
400            ->addConditionIsReserved();
401        $resultData = $this->fetchList($query, new Entity());
402        foreach ($resultData as $process) {
403            if (2 == $resolveReferences) {
404                $process->requests = (new \BO\Zmsbackend\Request\Service\Request())->readRequestByProcessId($process->id, $resolveReferences);
405                $process->scope = (new \BO\Zmsbackend\Scope\Service\Scope())->readEntity($process->getScopeId(), $resolveReferences);
406            }
407            if ($process instanceof Entity) {
408                $processList->addEntity($process);
409            }
410        }
411        return $processList;
412    }
413
414    /**
415     * Insert a new process if there are free slots
416     *
417     * @param \BO\Zmsentities\Process $process
418     * @param \DateTimeInterface $now
419     * @param String $slotType
420     * @param Int $slotsRequired we cannot use process.appointments.0.slotCount, because setting slotsRequired is
421     *        a priviliged operation. Just using the input would be a security flaw to get a wider selection of times
422     *        If slotsRequired = 0, readFreeProcesses() uses the slotsRequired based on request-provider relation
423     */
424    public function writeEntityReserved(
425        \BO\Zmsentities\Process $process,
426        \DateTimeInterface $now,
427        string $slotType = "public",
428        int $slotsRequired = 0,
429        int $resolveReferences = 0,
430        ?\BO\Zmsentities\Useraccount $userAccount = null
431    ): ?\BO\Zmsentities\Process {
432        $maxAttempts = 3;
433        $attempt = 0;
434        while (true) {
435            try {
436                return $this->writeEntityReservedAttempt(
437                    $process,
438                    $now,
439                    $slotType,
440                    $slotsRequired,
441                    $resolveReferences,
442                    $userAccount
443                );
444            } catch (\BO\Zmsbackend\Exception\Pdo\DeadLockFound $exception) {
445                $attempt++;
446                if ($attempt >= $maxAttempts) {
447                    throw $exception;
448                }
449                $this->resetWriteTransactionAfterDeadlock();
450                usleep(50000 * $attempt);
451            }
452        }
453    }
454
455    protected function writeEntityReservedAttempt(
456        \BO\Zmsentities\Process $process,
457        \DateTimeInterface $now,
458        string $slotType = "public",
459        int $slotsRequired = 0,
460        int $resolveReferences = 0,
461        ?\BO\Zmsentities\Useraccount $userAccount = null
462    ): ?\BO\Zmsentities\Process {
463        $process = clone $process;
464        $process->status = 'reserved';
465        $appointment = $process->getAppointments()->getFirst();
466        $appointmentTime = $appointment->toDateTime();
467        // Calendar lookup and the first free-slot check stay outside the slot lock.
468        $this->getWriter();
469        [$calendar, $dayquery, $days] = $this->prepareCalendarAndDays(
470            $process->toCalendar(),
471            $now,
472            $slotsRequired
473        );
474        $freeProcessList = $this->readPreparedFreeProcesses(
475            $calendar,
476            $days,
477            $slotType,
478            $slotsRequired,
479            false,
480            $appointmentTime
481        );
482        if (!$freeProcessList->getAppointmentList()->hasAppointment($appointment)) {
483            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
484        }
485
486        try {
487            // The availability chosen under the slot locks is the one the reservation is mapped to.
488            $reservation = (new \BO\Zmsbackend\Slot\Service\Slot())->readReservationByAppointment(
489                $appointment,
490                $slotsRequired,
491                (null !== $userAccount),
492                true,
493                $slotType
494            );
495        } catch (\BO\Zmsbackend\Exception\Pdo\LockTimeout) {
496            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
497        }
498        $slotList = $reservation['slotList'];
499        $availabilityId = (int) $reservation['availability']->getId() ?: null;
500        $freeProcessList = $this->readPreparedFreeProcesses(
501            $calendar,
502            $days,
503            $slotType,
504            $slotsRequired,
505            false,
506            $appointmentTime
507        );
508        if (!$freeProcessList->getAppointmentList()->hasAppointment($appointment) || ! $slotList) {
509            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
510        }
511        unset($dayquery);
512
513        // One row stores the length. The save maps every step of that length on the chosen availability.
514        if ($process->id === 0) {
515            $process = $this->writeNewProcess(
516                $process,
517                $now,
518                0,
519                count($slotList) - 1,
520                true,
521                $userAccount,
522                $availabilityId
523            );
524        } elseif ($process->id <= 99999) {
525            throw new \Exception("SQL UPDATE error on inserting new $process");
526        } else {
527            throw new \BO\Zmsbackend\Process\Exception\ProcessReserveFailed();
528        }
529        $this->writeRequestsToDb($process);
530        return $this->readEntity($process->getId(), new \BO\Zmsbackend\Helper\NoAuth(), $resolveReferences);
531    }
532
533    /**
534     * After InnoDB aborts a transaction on deadlock, clear PDO state and start a fresh transaction.
535     */
536    protected function resetWriteTransactionAfterDeadlock(): void
537    {
538        $connection = \BO\Zmsbackend\Connection\Select::getWriteConnection();
539        if ($connection->inTransaction()) {
540            try {
541                $connection->rollBack();
542            } catch (\PDOException $exception) {
543                \App::$log->warning('Rollback after deadlock failed', [
544                    'error' => $exception->getMessage(),
545                ]);
546            }
547        }
548        if (!$connection->inTransaction()) {
549            $connection->beginTransaction();
550        }
551    }
552}

Inherited from BO\Zmsbackend\Process\Service\Process

24    public function readEntity(int|string|null $processId = null, string|\BO\Zmsbackend\Helper\NoAuth|null $authKey = null, int $resolveReferences = 2): ?Entity
25    {
26        if (null === $processId || null === $authKey) {
27            return null;
28        }
29        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
30        $query->addEntityMapping()
31            ->addResolvedReferences($resolveReferences)
32            ->addConditionProcessId($processId);
33        if (!$authKey instanceof \BO\Zmsbackend\Helper\NoAuth) {
34            $query->addConditionAuthKey($authKey);
35        }
36        $process = $this->fetchOne($query, new Entity());
37        $process = $this->readResolvedReferences($process, $resolveReferences);
38
39        return $process;
40    }
42    public function readById(string|int $processId, int $resolveReferences = 1): Entity
43    {
44        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
45        $query->addEntityMapping()
46            ->addResolvedReferences($resolveReferences)
47            ->addConditionProcessId($processId);
48        return $this->fetchOne($query, new Entity());
49    }
56    public function readResolvedReferences(\BO\Zmsentities\Schema\Entity $entity, int $resolveReferences)
57    {
58        if (0 <= $resolveReferences) {
59            if ($entity->archiveId) {
60                $entity->requests = (new \BO\Zmsbackend\Request\Service\Request())
61                    ->readRequestByArchiveId($entity->archiveId, $resolveReferences - 1);
62            } else {
63                $entity->requests = (new \BO\Zmsbackend\Request\Service\Request())
64                    ->readRequestByProcessId($entity->id, $resolveReferences - 1);
65            }
66        }
67        return $entity;
68    }
77    public function updateEntity(\BO\Zmsentities\Process $process, \DateTimeInterface $now, int $resolveReferences = 0, string|null $previousStatus = null, ?\BO\Zmsentities\Useraccount $useraccount = null): Entity
78    {
79        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::UPDATE);
80        $query->addConditionProcessId($process->getId());
81        $query->addConditionAuthKey($process->getAuthKey());
82        $query->addValuesUpdateProcess($process, $now, 0, $previousStatus);
83        if ($this->perform($query->getLockProcessId(), ['processId' => $process->getId()])) {
84            $this->writeItem($query);
85            $this->writeRequestsToDb($process);
86        }
87        $process = $this->readEntity($process->getId(), $process->authKey, $resolveReferences);
88        if (!$process->getId()) {
89            throw new \BO\Zmsbackend\Process\Exception\ProcessUpdateFailed();
90        }
91        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_UPDATE_FOLLOWING_PROCESS, [
92            'reserved' => ($process->status == 'reserved') ? 1 : 0,
93            'processID' => $process->getId(),
94        ]);
95        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("UPDATE (\BO\Zmsbackend\Process\Service\Process::updateEntity) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process, $useraccount);
96        return $process;
97    }
99    public function updateEntityDisplayNumber(Entity $process): Entity
100    {
101        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::UPDATE);
102        $query->addConditionProcessId($process->getId());
103        $query->addConditionAuthKey($process->getAuthKey());
104
105        $process->displayNumber = $query->getNewDisplayNumber($process);
106        $query->addValueDisplayNumber($process);
107        if ($this->perform($query->getLockProcessId(), ['processId' => $process->getId()])) {
108            $this->writeItem($query);
109        }
110
111        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("UPDATE (updateEntityDisplayNumber) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process);
112        return $process;
113    }
125    public function updateEntityWithSlots(\BO\Zmsentities\Process $process, \DateTimeInterface $now, ?string $slotType = "intern", $slotsRequired = 0, int $resolveReferences = 0, ?\BO\Zmsentities\Useraccount $userAccount = null)
126    {
127        if ('intern' != $slotType) {
128            return $this->updateEntity($process, $now, $resolveReferences, null, $userAccount);
129        }
130        $process = clone $process;
131        $appointment = $process->getAppointments()->getFirst();
132        $slotService = new \BO\Zmsbackend\Slot\Service\Slot();
133        $reservation = $slotService->readReservationByAppointment($appointment, $slotsRequired, true);
134        $slotList = $reservation['slotList'];
135        $availabilityId = (int) $reservation['availability']->getId() ?: null;
136        $processEntityList = $this->readEntityList($process->getId());
137        foreach ($processEntityList as $entity) {
138            if ($process->getId() != $entity->getId()) {
139                $this->writeDeletedEntity($entity->getId());
140            }
141        }
142        // One row stores the length. Map its steps after that length is saved, on the availability
143        // chosen under the slot lock.
144        $appointment->addSlotCount($slotList->count());
145        $processEntity = $this->updateEntity($process, $now, $resolveReferences, null, $userAccount);
146        $savedProcess = $this->readEntity($process->getId(), $process->authKey, $resolveReferences);
147        if ($savedProcess instanceof Entity) {
148            $process = $savedProcess;
149        }
150        $slotService->writeSlotProcessMappingFor($process->getId(), $availabilityId);
151
152        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::updateEntityWithSlots) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process, $userAccount);
153        return $processEntity;
154    }
156    public function redirectToScope(Entity $process, \BO\Zmsentities\Scope $scope, int $waitingNumber, ?\BO\Zmsentities\Useraccount $useraccount = null): Entity
157    {
158        $datetime = \App::$now;
159        $process->setStatus('confirmed');
160        $appointment = $process->getFirstAppointment();
161        $date = (new \DateTimeImmutable())->setTimestamp($appointment->date);
162        $date = $date->setTime(0, 0, 0);
163        $appointment->date = $date->getTimestamp();
164        $process->appointments = new AppointmentList([$appointment]);
165        $newQueueNumber = (new \BO\Zmsbackend\Scope\Service\Scope())->readWaitingNumberUpdated($scope->id, $datetime);
166        $process->addQueue($newQueueNumber, $datetime);
167        $process->queue['number'] = $waitingNumber;
168        $process->priority = \BO\Zmsentities\Collection\QueueList::DEFAULT_PRIORITY_WITH_APPOINTMENT;
169        $process = $this->writeNewProcess($process, $datetime);
170        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::redirectToScope) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_REDIRECTED, $process, $useraccount);
171        $this->writeRequestsToDb($process);
172        return $process;
173    }
175    public function readSlotCount(\BO\Zmsentities\Process $process): Entity
176    {
177        $scope = new \BO\Zmsentities\Scope($process->scope);
178        $requestRelationList = (new \BO\Zmsbackend\RequestRelation\Service\RequestRelation())
179            ->readListByProviderId($scope->getProviderId(), $scope->getSource());
180        $appointment = $process->getAppointments()->getFirst();
181        $appointment->slotCount = 0;
182        foreach ($process->requests as $request) {
183            foreach ($requestRelationList as $requestRelation) {
184                if ($requestRelation->getRequest()->getId() == $request->getId()) {
185                    $appointment->slotCount += $requestRelation->getSlotCount();
186                }
187            }
188        }
189        $appointment->slotCount = round($appointment->slotCount, 0);
190        return $process;
191    }
196    public function writeEntityWithNewAppointment(\BO\Zmsentities\Process $process, \BO\Zmsentities\Appointment $appointment, \DateTimeInterface $now, string $slotType = 'public', int $slotsRequired = 0, int $resolveReferences = 0, bool $keepReserved = false): Entity|null
197    {
198        // clone to new process with id = 0 and new appointment to reserve
199        $processNew = clone $process;
200        $processNew->id = 0;
201        $processNew->scope = $appointment->scope;
202        $processNew->queue['arrivalTime'] = 0;
203        $processNew->queue['number'] = 0;
204        $processNew->appointments = (new \BO\Zmsentities\Collection\AppointmentList())->addEntity($appointment);
205//delete old process with following processes
206        $this->writeDeletedEntity($process->getId());
207//reserve new appointment
208        $processNew = \BO\Zmsbackend\Process\Service\ProcessStatusFree::init()
209            ->writeEntityReserved($processNew, $now, $slotType, $slotsRequired);
210        $processTempNewId = $processNew->getId();
211// reassign credentials of new process with credentials of old process
212        $processNew->withReassignedCredentials($process);
213// update new process with old credentials, also assigned requests and following slots
214        $this->updateFollowingProcesses($processTempNewId, $processNew);
215        $this->updateReassignedRequests($processTempNewId, $processNew->getId());
216//keep the availability chosen by the reservation, then delete slot mapping for temp process id
217        $slotService = new \BO\Zmsbackend\Slot\Service\Slot();
218        $reservedAvailabilityId = $slotService->readMappedAvailabilityId($processTempNewId);
219        $slotService->deleteSlotProcessMappingFor($processTempNewId);
220//write new slot mapping for changed process with old credentials because new appointment data
221        $slotService->writeSlotProcessMappingFor($processNew->getId(), $reservedAvailabilityId);
222        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("UPDATE (\BO\Zmsbackend\Process\Service\Process::writeEntityWithNewAppointment) $process ", \BO\Zmsbackend\Log\Service\Log::ACTION_EDITED, $process);
223        $status = ($keepReserved) ? Entity::STATUS_RESERVED : ENTITY::STATUS_CONFIRMED;
224        return $this->updateProcessStatus($processNew, $status, $now, $resolveReferences);
225    }
230    public function updateFollowingProcesses(string|int $processId, \BO\Zmsentities\Process $processData): void
231    {
232        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_PROCESS_CREDENTIALS, [
233            'newProcessId' => $processData->getId(),
234            'newAuthKey' => $processData->getAuthKey(),
235            'processId' => $processId
236        ]);
237        $processEntityList = $this->readEntityList($processId);
238        if ($processEntityList->count()) {
239            foreach ($processEntityList as $entity) {
240                if ($entity->getId() != $processId) {
241                    $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_FOLLWING_PROCESS, [
242                        'newProcessId' => $processData->getId(),
243                        'processId' => $processId
244                    ]);
245                }
246            }
247        }
248    }
253    public function updateReassignedRequests(string|int $processId, string|int $newProcessId): void
254    {
255        $this->perform(\BO\Zmsbackend\Process\Repository\Process::QUERY_REASSIGN_PROCESS_REQUESTS, [
256            'newProcessId' => $newProcessId,
257            'processId' => $processId
258        ]);
259    }
265    protected function writeNewProcess(\BO\Zmsentities\Process $process, \DateTimeInterface $dateTime, int $parentProcess = 0, int $childProcessCount = 0, bool $retry = true, \BO\Zmsentities\Useraccount|null $userAccount = null, ?int $availabilityId = null)
266    {
267        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::INSERT);
268        $process->id = $this->readNewProcessId();
269        $process->setRandomAuthKey();
270        $process->createTimestamp = $dateTime->getTimestamp();
271        if ($parentProcess !== 0) {
272            $process->displayNumber = '';
273        }
274
275        $query->addValuesNewProcess($process, $parentProcess, $childProcessCount);
276
277        if ($parentProcess === 0 && !empty($process->getDisplayNumber())) {
278            $query->addValueDisplayNumber($process);
279        }
280
281        $query->addValuesScopeData($process);
282        $query->addValuesAppointmentData($process);
283        $query->addValuesUpdateProcess($process, $dateTime, $parentProcess);
284        try {
285            $this->writeItem($query);
286        } catch (\BO\Zmsbackend\Exception\Pdo\PDOFailed $exception) {
287            if ($retry) {
288        // First try might fail if two processes are created with the same number at the same time
289                sleep(1);
290        // Let the other process complete his transaction
291                return $this->writeNewProcess($process, $dateTime, $parentProcess, $childProcessCount, false, $userAccount, $availabilityId);
292            }
293            throw new \BO\Zmsbackend\Process\Exception\ProcessCreateFailed($exception->getMessage());
294        }
295        (new \BO\Zmsbackend\Slot\Service\Slot())->writeSlotProcessMappingFor($process->id, $availabilityId);
296        $checksum = ($userAccount) ? sha1($process->id . '-' . $userAccount->getId()) : '';
297
298        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("CREATE (\BO\Zmsbackend\Process\Service\Process::writeNewProcess) $process $checksum ", \BO\Zmsbackend\Log\Service\Log::ACTION_NEW, $process, $userAccount);
299        return $process;
300    }
306    protected function readNewProcessId()
307    {
308        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
309        $newProcessId = $this->fetchValue($query->getQueryNewProcessId());
310        return $newProcessId;
311    }
318    public function readAuthKeyByProcessId(string|int $processId)
319    {
320        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
321        $query
322            ->addEntityMapping()
323            ->addResolvedReferences(0)
324            ->addConditionProcessId($processId);
325        $process = $this->fetchOne($query, new Entity());
326        return ($process->hasId()) ? array(
327            'authKey' => $process->authKey
328        ) : null;
329    }
331    protected function readList(\PDOStatement $statement, int $resolveReferences): Collection
332    {
333        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
334        $processList = new Collection();
335        $processIds = [];
336        while ($processData = $statement->fetch(\PDO::FETCH_ASSOC)) {
337            $entity = new Entity($query->postProcessJoins($processData));
338            // The availability join may match a process once per overlapping availability
339            if ($entity->getId() && isset($processIds[$entity->getId()])) {
340                continue;
341            }
342            $processIds[$entity->getId()] = true;
343            $entity = $this->readResolvedReferences($entity, $resolveReferences);
344            $processList->addEntity($entity);
345        }
346        return $processList;
347    }
349    protected function readProcessesWithoutRequests(\PDOStatement $statement): Collection
350    {
351        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
352        $processList = new Collection();
353        while ($processData = $statement->fetch(\PDO::FETCH_ASSOC)) {
354            $processList->addEntity(new Entity($query->postProcessJoins($processData)));
355        }
356        return $processList;
357    }
359    protected function attachAllRequestsInOneQuery(Collection $processList, int $resolveReferences): Collection
360    {
361        if ($processList->count() === 0 || $resolveReferences < 0) {
362            return $processList;
363        }
364
365        $processIds = [];
366        foreach ($processList as $process) {
367            if ($process->hasId()) {
368                $processIds[] = $process->getId();
369            }
370        }
371
372        $requestsByProcessId = (new \BO\Zmsbackend\Request\Service\Request())
373            ->readAllRequestsForProcessIds($processIds, $resolveReferences - 1);
374
375        foreach ($processList as $process) {
376            if (!$process->hasId()) {
377                continue;
378            }
379            $process->requests = $requestsByProcessId[(int) $process->getId()]
380                ?? new \BO\Zmsentities\Collection\RequestList();
381        }
382
383        return $processList;
384    }
389    public function readEntityList(string|int $processId, int $resolveReferences = 0)
390    {
391        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
392        $query
393            ->addResolvedReferences($resolveReferences)
394            ->addEntityMapping()
395            ->addConditionProcessIdFollow($processId);
396        $statement = $this->fetchStatement($query);
397        return $this->readList($statement, $resolveReferences)->sortByAppointmentDate();
398    }
400    public function readByWorkstation(\BO\Zmsentities\Workstation $workstation, int $resolveReferences = 0)
401    {
402        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
403        $query
404            ->addResolvedReferences($resolveReferences)
405            ->addEntityMapping()
406            ->addConditionWorkstationId($workstation->id);
407        $process = $this->fetchOne($query, new Entity());
408        return ($process->hasId()) ? $this->readResolvedReferences($process, $resolveReferences) : null;
409    }
420    public function readProcessListByScopesAndTime(
421        $scopeIds,
422        \DateTimeInterface $dateTime,
423        int $resolveReferences = 0,
424        array $withEntities = []
425    ) {
426        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT, '', false, null, $withEntities);
427        $query
428            ->addResolvedReferences($resolveReferences)
429            ->addEntityMapping()
430            ->addConditionScopeIds($scopeIds)
431            ->addConditionAssigned()
432            ->addConditionIgnoreSlots()
433            ->addConditionTime($dateTime)
434            ->removeDuplicates();
435        $statement = $this->fetchStatement($query);
436        return $this->readList($statement, $resolveReferences);
437    }
450    public function readConflictListByScopeAndTime(\BO\Zmsentities\Scope $scope, ?\DateTimeInterface $startDate = null, ?\DateTimeInterface $endDate = null, ?\DateTimeInterface $now = null, int $resolveReferences = 1)
451    {
452        $availabilityList = (new \BO\Zmsbackend\Availability\Service\Availability())
453            ->readAvailabilityListByScope($scope, 0, $startDate, $endDate)
454            ->withScope($scope);
455        if (! $endDate) {
456            $availabilityList = $availabilityList->withDateTime($startDate);
457            $endDate = $startDate;
458        }
459        $currentDate = ($startDate) ? $startDate : $now;
460        $conflictList = $availabilityList->getConflicts($startDate, $endDate);
461        while ($currentDate <= $endDate) {
462            $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
463            $query
464                ->addResolvedReferences($resolveReferences)
465                ->addEntityMapping()
466                ->addConditionScopeId($scope->getId())
467                ->addConditionAssigned()
468                ->addConditionIgnoreSlots();
469            $query->addConditionTime($currentDate);
470            $statement = $this->fetchStatement($query);
471            $processList = $this->readList($statement, $resolveReferences);
472            $processList = $processList->toQueueList($currentDate)->withoutStatus(['queued'])->toProcessList();
473            $conflictList->addList($processList->withOutAvailability($availabilityList));
474            $currentDate = $currentDate->modify('+1 day');
475        }
476        $conflictList = $conflictList->withoutExpiredAppointmentDate($now);
477        return $conflictList;
478    }
487    public function readProcessListByScopeAndStatus(int $scopeId, string $status, int $resolveReferences = 0, int $limit = 1000, ?int $offset = null)
488    {
489        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
490        $query
491            ->addResolvedReferences($resolveReferences)
492            ->addEntityMapping()
493            ->addConditionScopeId($scopeId) //removed because of dismatching scope and pickup scope
494            ->addConditionStatus($status)
495            ->addLimit($limit, $offset);
496        $statement = $this->fetchStatement($query);
497        return $this->readList($statement, $resolveReferences);
498    }
508    public function readProcessListByClusterAndTime($clusterId, \DateTimeInterface $dateTime)
509    {
510        $cluster = (new \BO\Zmsbackend\Cluster\Service\Cluster())->readEntity($clusterId, 1);
511        $scopeIds = [];
512        if ($cluster->scopes->count()) {
513            foreach ($cluster->scopes as $scope) {
514                $scopeIds[] = $scope->id;
515            }
516        }
517
518        return $this->readProcessListByScopesAndTime($scopeIds, $dateTime);
519    }
528    public function readProcessListCountByScope($scopeId)
529    {
530        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
531        $query
532            ->addCountValue()
533            ->addConditionAssigned()
534            ->addConditionIgnoreSlots()
535            ->addConditionScopeId($scopeId);
536        $statement = $this->fetchStatement($query);
537        $result = $statement->fetch(\PDO::FETCH_ASSOC);
538        return $result['processCount'];
539    }
546    public function readProcessListByMailAddress(string $mailAddress, ?int $scopeId = null, int $resolveReferences = 0, int $limit = 2000): Collection
547    {
548        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
549        $query
550            ->addResolvedReferences($resolveReferences)
551            ->addEntityMapping()
552            ->addConditionMail($mailAddress, true)
553            ->addConditionIgnoreSlots()
554            ->addLimit($limit);
555        if ($scopeId) {
556            $query->addConditionScopeId($scopeId);
557        }
558
559        $statement = $this->fetchStatement($query);
560        return $this->readList($statement, $resolveReferences);
561    }
569    public function readListByMailAndStatusList(string $mailAddress, array $statusList, int $resolveReferences = 1, int $limit = 300): Collection
570    {
571        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
572        $query
573            ->addResolvedReferences($resolveReferences)
574            ->addEntityMapping()
575            ->addConditionMail($mailAddress, true)
576            ->addConditionIgnoreSlots()
577            ->addLimit($limit);
578        $statement = $this->fetchStatement($query);
579        $collection = $this->readList($statement, $resolveReferences);
580        return $collection->toProcessListByStatusList($statusList);
581    }
592    public function updateProcessStatus(Entity $process, string $status, \DateTimeInterface $dateTime, int $resolveReferences = 0, ?\BO\Zmsentities\Useraccount $userAccount = null)
593    {
594        $process = (new ProcessStatus())
595            ->writeUpdatedStatus($process, $status, $dateTime, $resolveReferences, $userAccount);
596
597        /** @var Entity $process */
598        if ($this->shouldUpdateDisplayNumber($process, $status)) {
599            $this->updateEntityDisplayNumber($process);
600        }
601
602        return $process;
603    }
605    public function shouldUpdateDisplayNumber(Entity $process, string $status): bool
606    {
607        if ($status !== 'preconfirmed' && $status !== 'confirmed') {
608            return false;
609        }
610        $displayNumberPrefix = $process->scope->getPreference('queue', 'displayNumberPrefix');
611        if (empty($displayNumberPrefix)) {
612            return false;
613        }
614
615        if (str_starts_with($process->getDisplayNumber(), $displayNumberPrefix)) {
616            return false;
617        }
618
619        return true;
620    }
629    public function writeDeletedEntity(string|int $processId): bool
630    {
631        $processEntityList = $this->readEntityList($processId);
632        $status = false;
633        if ($processEntityList->count()) {
634            foreach ($processEntityList as $entity) {
635                $entityId = $entity->getId();
636                $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_DELETE;
637                $status = $this->perform($query, array(
638                    $entityId,
639                    $entityId
640                ));
641                if ($status) {
642                            $this->deleteRequestsForProcessId($entityId);
643                            (new \BO\Zmsbackend\Slot\Service\Slot())->deleteSlotProcessMappingFor($entityId);
644                            \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeDeletedEntity) $entityId ", \BO\Zmsbackend\Log\Service\Log::ACTION_DELETED, $entity);
645                }
646            }
647        }
648
649        return $status;
650    }
661    public function deleteEntity($processId, $authKey)
662    {
663        return $this->writeCanceledEntity($processId, $authKey);
664    }
674    public function writeCanceledEntity($processId, $authKey, ?\DateTimeInterface $now = null, ?\BO\Zmsentities\Useraccount $useraccount = null)
675    {
676        $canceledTimestamp = ($now) ? $now->getTimestamp() : (new \DateTimeImmutable())->getTimestamp();
677        $newAuthKey = bin2hex(random_bytes(32));
678        $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_CANCELED;
679        $this->perform($query, [
680            'processId' => $processId,
681            'authKey' => $authKey,
682            'canceledTimestamp' => $canceledTimestamp,
683            'newAuthKey' => $newAuthKey
684        ]);
685        $process = $this->readEntity($processId, new \BO\Zmsbackend\Helper\NoAuth(), 0);
686        \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeCanceledEntity) $processId ", \BO\Zmsbackend\Log\Service\Log::ACTION_CANCELED, $process, $useraccount);
687        return $process;
688    }
699    public function writeBlockedEntity(\BO\Zmsentities\Process $process, bool $releaseSlots = false, ?\BO\Zmsentities\Useraccount $useraccount = null)
700    {
701        $amendment = $process->toDerefencedAmendment();
702        $customTextfield = $process->toDerefencedcustomTextfield();
703        $customTextfield2 = $process->toDerefencedcustomTextfield2();
704        if (!isset($process->queue['status'])) {
705            $process->queue['status'] = $process->status;
706        }
707        $process->status = 'blocked';
708        $query = \BO\Zmsbackend\Process\Repository\Process::QUERY_DEREFERENCED;
709        $status = $this->perform($query, array(
710            $amendment,
711            $customTextfield,
712            $customTextfield2,
713            $process->id,
714            $process->authKey,
715            $process->id
716        ));
717        if ($status) {
718            $processEntityList = $this->readEntityList($process->id);
719            if ($processEntityList->count()) {
720                foreach ($processEntityList as $entity) {
721                    $entityId = $entity->getId();
722                    if ($releaseSlots) {
723                        (new \BO\Zmsbackend\Slot\Service\Slot())->deleteSlotProcessMappingFor($entityId);
724                    }
725                    \BO\Zmsbackend\Log\Service\Log::writeProcessLog("DELETE (\BO\Zmsbackend\Process\Service\Process::writeBlockedEntity) $entityId ", \BO\Zmsbackend\Log\Service\Log::ACTION_DELETED, $process, $useraccount);
726                }
727            }
728        }
729        return $status;
730    }
732    protected function writeRequestsToDb(\BO\Zmsentities\Process $process): void
733    {
734        // Beware of resolveReferences=0 to not delete the existing requests, except for queued processes
735        $hasRequests = ($process->requests && count($process->requests));
736        if ($hasRequests || 'queued' == $process->status) {
737            $this->deleteRequestsForProcessId($process->id);
738        }
739        if ($hasRequests) {
740            $query = new \BO\Zmsbackend\Request\Repository\XRequest(\BO\Zmsbackend\Query\Base::INSERT);
741            foreach ($process->requests as $request) {
742                if ($request->id >= 0) {
743        // allow deleting requests with a -1 request
744                    $query->addValues([
745                            'AnliegenID' => $request['id'],
746                            'source' => $request['source'],
747                            'BuergerID' => $process->id
748                        ]);
749                    $this->writeItem($query);
750                }
751            }
752        }
753    }
755    protected function deleteRequestsForProcessId(string|int $processId): bool
756    {
757        $status = false;
758        if (0 < $processId) {
759            $query = new \BO\Zmsbackend\Request\Repository\XRequest(\BO\Zmsbackend\Query\Base::DELETE);
760            $query->addConditionProcessId($processId);
761            $status = $this->deleteItem($query);
762        }
763        return $status;
764    }
766    public function readExpiredProcessList(\DateTimeInterface $expirationDate, int $limit = 500, int $resolveReferences = 0, ?int $offset = null)
767    {
768        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
769        $selectQuery
770            ->addEntityMapping()
771            ->addResolvedReferences($resolveReferences)
772            ->addConditionProcessDeleteInterval($expirationDate)
773            ->addConditionIgnoreSlots()
774            ->addLimit($limit, $offset);
775        $statement = $this->fetchStatement($selectQuery);
776        return $this->readList($statement, $resolveReferences);
777    }
781    public function readUnconfirmedProcessList(\DateTimeInterface $expirationDate, int $scopeId = 0, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
782    {
783        $selectQuery = $this->newDeleteListQuery();
784        $selectQuery
785            ->addConditionScopeId($scopeId)
786            ->addConditionProcessExpiredIPTimeStamp($expirationDate)
787            ->addConditionStatus('preconfirmed')
788            ->addConditionIgnoreSlots()
789            ->addLimit($limit, $offset);
790        return $this->readDeleteList($selectQuery);
791    }
793    public function readExpiredProcessListByStatus(\DateTimeInterface $expirationDate, string $status, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
794    {
795        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
796        $selectQuery
797            ->addEntityMapping()
798            ->addResolvedReferences($resolveReferences)
799            ->addConditionProcessDeleteBeforeDate($expirationDate)
800            ->addConditionStatus($status)
801            ->addConditionIgnoreSlots()
802            ->addLimit($limit, $offset);
803        $statement = $this->fetchStatement($selectQuery);
804        return $this->readList($statement, $resolveReferences);
805    }
810    public function readExpiredReservationsList(\DateTimeInterface $expirationDate, string|int $scopeId, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
811    {
812        $selectQuery = $this->newDeleteListQuery();
813        $selectQuery
814            ->addConditionScopeId($scopeId)
815            ->addConditionIsReserved()
816            ->addConditionProcessExpiredIPTimeStamp($expirationDate)
817            ->addConditionIgnoreSlots()
818            ->addLimit($limit, $offset);
819        return $this->readDeleteList($selectQuery);
820    }
822    protected function newDeleteListQuery(): \BO\Zmsbackend\Process\Repository\Process
823    {
824        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(
825            \BO\Zmsbackend\Query\Base::SELECT,
826            '',
827            false,
828            null,
829            ['delete-list']
830        );
831        $selectQuery->addDeleteListColumns();
832        return $selectQuery;
833    }
835    protected function readDeleteList(\BO\Zmsbackend\Process\Repository\Process $selectQuery): Collection
836    {
837        $statement = $this->fetchStatement($selectQuery);
838        $processList = new Collection();
839        while ($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
840            $processList->addEntity(new Entity([
841                'id' => $row['id'],
842                'status' => $row['status'],
843                'createTimestamp' => $row['createTimestamp'],
844            ]));
845        }
846        $statement->closeCursor();
847        return $processList;
848    }
850    public function readEmailReminderProcessListByInterval(\DateTimeInterface $now, \DateTimeInterface $lastRun, int $defaultReminderInMinutes, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
851    {
852        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
853        $selectQuery
854            ->addEntityMapping()
855            ->addResolvedReferences($resolveReferences)
856            ->addConditionProcessMailReminder($now, $lastRun, $defaultReminderInMinutes)
857            ->addConditionAssigned()
858            ->addConditionIgnoreSlots()
859            ->addConditionStatus('confirmed')
860            ->addLimit($limit, $offset);
861        $statement = $this->fetchStatement($selectQuery);
862        return $this->readList($statement, $resolveReferences)->withDepartmentHasMailFrom();
863    }
865    public function readDeallocateProcessList(\DateTimeInterface $now, int $limit = 500, ?int $offset = null, int $resolveReferences = 0)
866    {
867        $selectQuery = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
868        $selectQuery
869            ->addEntityMapping()
870            ->addResolvedReferences($resolveReferences)
871            ->addConditionDeallocate($now)
872            ->addConditionIgnoreSlots()
873            ->addLimit($limit, $offset);
874        $statement = $this->fetchStatement($selectQuery);
875        return $this->readList($statement, $resolveReferences);
876    }
878    public function isAppointmentAllowedWithSameMail(Entity $entity): bool
879    {
880        if (empty($entity->getClients()) || empty($entity->getClients()->getFirst())) {
881            return true;
882        }
883
884        $maxAppointmentsPerMail = $entity->scope->getAppointmentsPerMail();
885        $emailToCheck = $entity->getClients()->getFirst()->email;
886        if ($maxAppointmentsPerMail < 1 || empty($emailToCheck)) {
887            return true;
888        }
889
890        if ($this->isMailWhitelisted($emailToCheck, $entity->scope)) {
891            return true;
892        }
893
894        $processes = $this->readProcessListByMailAddress($entity->getClients()->getFirst()->email, $entity->scope->id);
895        $activeAppointments = 0;
896        foreach ($processes as $process) {
897            // Skip the process under change so list order cannot short-circuit the limit
898            // check (a reserved sibling with a lower id used to make preconfirm succeed).
899            if ($entity->id == $process->id) {
900                continue;
901            }
902
903            if (in_array($process->getStatus(), ['preconfirmed', 'confirmed'])) {
904                $activeAppointments++;
905                if ($activeAppointments >= $maxAppointmentsPerMail) {
906                    return false;
907                }
908            }
909        }
910
911        return true;
912    }
914    protected function isMailWhitelisted(string $email, ScopeEntity $scope): bool
915    {
916        $emailsWithNoLimit = explode(',', $scope->getWhitelistedMails());
917        if (empty($emailsWithNoLimit)) {
918            return false;
919        }
920
921        foreach ($emailsWithNoLimit as $whitelistedMail) {
922            $whitelistedMail = trim($whitelistedMail);
923            if ($email === $whitelistedMail) {
924                return true;
925            }
926
927            if (str_starts_with($whitelistedMail, '@') && str_contains($email, $whitelistedMail)) {
928                return true;
929            }
930        }
931
932        return false;
933    }
935    public function readProcessWithSameDayAndDisplayNumber(string|int $scopeId, string $displayNumber, string $date)
936    {
937        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
938        $query->addEntityMapping()
939            ->addResolvedReferences(1)
940            ->addConditionScopeId($scopeId)
941            ->addConditionDate($date)
942            ->addConditionDisplayNumber($displayNumber)
943            ->addLimit(1);
944
945        $process = $this->fetchOne($query, new Entity());
946
947        return $this->readResolvedReferences($process, 1);
948    }
950    public function readProcessListByExternalUserId(string $externalUserId, ?int $filterId = null, ?string $status = null, int $resolveReferences = 0, int $limit = 1000): Collection
951    {
952        $query = new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT);
953        $query
954            ->addResolvedReferences($resolveReferences)
955            ->addEntityMapping()
956            ->addConditionExternalUserId($externalUserId);
957        if (!is_null($filterId)) {
958            $query->addConditionProcessId($filterId);
959        }
960        if (!is_null($status)) {
961            $query->addConditionStatus($status);
962        }
963        $query
964            ->addLimit($limit);
965
966        $statement = $this->fetchStatement($query);
967        $processList = $this->readProcessesWithoutRequests($statement);
968        return $this->attachAllRequestsInOneQuery($processList, (int) $resolveReferences);
969    }
971    public function readAssignedWorkstationIdForUpdate(int $processId): ?int
972    {
973        $query = (new \BO\Zmsbackend\Process\Repository\Process(\BO\Zmsbackend\Query\Base::SELECT))->getLockAssignedWorkstationId();
974        $value = $this->fetchValue($query, ['processId' => $processId]);
975
976        if ($value === false || $value === null) {
977            return null;
978        }
979
980        return (int) $value;
981    }

Inherited from BO\Zmsbackend\Base

38    public function __construct(?Connection\Pdo $writeConnection = null, ?Connection\Pdo $readConnection = null)
39    {
40        $this->writeDb = $writeConnection;
41        $this->readDb = $readConnection;
42    }
44    public static function init(?Connection\Pdo $writeConnection = null, ?Connection\Pdo $readConnection = null): static
45    {
46        $instance = new static($writeConnection, $readConnection);
47        return $instance;
48    }
50    public function getWriter(): Connection\Pdo
51    {
52        if (null === $this->writeDb) {
53            $this->writeDb = Connection\Select::getWriteConnection();
54            $this->readDb = $this->writeDb;
55        }
56        return $this->writeDb;
57    }
59    public function getReader(): Connection\Pdo
60    {
61        if (null !== $this->writeDb) {
62            // if readDB gets a reset, still use writeDB
63            return $this->writeDb;
64        }
65        if (null === $this->readDb) {
66            $this->readDb = Connection\Select::getReadConnection();
67        }
68        return $this->readDb;
69    }
71    public function fetchPreparedStatement(Query\Base|string $query)
72    {
73        $sql = "$query";
74        $reader = $this->getReader();
75        if (spl_object_hash($reader) != static::$preparedConnectionId) {
76            // do not use prepared statements on a different connection
77            static::$preparedCache = [];
78            static::$preparedConnectionId = spl_object_hash($reader);
79        }
80        if (!isset(static::$preparedCache[$sql])) {
81            $prepared = $this->getReader()->prepare($sql);
82            static::$preparedCache[$sql] = $prepared;
83        }
84        return static::$preparedCache[$sql];
85    }
87    public function startExecute(\PDOStatement $statement, array $parameters)
88    {
89        $statement = static::pdoExceptionHandler(function () use ($statement, $parameters) {
90            $statement->execute($parameters);
91            return $statement;
92        });
93        return $statement;
94    }
96    protected static function pdoExceptionHandler(\Closure $pdoFunction, array $parameters = [])
97    {
98        try {
99            $statement = $pdoFunction($parameters);
100        } catch (\PDOException $pdoException) {
101            if (stripos($pdoException->getMessage(), 'Lock wait timeout') !== false) {
102                throw new \BO\Zmsbackend\Exception\Pdo\LockTimeout();
103            }
104            //@codeCoverageIgnoreStart
105            if (stripos($pdoException->getMessage(), 'Deadlock found') !== false) {
106                throw new \BO\Zmsbackend\Exception\Pdo\DeadLockFound();
107            }
108            //@codeCoverageIgnoreEnd
109            $message = "SQL: "
110                . " Err: "
111                . $pdoException->getMessage()
112                //. " || Statement: "
113                //.$statement->queryString
114                //." || Parameters=". var_export($parameters, true)
115                ;
116            throw new \BO\Zmsbackend\Exception\Pdo\PDOFailed($message, 0, $pdoException);
117        }
118        return $statement;
119    }
121    public function fetchStatement(Query\Base $query)
122    {
123        $parameters = $query->getParameters();
124        $statement = $this->startExecute($this->fetchPreparedStatement($query), $parameters);
125        return $statement;
126    }
133    public function fetchOne(Query\Base $query, \BO\Zmsentities\Schema\Entity $entity)
134    {
135        $statement = $this->fetchStatement($query);
136        $data = $statement->fetch(\PDO::FETCH_ASSOC);
137        if ($data) {
138            $entity->exchangeArray($query->postProcessJoins($data));
139            $entity->setResolveLevel($query->getResolveLevel());
140        }
141        $statement->closeCursor();
142        return $entity;
143    }
145    public function fetchRow(Query\Base|string $query, array|null $parameters = null)
146    {
147        return static::pdoExceptionHandler(function () use ($query, $parameters) {
148            $prepared = $this->fetchPreparedStatement($query);
149            $prepared->execute($parameters);
150            $row = $prepared->fetch(\PDO::FETCH_ASSOC);
151            $prepared->closeCursor();
152            return $row;
153        });
154    }
156    public function fetchValue(Query\Base|string $query, array|null $parameters = null)
157    {
158        return static::pdoExceptionHandler(function () use ($query, $parameters) {
159            $prepared = $this->fetchPreparedStatement($query);
160            $prepared->execute($parameters);
161            $value = $prepared->fetchColumn();
162            $prepared->closeCursor();
163            return $value;
164        });
165    }
167    public function fetchAll(Query\Base|string $query, array|null $parameters = null)
168    {
169        return static::pdoExceptionHandler(function () use ($query, $parameters) {
170            $prepared = $this->fetchPreparedStatement($query);
171            $prepared->execute($parameters);
172            $list = $prepared->fetchAll(\PDO::FETCH_ASSOC);
173            $prepared->closeCursor();
174            return $list;
175        });
176    }
178    public function fetchHandle(Query\Base|string $query, array|null $parameters = null)
179    {
180        return static::pdoExceptionHandler(function () use ($query, $parameters) {
181            $prepared = $this->fetchPreparedStatement($query);
182            $prepared->execute($parameters);
183            return $prepared;
184        });
185    }
187    public function fetchList(Query\Base $query, \BO\Zmsentities\Schema\Entity $entity, array|\ArrayAccess $resultList = [])
188    {
189        $statement = $this->fetchStatement($query);
190        while ($data = $statement->fetch(\PDO::FETCH_ASSOC)) {
191            $dataEntity = clone $entity;
192            $dataEntity->exchangeArray($query->postProcessJoins($data));
193            $dataEntity->setResolveLevel($query->getResolveLevel());
194            $resultList[] = $dataEntity;
195        }
196        $statement->closeCursor();
197        return $resultList;
198    }
206    public function writeItem(Query\Base $query)
207    {
208        return static::pdoExceptionHandler(function () use ($query) {
209            $this->getWriter(); //Switch to writer for write/delete
210            $statement = $this->fetchPreparedStatement($query);
211            $status = $statement->execute($query->getParameters());
212            $statement->closeCursor();
213            return $status;
214        });
215    }
221    public function deleteItem(Query\Base $query)
222    {
223        return $this->writeItem($query);
224    }
226    public function perform(string $sql, array|null $parameters = null)
227    {
228        return static::pdoExceptionHandler(function () use ($sql, $parameters) {
229            $this->getWriter(); //Switch to writer for perform
230            $prepared = $this->fetchPreparedStatement($sql);
231            $status = $prepared->execute($parameters);
232            $prepared->closeCursor();
233            return $status;
234        });
235    }
237    public function fetchAffected(string $sql, array|null $parameters = null)
238    {
239        return static::pdoExceptionHandler(function () use ($sql, $parameters) {
240            $this->getWriter(); //Switch to writer for perform
241            $prepared = $this->fetchPreparedStatement($sql);
242            $prepared->execute($parameters);
243            $count = $prepared->rowCount();
244            $prepared->closeCursor();
245            return $count;
246        });
247    }
268    public function hashStringValue(string $value, ?callable $callable = null): string
269    {
270        if ($callable === null) {
271            $callable = 'sha1';
272        }
273
274        if (is_callable($callable)) {
275            $hash = $callable($value);
276
277            if (is_string($callable)) {
278                return $callable . ':' . $hash;
279            }
280            if ($callable instanceof \Closure) {
281                return 'closure:' . $hash;
282            }
283            // else
284            return 'custom:' . $hash;
285        }
286
287        throw new \InvalidArgumentException('hashStringValue() should be called with a callable as second parameter.');
288    }