Lines 88.03% 184 / 209
Methods 79.31% 23 / 29
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 writeCreated 100.00% 1 / 1 100.00% 1 / 1 1
 writeUpdated 100.00% 1 / 1 100.00% 1 / 1 1
 writeDeleted 100.00% 1 / 1 100.00% 1 / 1 1
 writeDldbSlotUpdate 0.00% 0 / 1 0.00% 0 / 1 2
 readListByScopeId 100.00% 14 / 14 100.00% 1 / 1 5
 deleteOlderThanDays 100.00% 6 / 6 100.00% 1 / 1 1
 buildSnapshot 96.77% 30 / 31 0.00% 0 / 1 9
 formatTimeValue 66.66% 4 / 6 0.00% 0 / 1 7.33
 write 50.00% 11 / 22 0.00% 0 / 1 6.00
 resolveChangedBy 44.44% 4 / 9 0.00% 0 / 1 9.29
 [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] readResolvedReferences n/a 0 / 0 n/a 0 / 0 1
 [BO\Zmsbackend\Base] hashStringValue 50.00% 5 / 10 0.00% 0 / 1 8.12
14class AvailabilityHistory extends \BO\Zmsbackend\Base
15{
16    public const string ACTION_CREATED = Entity::ACTION_CREATED;
17    public const string ACTION_UPDATED = Entity::ACTION_UPDATED;
18    public const string ACTION_DELETED = Entity::ACTION_DELETED;
19    public const string ACTION_DLDB_SLOT_UPDATE = Entity::ACTION_DLDB_SLOT_UPDATE;
20
21    public const int DEFAULT_RETENTION_DAYS = 180;
22    public const int MAX_ROWS = 500;
23
24    private const int COMMENT_MAX_LENGTH = 200;
25
26    public function writeCreated(Availability $availability, ?string $changedBy = null): void
27    {
28        $this->write(self::ACTION_CREATED, $availability, $changedBy);
29    }
30
31    public function writeUpdated(Availability $availability, ?string $changedBy = null): void
32    {
33        $this->write(self::ACTION_UPDATED, $availability, $changedBy);
34    }
35
36    public function writeDeleted(Availability $availability, ?string $changedBy = null): void
37    {
38        $this->write(self::ACTION_DELETED, $availability, $changedBy);
39    }
40
41    public function writeDldbSlotUpdate(Availability $availability): void
42    {
43        $this->write(self::ACTION_DLDB_SLOT_UPDATE, $availability, 'dldb');
44    }
45
46    public function readListByScopeId(
47        int $scopeId,
48        \DateTimeInterface $from,
49        \DateTimeInterface $to,
50        ?int $availabilityId = null,
51        ?string $action = null
52    ): Collection {
53        $query = new AvailabilityHistoryQuery(\BO\Zmsbackend\Query\Base::SELECT);
54        $query->addEntityMapping()
55            ->addConditionScopeId($scopeId)
56            ->addConditionChangedAtRange($from, $to)
57            ->addLimit(self::MAX_ROWS);
58
59        if ($availabilityId !== null) {
60            $query->addConditionAvailabilityId($availabilityId);
61        }
62        if ($action !== null) {
63            $query->addConditionAction($action);
64        }
65
66        $collection = new Collection();
67        foreach ($this->fetchList($query, new Entity()) as $entity) {
68            if ($entity instanceof Entity) {
69                $collection->addEntity($entity);
70            }
71        }
72
73        return $collection;
74    }
75
76    public function deleteOlderThanDays(int $days): int
77    {
78        $days = max(1, $days);
79        $now = \DateTimeImmutable::createFromInterface(App::$now ?? new \DateTimeImmutable('now'));
80        $cutoff = $now->modify('-' . $days . ' days')->format('Y-m-d H:i:s');
81
82        return (int) $this->fetchAffected(AvailabilityHistoryQuery::QUERY_DELETE_OLDER_THAN, [
83            'cutoff' => $cutoff,
84        ]);
85    }
86
87    public function buildSnapshot(Availability $availability): array
88    {
89        $comment = $availability['description'] ?? null;
90        if (is_string($comment) && mb_strlen($comment) > self::COMMENT_MAX_LENGTH) {
91            $comment = mb_substr($comment, 0, self::COMMENT_MAX_LENGTH - 3) . '...';
92        }
93
94        $intern = (int) ($availability['workstationCount']['intern'] ?? 0);
95        $public = (int) ($availability['workstationCount']['public'] ?? 0);
96        $slotMinutes = (int) ($availability['slotTimeInMinutes'] ?? $availability->getSlotTimeInMinutes());
97        $isOpeningHours = $availability['type'] === 'openinghours';
98
99        return [
100            'start_date' => $availability->getStartDateTime()->format('Y-m-d'),
101            'end_date' => $availability->getEndDateTime()->format('Y-m-d'),
102            'every_x_weeks' => (int) ($availability['repeat']['afterWeeks'] ?? 0),
103            'every_other_week' => (int) ($availability['repeat']['weekOfMonth'] ?? 0),
104            'weekday' => Entity::encodeWeekdayMask($availability),
105            'start_time' => $isOpeningHours ? $this->formatTimeValue($availability['startTime']) : '00:00:00',
106            'end_time' => $isOpeningHours ? $this->formatTimeValue($availability['endTime']) : '00:00:00',
107            'appointment_start_time' => $isOpeningHours
108                ? '00:00:00'
109                : $this->formatTimeValue($availability['startTime']),
110            'appointment_end_time' => $isOpeningHours
111                ? '00:00:00'
112                : $this->formatTimeValue($availability['endTime']),
113            'time_slot' => gmdate('H:i:s', max(0, $slotMinutes) * 60),
114            'workstation_count' => 0,
115            'appointment_workstation_count' => $intern,
116            'comment' => $comment,
117            'internet_reduction' => $intern - $public,
118            'multiple_slots_allowed' => !empty($availability['multipleSlotsAllowed']) ? 1 : 0,
119            'open_from_days' => (int) ($availability['bookable']['startInDays'] ?? 0),
120            'open_until_days' => (int) ($availability['bookable']['endInDays'] ?? 0),
121            'version' => $availability['version'] !== null ? (int) $availability['version'] : 1,
122        ];
123    }
124
125    protected function formatTimeValue(mixed $value): string
126    {
127        if ($value === null || $value === '' || $value === 0 || $value === '0') {
128            return '00:00:00';
129        }
130
131        $value = trim((string) $value);
132        if (preg_match('/^\d{1,2}:\d{2}$/', $value) === 1) {
133            return $value . ':00';
134        }
135
136        return $value;
137    }
138
139    protected function write(string $action, Availability $availability, ?string $changedBy): void
140    {
141        try {
142            $scopeId = (int) ($availability->scope['id'] ?? 0);
143            if ($scopeId < 1) {
144                App::$log->warning('availability_history skipped: missing scope_id', [
145                    'action' => $action,
146                    'availability_id' => $availability->id,
147                ]);
148                return;
149            }
150
151            $snapshot = $this->buildSnapshot($availability);
152            $query = new AvailabilityHistoryQuery(\BO\Zmsbackend\Query\Base::INSERT);
153            $query->addValues($query->reverseEntityMapping(array_merge($snapshot, [
154                'scope_id' => $scopeId,
155                'availability_id' => $availability->hasId() ? (int) $availability->getId() : null,
156                'action' => $action,
157                'changed_by' => $changedBy ?? $this->resolveChangedBy(),
158            ])));
159
160            $this->writeItem($query);
161        } catch (\Throwable $exception) {
162            App::$log->error('availability_history write failed', [
163                'action' => $action,
164                'availability_id' => $availability->id,
165                'exception' => $exception->getMessage(),
166            ]);
167        }
168    }
169
170    protected function resolveChangedBy(): string
171    {
172        try {
173            if (User::hasLogin()) {
174                $userId = User::readWorkstation()->getUseraccount()->id ?? null;
175                if ($userId !== null && $userId !== '') {
176                    return (string) $userId;
177                }
178            }
179        } catch (\Throwable $exception) {
180            App::$log->warning('availability_history actor resolution failed', [
181                'exception' => $exception->getMessage(),
182            ]);
183        }
184
185        return 'system';
186    }
187}

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($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, $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    }
256    public function readResolvedReferences(\BO\Zmsentities\Schema\Entity $entity, int $resolveReferences)
257    {
258        return $entity;
259    }
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    }