Lines 91.53% 508 / 555
Methods 74.54% 41 / 55
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 readEntity 100.00% 16 / 16 100.00% 1 / 1 8
 readEntitiesByIds 92.85% 26 / 28 0.00% 0 / 1 10.04
 readResolvedReferences 100.00% 4 / 4 100.00% 1 / 1 2
 readByClusterId 100.00% 38 / 38 100.00% 1 / 1 12
 readByProviderId 78.12% 25 / 32 0.00% 0 / 1 12.27
 readByRequestId 100.00% 7 / 7 100.00% 1 / 1 3
 readByDepartmentId 97.14% 34 / 35 0.00% 0 / 1 12
 readListBySource 0.00% 0 / 7 0.00% 0 / 1 6
 testSource 0.00% 0 / 2 0.00% 0 / 1 6
 readCollection 0.00% 0 / 6 0.00% 0 / 1 6
 readList 94.73% 18 / 19 0.00% 0 / 1 10.01
 readDurationList 100.00% 17 / 17 100.00% 1 / 1 2
 readIsOpened 100.00% 5 / 5 100.00% 1 / 1 2
 readIsEnabled 100.00% 10 / 10 100.00% 1 / 1 3
 readWaitingNumberUpdated 100.00% 9 / 9 100.00% 1 / 1 3
 readDisplayNumberUpdated 0.00% 0 / 7 0.00% 0 / 1 2
 readIsGivenNumberInContingent 100.00% 4 / 4 100.00% 1 / 1 2
 readQueueList 100.00% 12 / 12 100.00% 1 / 1 2
 readWithWorkstationCount 100.00% 9 / 9 100.00% 1 / 1 2
 readQueueListWithWaitingTime 66.66% 6 / 9 0.00% 0 / 1 3.33
 readScopesQueueListWithWaitingTime 91.66% 11 / 12 0.00% 0 / 1 3.01
 readListWithScopeAdminEmail 100.00% 13 / 13 100.00% 1 / 1 4
 writeEntity 100.00% 10 / 10 100.00% 1 / 1 1
 updateEntity 100.00% 10 / 10 100.00% 1 / 1 1
 replacePreferences 100.00% 7 / 7 100.00% 1 / 1 4
 updateGhostWorkstationCount 100.00% 8 / 8 100.00% 1 / 1 1
 updateEmergency 100.00% 9 / 9 100.00% 1 / 1 1
 writeImageData 93.33% 14 / 15 0.00% 0 / 1 4.00
 readImageData 100.00% 10 / 10 100.00% 1 / 1 2
 deleteImage 100.00% 4 / 4 100.00% 1 / 1 1
 deleteEntity 100.00% 11 / 11 100.00% 1 / 1 3
 deletePreferences 100.00% 6 / 6 100.00% 1 / 1 3
 readDepartmentIdByScopeId 100.00% 2 / 2 100.00% 1 / 1 1
 readClusterIdsByScopeId 100.00% 3 / 3 100.00% 1 / 1 1
 removeCacheByContext 95.00% 38 / 40 0.00% 0 / 1 22
 removeCache 0.00% 0 / 2 0.00% 0 / 1 6
 [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
16class Scope extends \BO\Zmsbackend\Base
17{
18    public static $cache = [ ];
19
20    /**
21     * @param false|int|string $scopeId
22     */
23    public function readEntity(string|int|false $scopeId, int $resolveReferences = 0, bool $disableCache = false): ?Entity
24    {
25        $cacheKey = "scope-$scopeId-$resolveReferences";
26
27        if (!$disableCache && \App::$cache && \App::$cache->has($cacheKey)) {
28            $scope = \App::$cache->get($cacheKey);
29        }
30
31        if (empty($scope)) {
32            $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
33            $query->addEntityMapping()
34                ->addResolvedReferences($resolveReferences)
35                ->addConditionScopeId($scopeId);
36            $scope = $this->fetchOne($query, new Entity());
37            if (! $scope->hasId()) {
38                return null;
39            }
40
41            if (\App::$cache) {
42                \App::$cache->set($cacheKey, $scope);
43                if (\App::$log) {
44                    \App::$log->info('Scope cache set', ['cache_key' => $cacheKey]);
45                }
46            }
47        }
48
49        return $this->readResolvedReferences($scope, $resolveReferences, $disableCache);
50    }
51
52    public function readEntitiesByIds(array $scopeIds, int $resolveReferences = 0, bool $disableCache = false): array
53    {
54        $scopeIds = array_values(array_unique(array_filter(array_map('intval', $scopeIds))));
55        if (!$scopeIds) {
56            return [];
57        }
58
59        $result  = [];
60        $missing = [];
61        foreach ($scopeIds as $scopeId) {
62            $cacheKey = "{$scopeId}-{$resolveReferences}";
63            if (!$disableCache && array_key_exists($cacheKey, self::$cache)) {
64                $result[$scopeId] = self::$cache[$cacheKey];
65            } else {
66                $missing[] = $scopeId;
67            }
68        }
69
70        if ($missing) {
71            $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
72            $query
73                ->addEntityMapping()
74                ->addResolvedReferences($resolveReferences)
75                ->addConditionScopeIds($missing);
76
77            $fetched = $this->fetchList($query, new Entity());
78            foreach ($fetched as $entity) {
79                if (!$entity->hasId()) {
80                    continue;
81                }
82                $entity = $this->readResolvedReferences($entity, $resolveReferences);
83                $result[$entity->id] = $entity;
84                self::$cache["{$entity->id}-{$resolveReferences}"] = $entity;
85            }
86        }
87
88        $ordered = [];
89        foreach ($scopeIds as $id) {
90            if (isset($result[$id])) {
91                $ordered[$id] = $result[$id];
92            }
93        }
94
95        return $ordered;
96    }
97
98    /**
99     * @return \BO\Zmsentities\Schema\Entity
100     */
101    #[\Override]
102    public function readResolvedReferences(
103        \BO\Zmsentities\Schema\Entity $entity,
104        int $resolveReferences,
105        bool $disableCache = false
106    ) {
107        if (0 < $resolveReferences) {
108            $entity['dayoff'] = (new \BO\Zmsbackend\Dayoff\Service\DayOff())->readByScopeId($entity->id, $disableCache);
109            $entity['closure'] = (new \BO\Zmsbackend\Availability\Service\Closure())->readByScopeId($entity->id, $disableCache);
110        }
111        return $entity;
112    }
113
114    public function readByClusterId(
115        string|int $clusterId,
116        int $resolveReferences = 0,
117        bool $disableCache = false
118    ): Collection {
119        $cacheKey = "scopeReadByClusterId-$clusterId-$resolveReferences";
120
121        if (!$disableCache && \App::$cache && \App::$cache->has($cacheKey)) {
122            $result = \App::$cache->get($cacheKey);
123        }
124
125        if (empty($result)) {
126            if ($resolveReferences > 0) {
127                $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
128                $query->addEntityMapping()
129                    ->addResolvedReferences($resolveReferences - 1)
130                    ->addConditionClusterId($clusterId);
131                $result = $this->fetchList($query, new Entity());
132            } else {
133                $result = $this->getReader()->perform(
134                    (new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT))->getQuerySimpleClusterMatch(),
135                    [$clusterId]
136                );
137            }
138
139            if (\App::$cache && !($result instanceof \PDOStatement)) {
140                \App::$cache->set($cacheKey, $result);
141                if (\App::$log) {
142                    \App::$log->info('Scope cache set', ['cache_key' => $cacheKey]);
143                }
144            }
145        }
146
147        $scopeList = new Collection();
148        if (!$result) {
149            return $scopeList;
150        }
151
152        foreach ($result as $entity) {
153            if (0 == $resolveReferences) {
154                $entity = new Entity(
155                    array(
156                        'id' => $entity['id'],
157                        'contact' => ['name' => $entity['contact__name']],
158                        'shortName' => $entity['shortName'] ?? '',
159                        '$ref' => '/scope/' . $entity['id'] . '/'
160                    )
161                );
162                $scopeList->addEntity($entity);
163            } else {
164                $scopeList->addEntity($this->readResolvedReferences(
165                    $entity,
166                    $resolveReferences - 1,
167                    $disableCache
168                ));
169            }
170        }
171
172        return $scopeList;
173    }
174
175    public function readByProviderId(string|int $providerId, int $resolveReferences = 0, bool $disableCache = false): Collection
176    {
177        $cacheKey = "scopeReadByProviderId-$providerId-$resolveReferences";
178
179        if (!$disableCache && \App::$cache && \App::$cache->has($cacheKey)) {
180            $result = \App::$cache->get($cacheKey);
181        }
182
183        if (empty($result)) {
184            $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
185            $query->addEntityMapping()
186                ->addResolvedReferences($resolveReferences)
187                ->addConditionProviderId($providerId);
188            $result = $this->fetchList($query, new Entity());
189
190            if (\App::$cache) {
191                \App::$cache->set($cacheKey, $result);
192                if (\App::$log) {
193                    \App::$log->info('Scope cache set', ['cache_key' => $cacheKey]);
194                }
195            }
196        }
197
198        $scopeList = new Collection();
199        if (count($result)) {
200            foreach ($result as $entity) {
201                if (0 == $resolveReferences) {
202                    $entity = new Entity(
203                        array(
204                            'id' => $entity->id,
205                            '$ref' => '/scope/' . $entity->id . '/'
206                        )
207                    );
208                    $scopeList->addEntity($entity);
209                } else {
210                    if ($entity instanceof Entity) {
211                        $entity = $this->readResolvedReferences(
212                            $entity,
213                            $resolveReferences - 1,
214                            $disableCache
215                        );
216                        $scopeList->addEntity($entity);
217                    }
218                }
219            }
220        }
221
222        return $scopeList;
223    }
224
225    public function readByRequestId(string|int $requestId, string $source, int $resolveReferences = 0): Collection
226    {
227        $scopeList = new Collection();
228        $providerList = (new \BO\Zmsbackend\Provider\Service\Provider())->readListBySource($source, 0, true, $requestId);
229
230        foreach ($providerList as $provider) {
231            $scopeListByProvider = $this->readByProviderId($provider->getId(), $resolveReferences);
232            if ($scopeListByProvider->count()) {
233                $scopeList->addList($scopeListByProvider);
234            }
235        }
236        return $scopeList->withUniqueScopes();
237    }
238
239    public function readByDepartmentId(int $departmentId, int $resolveReferences = 0, bool $disableCache = false): Collection
240    {
241        $cacheKey = "scopeReadByDepartmentId-$departmentId-$resolveReferences";
242
243        if (!$disableCache && \App::$cache && \App::$cache->has($cacheKey)) {
244            $result = \App::$cache->get($cacheKey);
245        }
246
247        $scopeList = new Collection();
248
249        if (empty($result)) {
250            if ($resolveReferences > 0) {
251                $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
252                $query->addEntityMapping()
253                    ->addResolvedReferences($resolveReferences)
254                    ->addConditionDepartmentId($departmentId);
255                $result = $this->fetchList($query, new Entity());
256
257                if (\App::$cache) {
258                    \App::$cache->set($cacheKey, $result);
259                    if (\App::$log) {
260                        \App::$log->info('Scope cache set', ['cache_key' => $cacheKey]);
261                    }
262                }
263            } else {
264                $result = $this->getReader()->perform(
265                    (new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT))->getQuerySimpleDepartmentMatch(),
266                    [$departmentId]
267                );
268            }
269        }
270
271        if ($result) {
272            foreach ($result as $entity) {
273                if (0 == $resolveReferences) {
274                    $entity = new Entity(
275                        array(
276                            'id' => $entity['id'],
277                            'contact' => ['name' => $entity['contact__name']],
278                            'shortName' => $entity['shortName'] ?? '',
279                            '$ref' => '/scope/' . $entity['id'] . '/'
280                        )
281                    );
282                    $scopeList->addEntity($entity);
283                } else {
284                    if ($entity instanceof Entity) {
285                        $entity = $this->readResolvedReferences($entity, $resolveReferences, $disableCache);
286                        $scopeList->addEntity($entity);
287                    }
288                }
289            }
290        }
291
292        return $scopeList;
293    }
294    /** @psalm-api */
295    public function readListBySource(string $source, int $resolveReferences = 0)
296    {
297        $this->testSource($source);
298        $query = new \BO\Zmsbackend\Request\Repository\Request(\BO\Zmsbackend\Query\Base::SELECT);
299        $query->setResolveLevel($resolveReferences);
300        $query->addConditionRequestSource($source);
301        $query->addEntityMapping();
302        $requestList = $this->readCollection($query);
303        return ($requestList->count()) ? $requestList->sortByCustomKey('id') : $requestList;
304    }
305
306    /**
307     * @return void
308     */
309    protected function testSource(string $source)
310    {
311        if (! (new \BO\Zmsbackend\Source\Service\Source())->readEntity($source)) {
312            throw new \BO\Zmsbackend\Source\Exception\UnknownDataSource();
313        }
314    }
315
316    protected function readCollection(\BO\Zmsbackend\Request\Repository\Request $query): Collection
317    {
318        $requestList = new Collection();
319        $statement = $this->fetchStatement($query);
320        while ($requestData = $statement->fetch(\PDO::FETCH_ASSOC)) {
321            $request = new Entity($query->postProcessJoins($requestData));
322            $requestList->addEntity($request);
323        }
324        return $requestList;
325    }
326
327    public function readList(int $resolveReferences = 0, bool $disableCache = false): Collection
328    {
329        $cacheKey = "scopeReadList-$resolveReferences";
330
331        if (!$disableCache && \App::$cache && \App::$cache->has($cacheKey)) {
332            $result = \App::$cache->get($cacheKey);
333        }
334
335        if (empty($result)) {
336            $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
337            $query->addEntityMapping()
338                ->addResolvedReferences($resolveReferences);
339            $result = $this->fetchList($query, new Entity());
340
341            if (\App::$cache) {
342                \App::$cache->set($cacheKey, $result);
343                if (\App::$log) {
344                    \App::$log->info('Scope cache set', ['cache_key' => $cacheKey]);
345                }
346            }
347        }
348
349        $scopeList = new Collection();
350        if (count($result)) {
351            foreach ($result as $entity) {
352                if ($entity instanceof Entity) {
353                    $entity = $this->readResolvedReferences($entity, $resolveReferences);
354                    $scopeList->addEntity($entity);
355                }
356            }
357        }
358        return $scopeList;
359    }
360
361    /**
362     * Id and durations for the delete crons. readList() joins department, mail, and provider.
363     */
364    public function readDurationList(): Collection
365    {
366        $rows = $this->fetchAll(
367            'SELECT `StandortID` AS `id`, `aktivierungsdauer` AS `activationDuration`,'
368            . ' `reservierungsdauer` AS `reservationDuration`'
369            . ' FROM `' . \BO\Zmsbackend\Query\Scope::TABLE . '`'
370        );
371        $scopeList = new Collection();
372        foreach ($rows as $row) {
373            $scopeList->addEntity(new Entity([
374                'id' => $row['id'],
375                'preferences' => [
376                    'appointment' => [
377                        'activationDuration' => $row['activationDuration'],
378                        'reservationDuration' => $row['reservationDuration'],
379                    ],
380                ],
381            ]));
382        }
383        return $scopeList;
384    }
385
386    public function readIsOpened(string|int $scopeId, \DateTimeInterface $now): bool
387    {
388        $isOpened = false;
389        $availabilityList = (new \BO\Zmsbackend\Availability\Service\Availability())->readOpeningHoursListByDate($scopeId, $now, 2);
390        if ($availabilityList->isOpened($now)) {
391            $isOpened = true;
392        }
393        return $isOpened;
394    }
395
396    public function readIsEnabled(string $scopeId, \DateTimeInterface $now): bool
397    {
398        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
399        $query->addEntityMapping()
400            ->setResolveLevel(0)
401            ->addConditionScopeId($scopeId);
402        $scope = $this->fetchOne($query, new Entity());
403        return (
404            $this->readIsOpened($scopeId, $now) &&
405            $this->readIsGivenNumberInContingent($scopeId) &&
406            ! $scope->getStatus('ticketprinter', 'deactivated')
407        );
408    }
409
410    public function readWaitingNumberUpdated(string|int $scopeId, \DateTimeInterface $dateTime, bool $respectContingent = true)
411    {
412        if (! $this->readIsGivenNumberInContingent($scopeId) && $respectContingent) {
413            throw new \BO\Zmsbackend\Scope\Exception\GivenNumberCountExceeded();
414        }
415        $this->perform(
416            (new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT))->getQueryLastWaitingNumber(),
417            ['scope_id' => $scopeId]
418        );
419        $entity = $this->readEntity($scopeId, 0, true)->updateStatusQueue($dateTime);
420        $scope = $this->updateEntity($scopeId, $entity);
421        return $scope->getStatus('queue', 'lastGivenNumber');
422    }
423
424    public function readDisplayNumberUpdated(string|int $scopeId)
425    {
426        $this->perform(
427            (new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT))->getQueryLastDisplayNumber(),
428            ['scope_id' => $scopeId]
429        );
430        $entity = $this->readEntity($scopeId, 0, true)->incrementDisplayNumber();
431        $scope = $this->updateEntity($scopeId, $entity);
432        return $scope->getStatus('queue', 'lastDisplayNumber');
433    }
434
435    public function readIsGivenNumberInContingent(string|int $scopeId): bool
436    {
437        $isInContingent = $this->getReader()
438            ->fetchValue((new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT))
439            ->getQueryGivenNumbersInContingent(), ['scope_id' => $scopeId]);
440        return ($isInContingent) ? true : false;
441    }
442
443    public function readQueueList(array $scopeIds, \DateTimeInterface $dateTime, int $resolveReferences = 0, array $withEntities = []): \BO\Zmsentities\Collection\QueueList
444    {
445        if ($resolveReferences > 0) {
446            $queueList = (new \BO\Zmsbackend\Process\Service\Process())
447                ->readProcessListByScopesAndTime(
448                    $scopeIds,
449                    $dateTime,
450                    $resolveReferences - 1,
451                    $withEntities
452                )
453                ->toQueueList($dateTime);
454        } else {
455            $queueList = (new \BO\Zmsbackend\Queue\Service\Queue())
456                ->readListByScopeAndTime($scopeIds, $dateTime, $resolveReferences);
457        }
458
459        return $queueList->withSortedArrival();
460    }
461
462    /**
463     * @param string[] $withEntities
464     *
465     */
466    public function readWithWorkstationCount(string $scopeId, \DateTimeInterface $dateTime, int $resolveReferences = 0, array $withEntities = [])
467    {
468        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT, '', false, null, $withEntities);
469        $query
470            ->addEntityMapping()
471            ->addConditionScopeId($scopeId)
472            ->addResolvedReferences($resolveReferences)
473            ->addSelectWorkstationCount($dateTime);
474        $scope = $this->fetchOne($query, new Entity());
475        $scope = $this->readResolvedReferences($scope, $resolveReferences);
476        return ($scope->hasId()) ? $scope : null;
477    }
478
479    /**
480     * @param string[] $withEntities
481     *
482     */
483    public function readQueueListWithWaitingTime(\BO\Zmsentities\Useraccount\AccessInterface $scope, \DateTimeInterface|false $dateTime, int $resolveReferences = 0, array $withEntities = [])
484    {
485        $timeAverage = (int) $scope->getPreference('queue', 'processingTimeAverage');
486        if ($timeAverage <= 0) {
487            $scope = (new \BO\Zmsbackend\Scope\Service\Scope())->readEntity($scope->id);
488            $timeAverage = (int) $scope->getPreference('queue', 'processingTimeAverage');
489        }
490        if ($timeAverage <= 0) {
491            $timeAverage = 12;
492        }
493        $queueList = $this->readQueueList([$scope->id], $dateTime, $resolveReferences, $withEntities);
494        $workstationCount = $scope->getCalculatedWorkstationCount();
495        return $queueList->withEstimatedWaitingTime($timeAverage, $workstationCount, $dateTime);
496    }
497
498    public function readScopesQueueListWithWaitingTime(Collection $scopes, \DateTimeInterface $dateTime, int $resolveReferences = 0, array $withEntities = [])
499    {
500        $timeSum = 0;
501        $workstationCount = 0;
502        $scopeIds = [];
503        foreach ($scopes as $scope) {
504            $timeSum += $scope->getPreference('queue', 'processingTimeAverage');
505            $workstationCount += $scope->getCalculatedWorkstationCount();
506            $scopeIds[] = $scope->id;
507        }
508
509        $timeAverage = (int) round($timeSum / $scopes->count());
510        if ($timeAverage <= 0) {
511            $timeAverage = 12;
512        }
513        $queueList = $this->readQueueList($scopeIds, $dateTime, $resolveReferences, $withEntities);
514
515        return $queueList->withEstimatedWaitingTime($timeAverage, $workstationCount, $dateTime);
516    }
517
518    public function readListWithScopeAdminEmail(int $resolveReferences = 0): Collection
519    {
520        $scopeList = new Collection();
521        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
522        $query
523            ->addEntityMapping()
524            ->addConditionWithAdminEmail()
525            ->addResolvedReferences($resolveReferences);
526        $result = $this->fetchList($query, new Entity());
527        if (count($result)) {
528            foreach ($result as $entity) {
529                if ($entity instanceof Entity) {
530                    $entity = $this->readResolvedReferences($entity, $resolveReferences);
531                    $scopeList->addEntity($entity);
532                }
533            }
534        }
535        return $scopeList;
536    }
537
538    public function writeEntity(\BO\Zmsentities\Scope $entity, string|int $parentId): Entity|null
539    {
540        self::$cache = [];
541        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::INSERT);
542        $values = $query->reverseEntityMapping($entity, $parentId);
543        $query->addValues($values);
544        $this->writeItem($query);
545        $lastInsertId = $this->getWriter()
546            ->lastInsertId();
547        $this->replacePreferences($entity);
548
549        $this->removeCacheByContext($entity, $parentId);
550
551        return $this->readEntity($lastInsertId);
552    }
553
554    public function updateEntity(string|int $scopeId, \BO\Zmsentities\Scope $entity, int $resolveReferences = 0): Entity|null
555    {
556        self::$cache = [];
557
558        $departmentId = $this->readDepartmentIdByScopeId($scopeId);
559
560        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::UPDATE);
561        $query->addConditionScopeId($scopeId);
562        $values = $query->reverseEntityMapping($entity);
563        $query->addValues($values);
564        $this->writeItem($query);
565        $this->replacePreferences($entity);
566
567        $this->removeCacheByContext($entity, $departmentId);
568
569        return $this->readEntity($scopeId, $resolveReferences, true);
570    }
571
572    public function replacePreferences(\BO\Zmsentities\Scope $entity): void
573    {
574        if (isset($entity['preferences'])) {
575            $preferenceQuery = new \BO\Zmsbackend\Preferences\Service\Preferences();
576            $entityName = 'scope';
577            $entityId = $entity['id'];
578            foreach ($entity['preferences'] as $groupName => $groupValues) {
579                foreach ($groupValues as $name => $value) {
580                    $preferenceQuery->replaceProperty($entityName, $entityId, $groupName, $name, $value);
581                }
582            }
583        }
584    }
585
586    public function updateGhostWorkstationCount(\BO\Zmsentities\Scope $entity, \DateTimeInterface $dateTime): Entity
587    {
588        $departmentId = $this->readDepartmentIdByScopeId($entity->id);
589
590        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::UPDATE);
591        $query->addConditionScopeId($entity->id);
592        $values = $query->setGhostWorkstationCountEntityMapping($entity, $dateTime);
593        $query->addValues($values);
594        $this->writeItem($query);
595
596        $this->removeCacheByContext($entity, $departmentId);
597
598        return $entity;
599    }
600
601    public function updateEmergency(string|int $scopeId, \BO\Zmsentities\Scope $entity): Entity|null
602    {
603        self::$cache = [];
604        $departmentId = $this->readDepartmentIdByScopeId($scopeId);
605
606        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::UPDATE);
607        $query->addConditionScopeId($scopeId);
608        $values = $query->setEmergencyEntityMapping($entity);
609        $query->addValues($values);
610        $this->writeItem($query);
611
612        $this->removeCacheByContext($entity, $departmentId);
613
614        return $this->readEntity($scopeId, 0, true);
615    }
616
617    public function writeImageData(string|int $scopeId, \BO\Zmsentities\Mimepart $entity): \BO\Zmsentities\Mimepart
618    {
619        if ($entity->mime && $entity->content) {
620            $this->deleteImage($scopeId);
621            $extension = $entity->getExtension();
622            if ($extension == 'jpeg') {
623                $extension = 'jpg'; //compatibility ZMS1
624            }
625            $imageName = 's_' . $scopeId . '_bild.' . $extension;
626            $this->getWriter()->perform(
627                (new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::REPLACE))->getQueryWriteImageData(),
628                array(
629                    'imagename' => $imageName,
630                    'imagedata' => $entity->content
631                )
632            );
633        }
634        $entity->id = $scopeId;
635        return $entity;
636    }
637
638    public function readImageData(string|int $scopeId): \BO\Zmsentities\Mimepart
639    {
640        $imageName = 's_' . $scopeId . '_bild';
641        $imageData = new \BO\Zmsentities\Mimepart();
642        $fileData = $this->getReader()->fetchAll(
643            (new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT))->getQueryReadImageData(),
644            ['imagename' => "$imageName%"]
645        );
646        if ($fileData) {
647            $imageData->content = $fileData[0]['imagecontent'];
648            $imageData->mime = pathinfo($fileData[0]['imagename'])['extension'];
649        }
650        return $imageData;
651    }
652
653    public function deleteImage(string|int $scopeId)
654    {
655        $imageName = 's_' . $scopeId . '_bild';
656        return $this->perform((new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::DELETE))->getQueryDeleteImage(), array(
657            'imagename' => "$imageName%"
658        ));
659    }
660
661    public function deleteEntity(string|int $scopeId): Entity|null
662    {
663        $processListCount = (new \BO\Zmsbackend\Process\Service\Process())->readProcessListCountByScope($scopeId);
664        if (0 < $processListCount) {
665            throw new \BO\Zmsbackend\Scope\Exception\ScopeHasProcesses();
666        }
667        self::$cache = [];
668
669        $departmentId = $this->readDepartmentIdByScopeId($scopeId);
670
671        $entity = $this->readEntity($scopeId);
672        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::DELETE);
673        $query->addConditionScopeId($scopeId);
674        $this->deletePreferences($entity);
675
676        $this->removeCacheByContext($entity, $departmentId);
677
678        return ($this->deleteItem($query)) ? $entity : null;
679    }
680
681    public function deletePreferences(\BO\Zmsentities\Scope $entity): void
682    {
683        $preferenceQuery = new \BO\Zmsbackend\Preferences\Service\Preferences();
684        $entityName = 'scope';
685        $entityId = $entity['id'];
686        foreach ($entity['preferences'] as $groupName => $groupValues) {
687            foreach (array_keys($groupValues) as $name) {
688                $preferenceQuery->deleteProperty($entityName, $entityId, $groupName, $name);
689            }
690        }
691    }
692
693    public function readDepartmentIdByScopeId(int $scopeId)
694    {
695        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
696        return $this->getReader()->fetchValue($query->getQueryDepartmentIdByScopeId(), [$scopeId]);
697    }
698
699    public function readClusterIdsByScopeId(string|int $scopeId): array
700    {
701        $query = new \BO\Zmsbackend\Query\Scope(\BO\Zmsbackend\Query\Base::SELECT);
702        $result = $this->getReader()->fetchAll($query->getQueryClusterIdsByScopeId(), [$scopeId]);
703        return array_column($result, 'clusterID');
704    }
705
706    /**
707     * @return void
708     */
709    public function removeCacheByContext(Entity $scope, int|string|null $departmentId = null)
710    {
711        if (!\App::$cache) {
712            return;
713        }
714
715        $invalidatedKeys = [];
716
717        // Invalidate scope entity cache for all resolveReferences levels (0, 1, 2)
718        if (isset($scope->id)) {
719            for ($resolveReferences = 0; $resolveReferences <= 2; $resolveReferences++) {
720                $key = "scope-{$scope->id}-{$resolveReferences}";
721                if (\App::$cache->has($key)) {
722                    \App::$cache->delete($key);
723                    $invalidatedKeys[] = $key;
724                }
725            }
726        }
727
728        // Invalidate scope list cache for all resolveReferences levels (0, 1, 2)
729        for ($resolveReferences = 0; $resolveReferences <= 2; $resolveReferences++) {
730            $key = "scopeReadList-{$resolveReferences}";
731            if (\App::$cache->has($key)) {
732                \App::$cache->delete($key);
733                $invalidatedKeys[] = $key;
734            }
735        }
736
737        // Invalidate scopeReadByDepartmentId cache for all resolveReferences levels (0, 1, 2)
738        if ($departmentId) {
739            for ($resolveReferences = 0; $resolveReferences <= 2; $resolveReferences++) {
740                $key = "scopeReadByDepartmentId-{$departmentId}-{$resolveReferences}";
741                if (\App::$cache->has($key)) {
742                    \App::$cache->delete($key);
743                    $invalidatedKeys[] = $key;
744                }
745            }
746        }
747
748        // Invalidate scopeReadByClusterId cache for all clusters containing this scope
749        if (isset($scope->id)) {
750            $clusterIds = $this->readClusterIdsByScopeId($scope->id);
751            foreach ($clusterIds as $clusterId) {
752                for ($resolveReferences = 0; $resolveReferences <= 2; $resolveReferences++) {
753                    $key = "scopeReadByClusterId-{$clusterId}-{$resolveReferences}";
754                    if (\App::$cache->has($key)) {
755                        \App::$cache->delete($key);
756                        $invalidatedKeys[] = $key;
757                    }
758                }
759            }
760        }
761
762        // Invalidate scopeReadByProviderId cache for all resolveReferences levels (0, 1, 2)
763        if (isset($scope->provider) && isset($scope->provider['id']) && $scope->provider['id']) {
764            $providerId = $scope->provider['id'];
765            for ($resolveReferences = 0; $resolveReferences <= 2; $resolveReferences++) {
766                $key = "scopeReadByProviderId-{$providerId}-{$resolveReferences}";
767                if (\App::$cache->has($key)) {
768                    \App::$cache->delete($key);
769                    $invalidatedKeys[] = $key;
770                }
771            }
772        }
773
774        if (!empty($invalidatedKeys) && \App::$log) {
775            \App::$log->info('Scope cache invalidated', [
776                'scope_id' => isset($scope->id) ? $scope->id : 'unknown',
777                'invalidated_keys' => $invalidatedKeys
778            ]);
779        }
780    }
781
782    /**
783     * @psalm-api
784     */
785    public function removeCache(\BO\Zmsentities\Scope $scope): void
786    {
787        $departmentId = isset($scope->id) ? $this->readDepartmentIdByScopeId($scope->id) : null;
788        $this->removeCacheByContext($scope, $departmentId);
789    }
790}

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    }