Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.59% covered (warning)
78.59%
367 / 467
76.92% covered (warning)
76.92%
30 / 39
CRAP
0.00% covered (danger)
0.00%
0 / 1
Availability
78.59% covered (warning)
78.59%
367 / 467
76.92% covered (warning)
76.92%
30 / 39
423.87
0.00% covered (danger)
0.00%
0 / 1
 getDefaults
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
1
 hasDate
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 hasBookableDates
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 isOpenedOnDate
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
8
 overridesDayOff
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
6.03
 isOpened
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 hasWeekDay
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 hasAppointment
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 hasTime
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 getAvailableSecondsPerDay
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 hasDay
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 hasDayOff
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 hasWeek
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
10
 getStartDateTime
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getEndDateTime
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getDuration
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getBookableStart
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 getBookableEnd
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 isBookable
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
7
 hasDateBetween
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 validateStartTime
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
 validateWeekdays
85.71% covered (warning)
85.71%
42 / 49
0.00% covered (danger)
0.00%
0 / 1
10.29
 validateEndTime
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
12
 validateOriginEndTime
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
72
 validateType
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 validateSlotTime
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
12
 validateBookableDayRange
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getSlotList
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 getSlotTimeInMinutes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getConflict
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 isMatchOf
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
15
 hasSharedWeekdayWith
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
9
 getTimeOverlaps
100.00% covered (success)
100.00%
38 / 38
100.00% covered (success)
100.00%
1 / 1
12
 withCalculatedSlots
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
2
 withScope
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 __toString
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
3
 offsetSet
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 isNewerThan
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 withLessData
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
9
1<?php
2
3namespace BO\Zmsentities;
4
5/**
6 * @SuppressWarnings(Complexity)
7 * @SuppressWarnings(Coupling)
8 * @SuppressWarnings(PublicMethod)
9 *
10 * Schema-backed entity (ArrayObject::ARRAY_AS_PROPS); document dynamic keys for Psalm.
11 *
12 * @property int|string $id
13 * @property Scope|array $scope
14 * @property string|null $description
15 * @property array $workstationCount
16 * @property int|string|null $slotTimeInMinutes
17 * @property string $type
18 * @property string|null $startTime
19 * @property string|null $endTime
20 * @property array $repeat
21 * @property bool|int|string|null $multipleSlotsAllowed
22 * @property array $bookable
23 * @property int|null $version
24 * @property array $weekday
25 */
26class Availability extends Schema\Entity
27{
28    public const string PRIMARY = 'id';
29
30    public static $schema = "availability.json";
31
32    /**
33     * @var array $weekday english localized weekdays to avoid problems with setlocale()
34     */
35    protected static $weekdayNameList = [
36        'sunday',
37        'monday',
38        'tuesday',
39        'wednesday',
40        'thursday',
41        'friday',
42        'saturday'
43    ];
44
45    /**
46     * Performance costs for modifying time are high, cache the calculated value
47     * @var Helper\DateTime|null $startTimeCache
48     */
49    protected $startTimeCache;
50
51    /**
52     * Performance costs for modifying time are high, cache the calculated value
53     * @var Helper\DateTime|null $endTimeCache
54     */
55    protected $endTimeCache;
56
57    /**
58     * Set Default values
59     *
60     * @return (((int|string)[]|int|string)[]|int|string|true)[]
61     *
62     */
63    #[\Override]
64    public function getDefaults()
65    {
66        return [
67            'id' => 0,
68            'weekday' => array_fill_keys(self::$weekdayNameList, 0),
69            'repeat' => [
70                'afterWeeks' => 1,
71                'weekOfMonth' => 0,
72            ],
73            'bookable' => [
74                'startInDays' => 1,
75                'endInDays' => 60,
76            ],
77            'workstationCount' => [
78                'public' => 0,
79                'intern' => 0,
80            ],
81            'lastChange' => 0,
82            'multipleSlotsAllowed' => true,
83            'slotTimeInMinutes' => 10,
84            'startDate' => 0,
85            'endDate' => 0,
86            'startTime' => '0:00',
87            'endTime' => '23:59',
88            'type' => 'appointment',
89            'version' => 1,
90            'scope' => [
91                'id' => 123,
92                'provider' => [
93                    'id' => 0,
94                    'name' => '',
95                    'source' => ''
96                ],
97                'shortName' => ''
98            ]
99        ];
100    }
101
102    /**
103     * Check, if the dateTime contains a day given by the settings
104     * ATTENTION: Time critical function, keep highly optimized
105     * Compared to isOpened() the Booking time is checked too
106     *
107     * @param \DateTimeInterface $dateTime
108     *
109     * @return Bool
110     */
111    public function hasDate(\DateTimeInterface $dateTime, \DateTimeInterface $now)
112    {
113        $dateTime = Helper\DateTime::create($dateTime);
114        if (
115            !$this->isOpenedOnDate($dateTime)
116            || !$this->isBookable($dateTime, $now)
117        ) {
118            // Out of date range
119            return false;
120        }
121        return true;
122    }
123
124    public function hasBookableDates(\DateTimeInterface $now): bool
125    {
126        if ($this->workstationCount['intern'] <= 0) {
127            return false;
128        }
129        if ($this->getEndDateTime()->getTimestamp() < $now->getTimestamp()) {
130            return false;
131        }
132        $stopDate = $this->getBookableEnd($now);
133        if ($this->getStartDateTime()->getTimestamp() > $stopDate->getTimestamp()) {
134            return false;
135        }
136        return $this->hasDateBetween($this->getBookableStart($now), $this->getBookableEnd($now), $now);
137    }
138
139    /**
140     * Check, if the dateTime contains a day
141     * ATTENTION: Time critical function, keep highly optimized
142     *
143     * @param \DateTimeInterface $dateTime
144     * @param string|false $type of "openinghours", "appointment" or false to ignore type
145     *
146     * @return Bool
147     */
148    public function isOpenedOnDate(\DateTimeInterface $dateTime, string|false $type = false)
149    {
150        $dateTime = Helper\DateTime::create($dateTime);
151        if (
152            !$this->hasWeekDay($dateTime)
153            || ($type !== false && $this->type != $type)
154            || !$this->hasDay($dateTime)
155            || !$this->hasWeek($dateTime)
156            || ($this->getDuration() > 1 && $this->hasDayOff($dateTime))
157        ) {
158            // Out of date range
159            return false;
160        }
161        return true;
162    }
163
164    public function overridesDayOff(): bool
165    {
166        if ($this->getDuration() >= 2) {
167            return false;
168        }
169
170        $start = $this->getStartDateTime()->modify('00:00:00');
171        $end   = $this->getEndDateTime()->modify('23:59:59');
172        $current = clone $start;
173
174        while ($current <= $end) {
175            try {
176                if ($this->hasWeekDay($current) && $this->hasDayOff($current)) {
177                    return true;
178                }
179            } catch (Exception\DayoffMissing $e) {
180                // Scope doesn't have dayoff data, skip this day
181            }
182            $current = $current->modify('+1 day');
183        }
184        return false;
185    }
186
187    /**
188     * Check if date and time is in availability
189     * Compared to hasDate() the time of the day is checked, but not booking time
190     *
191     * @param \DateTimeInterface $dateTime
192     * @param string|false $type of "openinghours", "appointment" or false to ignore type
193     *
194     */
195    public function isOpened(\DateTimeInterface $dateTime, string|false $type = false): bool
196    {
197        return (!$this->isOpenedOnDate($dateTime, $type) || !$this->hasTime($dateTime)) ? false : true;
198    }
199
200    public function hasWeekDay(\DateTimeInterface $dateTime): bool
201    {
202        $weekDayName = self::$weekdayNameList[$dateTime->format('w')];
203        if (!$this['weekday'][$weekDayName]) {
204            // Wrong weekday
205            return false;
206        }
207        return true;
208    }
209
210    public function hasAppointment(Appointment $appointment): bool
211    {
212        $dateTime = $appointment->toDateTime();
213        $isOpenedStart = $this->isOpened($dateTime, false);
214        $duration = (int) $this->slotTimeInMinutes * $appointment->slotCount;
215        $endTime = $dateTime->modify("+" . $duration . "minutes")
216            ->modify("-1 second"); // To allow the last slot for an appointment
217        $isOpenedEnd = $this->isOpened($endTime, false);
218        return ($isOpenedStart && $isOpenedEnd);
219    }
220
221    /**
222     * Check, if the dateTime is a time covered by availability
223     *
224     * @param \DateTimeInterface $dateTime
225     *
226     * @return Bool
227     */
228    public function hasTime(\DateTimeInterface $dateTime)
229    {
230        $start = $this->getStartDateTime()->getSecondsOfDay();
231        $end = $this->getEndDateTime()->getSecondsOfDay();
232        $compare = Helper\DateTime::create($dateTime)->getSecondsOfDay();
233        if ($start > $compare || $end <= $compare) {
234            // Out of time range
235            return false;
236        }
237        return true;
238    }
239
240    public function getAvailableSecondsPerDay(string $type = "intern"): mixed
241    {
242        $start = $this->getStartDateTime()->getSecondsOfDay();
243        $end = $this->getEndDateTime()->getSecondsOfDay();
244        return ($end - $start) * $this->workstationCount[$type];
245    }
246
247    /**
248     * Check, if the dateTime is a day covered by availability
249     *
250     * @param \DateTimeInterface $dateTime
251     *
252     * @return Bool
253     */
254    public function hasDay(\DateTimeInterface $dateTime)
255    {
256        $start = $this->getStartDateTime()->modify('0:00:00');
257        $end = $this->getEndDateTime()->modify('23:59:59');
258        if ($dateTime->getTimestamp() < $start->getTimestamp() || $dateTime->getTimestamp() > $end->getTimestamp()) {
259            // Out of date range
260            return false;
261        }
262        return true;
263    }
264
265    /**
266     * Check, if the dateTime is a dayoff date
267     *
268     * @param \DateTimeInterface $dateTime
269     *
270     * @return Bool
271     */
272    public function hasDayOff(\DateTimeInterface $dateTime)
273    {
274        if (isset($this['scope']['dayoff'])) {
275            $timeStamp = $dateTime->format('Y-m-d');
276            foreach ($this['scope']['dayoff'] as $dayOff) {
277                if (date('Y-m-d', $dayOff['date']) == $timeStamp) {
278                    return true;
279                }
280            }
281        } else {
282            throw new Exception\DayoffMissing();
283        }
284        return false;
285    }
286
287    /**
288     * Check, if the dateTime contains a week given by the week repetition settings
289     *
290     * @param \DateTimeInterface $dateTime
291     *
292     * @return Bool
293     */
294    public function hasWeek(\DateTimeInterface $dateTime)
295    {
296        $dateTime = Helper\DateTime::create($dateTime);
297        $start = $this->getStartDateTime();
298        $monday = "monday this week";
299        if (
300            $this['repeat']['afterWeeks']
301            && ($this['repeat']['afterWeeks'] == 1
302                || 0 ===
303                    $dateTime->modify($monday)->diff($start->modify($monday))->days
304                 % ($this['repeat']['afterWeeks'] * 7)
305            )
306        ) {
307            return true;
308        }
309        if (
310            $this['repeat']['weekOfMonth']
311            && (
312                $dateTime->isWeekOfMonth($this['repeat']['weekOfMonth'])
313                // On a value of 5, always take the last week
314                || ($this['repeat']['weekOfMonth'] >= 5 && $dateTime->isLastWeekOfMonth())
315            )
316        ) {
317            return true;
318        }
319        if (!$this['repeat']['weekOfMonth'] && !$this['repeat']['afterWeeks']) {
320            return true;
321        }
322        return false;
323    }
324
325    /**
326     * Get DateTimeInterface for start time of availability
327     *
328     * @return Helper\DateTime
329     */
330    public function getStartDateTime()
331    {
332        if (!$this->startTimeCache) {
333            $this->startTimeCache = Helper\DateTime::create()
334                ->setTimestamp($this['startDate'])
335                ->modify('today ' .  $this['startTime']);
336        }
337        return $this->startTimeCache;
338    }
339
340    /**
341     * Get DateTimeInterface for end time of availability
342     *
343     * @return Helper\DateTime
344     */
345    public function getEndDateTime()
346    {
347        if (!$this->endTimeCache) {
348            $this->endTimeCache = Helper\DateTime::create()
349                ->setTimestamp($this['endDate'])
350                ->modify('today ' .  $this['endTime']);
351        }
352        return $this->endTimeCache;
353    }
354
355    /**
356     * Get duration of availability
357     *
358     * @return integer
359     */
360    public function getDuration()
361    {
362        $startTime = $this->getStartDateTime();
363        $endTime = $this->getEndDateTime();
364        return (int)$endTime->diff($startTime)->format("%a");
365    }
366
367    /**
368     * Get DateTimeInterface for start booking time of availability
369     *
370     * @param \DateTimeInterface $now relative time to compare booking settings
371     *
372     * @return Helper\DateTime
373     */
374    public function getBookableStart(\DateTimeInterface $now)
375    {
376        $now = Helper\DateTime::create($now);
377        $availabilityStart = Helper\Property::create($this)->bookable->startInDays->get();
378        $time = $this->getStartDateTime()->format('H:i:s');
379        if (null !== $availabilityStart) {
380            return $now->modify('+' . $availabilityStart . 'days')->modify($time);
381        }
382        $scopeStart = Helper\Property::create($this)->scope->preferences->appointment->startInDaysDefault->get();
383        if (null !== $scopeStart) {
384            return $now->modify('+' . $scopeStart . 'days')->modify($time);
385        }
386        throw new \BO\Zmsentities\Exception\ProcessBookableFailed(
387            "Undefined start time for booking, try to set the scope properly"
388        );
389    }
390
391    /**
392     * Get DateTimeInterface for end booking time of availability
393     *
394     * @param \DateTimeInterface $now relative time to compare booking settings
395     *
396     * @return Helper\DateTime
397     */
398    public function getBookableEnd(\DateTimeInterface $now)
399    {
400        $now = Helper\DateTime::create($now);
401        $availabilityEnd = Helper\Property::create($this)->bookable->endInDays->get();
402        $time = $this->getEndDateTime()->format('H:i:s');
403        if (null !== $availabilityEnd) {
404            return $now->modify('+' . $availabilityEnd . 'days')->modify($time);
405        }
406        $scopeEnd = Helper\Property::create($this)->scope->preferences->appointment->endInDaysDefault->get();
407        if (null !== $scopeEnd) {
408            return $now->modify('+' . $scopeEnd . 'days')->modify($time);
409        }
410        throw new \BO\Zmsentities\Exception\ProcessBookableFailed(
411            "Undefined end time for booking, try to set the scope properly"
412        );
413    }
414
415    /**
416     * Check, if the dateTime contains is within the bookable range (usually for public access)
417     * The current time is used to compare the start Time of the availability
418     *
419     * @param \DateTimeInterface $bookableDate
420     * @param \DateTimeInterface $now relative time to compare booking settings
421     *
422     * @return bool
423     */
424    public function isBookable(\DateTimeInterface $bookableDate, \DateTimeInterface $now)
425    {
426        if (!$this->hasDay($bookableDate)) {
427            return false;
428        }
429        $bookableCurrentTime = Helper\DateTime::create($bookableDate)->modify($now->format('H:i:s'));
430        Helper\DateTime::create($bookableDate)->getTimestamp() + Helper\DateTime::create($now)->getSecondsOfDay();
431        $startDate = $this->getBookableStart($now)->modify('00:00:00');
432
433        if ($bookableCurrentTime->getTimestamp() < $startDate->getTimestamp()) {
434            return false;
435        }
436        $endDate = $this->getBookableEnd($now)->modify('23:59:59');
437        if ($bookableCurrentTime->getTimestamp() > $endDate->getTimestamp()) {
438            return false;
439        }
440        if (
441            $bookableDate->format('Y-m-d') == $endDate->format('Y-m-d')
442            && $now->format('Y-m-d') != $this->getEndDateTime()->format('Y-m-d')
443        ) {
444            // Avoid releasing all appointments on midnight, allow smaller contingents distributed over the day
445            $delayedStart = $this->getBookableEnd($now)->modify($this->getStartDateTime()->format('H:i:s'));
446            if ($bookableCurrentTime->getTimestamp() < $delayedStart->getTimestamp()) {
447                return false;
448            }
449        }
450        return true;
451    }
452
453    /**
454     * Check, if a day between two dates is included
455     *
456     * @return bool
457     */
458    public function hasDateBetween(\DateTimeInterface $startTime, \DateTimeInterface $stopTime, \DateTimeInterface $now): bool
459    {
460        if ($startTime->getTimestamp() < $now->getTimestamp()) {
461            $startTime = $now;
462        }
463        if ($stopTime->getTimestamp() < $now->getTimestamp()) {
464            return false;
465        }
466        $startTime = Helper\DateTime::create($startTime);
467        do {
468            if ($this->hasDate($startTime, $now)) {
469                return true;
470            }
471            $startTime = $startTime->modify('+1 day');
472        } while ($startTime->getTimestamp() <= $stopTime->getTimestamp());
473        return false;
474    }
475
476    public function validateStartTime(\DateTimeInterface $today, \DateTimeInterface $tomorrow, \DateTimeInterface $startDate, \DateTimeInterface $selectedDate, string $kind): array
477    {
478        $errorList = [];
479
480        $startTime = Helper\DateTime::create($startDate)->setTime(0, 0);
481        $isFuture = ($kind && $kind === 'future');
482
483        if (
484            !$isFuture &&
485            $selectedDate->getTimestamp() > $today->getTimestamp() &&
486            $startTime->getTimestamp() > Helper\DateTime::create($selectedDate)->setTime(0, 0)->getTimestamp()
487        ) {
488            $errorList[] = [
489                'type' => 'startTimeFuture',
490                'message' => "Das Startdatum der Ã–ffnungszeit muss vor dem " . $tomorrow->format('d.m.Y') . " liegen."
491            ];
492        }
493
494        return $errorList;
495    }
496
497    public function validateWeekdays(\DateTimeInterface $startDate, \DateTimeInterface $endDate, array $weekday, string $kind): array
498    {
499        $errorList = [];
500
501        // Skip validation if this is part of a split series
502        if ($kind === 'origin' || $kind === 'future') {
503            return $errorList;
504        }
505
506        if ($startDate > $endDate) {
507            return $errorList;
508        }
509
510        $hasSelectedDay = false;
511        foreach (self::$weekdayNameList as $day) {
512            if ((int)$weekday[$day] > 0) {
513                $hasSelectedDay = true;
514                break;
515            }
516        }
517
518        if (!$hasSelectedDay) {
519            $errorList[] = [
520                'type' => 'weekdayRequired',
521                'message' => 'Mindestens ein Wochentag muss ausgewählt sein.'
522            ];
523            return $errorList;
524        }
525
526        $germanWeekdays = [
527            'sunday' => 'Sonntag',
528            'monday' => 'Montag',
529            'tuesday' => 'Dienstag',
530            'wednesday' => 'Mittwoch',
531            'thursday' => 'Donnerstag',
532            'friday' => 'Freitag',
533            'saturday' => 'Samstag'
534        ];
535
536        $selectedWeekdays = array_filter(self::$weekdayNameList, function ($day) use ($weekday) {
537            return (int)$weekday[$day] > 0;
538        });
539        $foundWeekdays = [];
540
541        // Walk calendar days at noon so a clock time on the timestamp, or the
542        // DST fallback, cannot skip the last day of the range.
543        $currentDate = Helper\DateTime::create($startDate)->setTime(12, 0);
544        $endDay = Helper\DateTime::create($endDate)->setTime(12, 0);
545        while ($currentDate <= $endDay) {
546            $weekDayName = self::$weekdayNameList[$currentDate->format('w')];
547            if (in_array($weekDayName, $selectedWeekdays)) {
548                $foundWeekdays[] = $weekDayName;
549            }
550            $currentDate = $currentDate->modify('+1 day');
551        }
552
553        $missingWeekdays = array_diff($selectedWeekdays, array_unique($foundWeekdays));
554        if (!empty($missingWeekdays)) {
555            $germanMissingWeekdays = array_map(function ($day) use ($germanWeekdays) {
556                return $germanWeekdays[$day];
557            }, $missingWeekdays);
558
559            $errorList[] = [
560                'type' => 'invalidWeekday',
561                'message' => sprintf(
562                    'Die ausgewählten Wochentage (%s) kommen im gewählten Zeitraum nicht vor.',
563                    implode(', ', $germanMissingWeekdays)
564                )
565            ];
566        }
567
568        return $errorList;
569    }
570
571    public function validateEndTime(\DateTimeInterface $startDate, \DateTimeInterface $endDate): array
572    {
573        $errorList = [];
574
575        $startHour = (int) $startDate->format('H');
576        $endHour = (int) $endDate->format('H');
577        $startMinute = (int) $startDate->format('i');
578        $endMinute = (int) $endDate->format('i');
579        $dayMinutesStart = ($startHour * 60) + $startMinute;
580        $dayMinutesEnd = ($endHour * 60) + $endMinute;
581        $startTimestamp = $startDate->getTimestamp();
582        $endTimestamp = $endDate->getTimestamp();
583
584        if ($dayMinutesEnd <= $dayMinutesStart) {
585            $errorList[] = [
586                'type' => 'endTime',
587                'message' => 'Die Endzeit darf nicht vor der Startzeit liegen.'
588            ];
589        } elseif ($startTimestamp >= $endTimestamp) {
590            $errorList[] = [
591                'type' => 'endTime',
592                'message' => 'Das Enddatum darf nicht vor dem Startdatum liegen.'
593            ];
594        }
595
596        return $errorList;
597    }
598
599    public function validateOriginEndTime(\DateTimeInterface $today, \DateTimeInterface $yesterday, \DateTimeInterface $endDate, \DateTimeInterface $selectedDate, string $kind): array
600    {
601        $errorList = [];
602        $endHour = (int) $endDate->format('H');
603        $endMinute = (int) $endDate->format('i');
604        $startDate = $this->getStartDateTime();
605        $startHour = (int) $startDate->format('H');
606        $startMinute = (int) $startDate->format('i');
607        $endDateTime = Helper\DateTime::create($endDate)->setTime($endHour, $endMinute);
608        $startDateTime = Helper\DateTime::create($startDate)->setTime($startHour, $startMinute);
609        $endTimestamp = $endDateTime->getTimestamp();
610        $startTimestamp = $startDateTime->getTimestamp();
611        $isOrigin = ($kind && $kind === 'origin');
612
613        if (
614            !$isOrigin
615            && $selectedDate->getTimestamp() > $today->getTimestamp()
616            && $endDate < Helper\DateTime::create($selectedDate)->setTime(0, 0)
617        ) {
618            $errorList[] = [
619                'type' => 'endTimeFuture',
620                'message' => "Das Enddatum der Ã–ffnungszeit muss nach dem " . $yesterday->format('d.m.Y') . " liegen."
621            ];
622        }
623
624        if (!$isOrigin && $startTimestamp < $today->getTimestamp() && $endTimestamp < $today->getTimestamp()) {
625            $errorList[] = [
626                'type' => 'endTimePast',
627                'message' => 'Öffnungszeiten in der Vergangenheit lassen sich nicht bearbeiten '
628                    . '(Die aktuelle Zeit "' . $today->format('d.m.Y H:i') . ' Uhr" liegt nach dem Terminende am "'
629                    . $endDateTime->format('d.m.Y H:i') . ' Uhr" und dem Terminanfang am "'
630                    . $startDateTime->format('d.m.Y H:i') . ' Uhr").'
631            ];
632        }
633
634        return $errorList;
635    }
636
637    public function validateType(string $kind): array
638    {
639        $errorList = [];
640        if (empty($kind)) {
641            $errorList[] = [
642                'type' => 'type',
643                'message' => 'Typ erforderlich'
644            ];
645        }
646        return $errorList;
647    }
648
649    public function validateSlotTime(\DateTimeInterface $startDate, \DateTimeInterface $endDate): array
650    {
651        $errorList = [];
652        $slotTime = $this['slotTimeInMinutes'];
653
654        $startHour = (int)$startDate->format('H');
655        $startMinute = (int)$startDate->format('i');
656        $endHour = (int)$endDate->format('H');
657        $endMinute = (int)$endDate->format('i');
658
659        $totalMinutes = (($endHour - $startHour) * 60) + ($endMinute - $startMinute);
660
661        if ($slotTime === 0) {
662            $errorList[] = [
663                'type' => 'slotTime',
664                'message' => 'Die Slot-Zeit darf nicht 0 sein.'
665            ];
666            return $errorList;
667        }
668
669        if ($totalMinutes % $slotTime > 0) {
670            $errorList[] = [
671                'type' => 'slotCount',
672                'message' => 'Zeitschlitze müssen sich gleichmäßig in der Ã–ffnungszeit aufteilen lassen.'
673            ];
674        }
675
676        return $errorList;
677    }
678
679    public function validateBookableDayRange(int $startInDays, int $endInDays): array
680    {
681        $errorList = [];
682        if ($startInDays > $endInDays) {
683            $errorList[] = [
684                'type' => 'bookableDayRange',
685                'message' => 'Bitte geben Sie im Feld \'von\' eine kleinere Zahl ein als im Feld \'bis\', wenn Sie bei \'Buchbar\' sind.'
686            ];
687        }
688
689        return $errorList;
690    }
691
692    /**
693     * Creates a list of slots available on a valid day
694     *
695     * @return Collection\SlotList
696     */
697    public function getSlotList(): Collection\SlotList
698    {
699        $startTime = Helper\DateTime::create($this['startTime']);
700        $stopTime = Helper\DateTime::create($this['endTime']);
701        $slotList = new Collection\SlotList();
702        $slotInstance = new Slot($this['workstationCount']);
703        if ($this['slotTimeInMinutes'] > 0) {
704            do {
705                $slot = clone $slotInstance;
706                $slot->setTime($startTime);
707                $slotList[] = $slot;
708                $startTime = $startTime->modify('+' . $this['slotTimeInMinutes'] . 'minute');
709                // Only add a slot, if at least a minute is left, otherwise do not ("<" instead "<=")
710            } while ($startTime->getTimestamp() < $stopTime->getTimestamp());
711        }
712        return $slotList;
713    }
714
715    public function getSlotTimeInMinutes(): mixed
716    {
717        return $this['slotTimeInMinutes'];
718    }
719
720    /**
721     * Get problems on configuration of this availability
722     *
723     * @return Process|false with processes in status "conflict"
724     */
725    public function getConflict(): Process|false
726    {
727        $start = $this->getStartDateTime()->getSecondsOfDay();
728        $end = $this->getEndDateTime()->getSecondsOfDay();
729        $minutesPerDay = floor(($end - $start) / 60);
730        if ($minutesPerDay % (int) $this->slotTimeInMinutes > 0) {
731            $conflict = new Process();
732            $conflict->status = 'conflict';
733            $appointment = $conflict->getFirstAppointment();
734            $appointment->availability = $this;
735            $appointment->date = $this->getStartDateTime()->getTimestamp();
736            $conflict->amendment =
737                "Der eingestellte Zeitschlitz von {$this->slotTimeInMinutes} Minuten"
738                . " sollte in die eingestellte Uhrzeit passen.";
739            return $conflict;
740        }
741        return false;
742    }
743
744    /**
745     * Check of a different availability has the same opening configuration
746     */
747    public function isMatchOf(Availability $availability): bool
748    {
749        return ($this->type != $availability->type
750            || $this->startTime != $availability->startTime
751            || $this->endTime != $availability->endTime
752            || $this->startDate != $availability->startDate
753            || $this->endDate != $availability->endDate
754            || $this->repeat['afterWeeks'] != $availability->repeat['afterWeeks']
755            || $this->repeat['weekOfMonth'] != $availability->repeat['weekOfMonth']
756            || (bool)$this->weekday['monday'] != (bool)$availability->weekday['monday']
757            || (bool)$this->weekday['tuesday'] != (bool)$availability->weekday['tuesday']
758            || (bool)$this->weekday['wednesday'] != (bool)$availability->weekday['wednesday']
759            || (bool)$this->weekday['thursday'] != (bool)$availability->weekday['thursday']
760            || (bool)$this->weekday['friday'] != (bool)$availability->weekday['friday']
761            || (bool)$this->weekday['saturday'] != (bool)$availability->weekday['saturday']
762            || (bool)$this->weekday['sunday'] != (bool)$availability->weekday['sunday']
763        ) ? false : true;
764    }
765
766    public function hasSharedWeekdayWith(Availability $availability): bool
767    {
768        return ($this->type == $availability->type
769            && (bool)$this->weekday['monday'] != (bool)$availability->weekday['monday']
770            && (bool)$this->weekday['tuesday'] != (bool)$availability->weekday['tuesday']
771            && (bool)$this->weekday['wednesday'] != (bool)$availability->weekday['wednesday']
772            && (bool)$this->weekday['thursday'] != (bool)$availability->weekday['thursday']
773            && (bool)$this->weekday['friday'] != (bool)$availability->weekday['friday']
774            && (bool)$this->weekday['saturday'] != (bool)$availability->weekday['saturday']
775            && (bool)$this->weekday['sunday'] != (bool)$availability->weekday['sunday']
776        ) ? false : true;
777    }
778
779    /**
780     * Get overlaps on daytime
781     * This functions does not check, if two availabilities are openend on the same day!
782     *
783     * @param Availability $availability for comparision
784     *
785     * @return Collection\ProcessList with processes in status "conflict"
786     *
787     *
788     */
789
790    /*
791    1
792    Case 01:  |-----|
793              |-----|
794                 2
795
796                 1
797    Case 02:  |-----|
798                 |-----|
799                    2
800
801                    1
802    Case 03:     |-----|
803              |-----|
804                 2
805
806                   1
807    Case 04:  |---------|
808                |-----|
809                   2
810
811                   1
812    Case 05:    |-----|
813              |---------|
814                   2
815
816                 1
817    Case 06:  |-----|
818                      |-----|
819                         2
820
821                         1
822    Case 07:          |-----|
823              |-----|
824                 2
825
826                 1
827    Case 08:  |-----|
828                    |-----|
829                       2
830
831                       1
832    Case 09:        |-----|
833              |-----|
834                 2
835
836                 1
837    Case 10:     |
838              |-----|
839                 2
840
841                 1
842    Case 11:  |-----|
843                 |
844                 2
845
846              1
847    Case 12:  |
848              |-----|
849                 2
850
851                    1
852    Case 13:        |
853              |-----|
854                 2
855
856                 1
857    Case 14:  |-----|
858              |
859              2
860
861                 1
862    Case 15:  |-----|
863                    |
864                    2
865
866              1
867    Case 16:  |
868              |
869              2
870
871            |                         |    Operlap    |     Overlap
872      Case  |         Example         | Open Interval | Closed Interval
873    --------|-------------------------|---------------|-----------------
874    Case 01 | 09:00-11:00 09:00-11:00 |      Yes      |        Yes
875    Case 02 | 09:00-11:00 10:00-12:00 |      Yes      |        Yes
876    Case 03 | 10:00-12:00 09:00-11:00 |      Yes      |        Yes
877    Case 04 | 09:00-12:00 10:00-11:00 |      Yes      |        Yes
878    Case 05 | 10:00-11:00 09:00-12:00 |      Yes      |        Yes
879    Case 06 | 09:00-10:00 11:00-12:00 |      No       |        No
880    Case 07 | 11:00-12:00 09:00-10:00 |      No       |        No
881    Case 08 | 09:00-10:00 10:00-11:00 |      No       |        Yes
882    Case 09 | 10:00-11:00 09:00-10:00 |      No       |        Yes
883    Case 10 | 10:00-10:00 09:00-11:00 |      Yes      |        Yes
884    Case 11 | 09:00-11:00 10:00-10:00 |      Yes      |        Yes
885    Case 12 | 09:00-09:00 09:00-10:00 |      No       |        Yes
886    Case 13 | 10:00-10:00 09:00-10:00 |      No       |        Yes
887    Case 14 | 09:00-10:00 09:00-09:00 |      No       |        Yes
888    Case 15 | 09:00-10:00 10:00-10:00 |      No       |        Yes
889    Case 16 | 09:00-09:00 09:00-09:00 |      No       |        Yes
890    */
891
892    public function getTimeOverlaps(Availability $availability, \DateTimeInterface $currentDate)
893    {
894        $processList = new Collection\ProcessList();
895        if (
896            $availability->id != $this->id
897            && $availability->type == $this->type
898            && $this->hasSharedWeekdayWith($availability)
899        ) {
900            $processTemplate = new Process();
901            $processTemplate->amendment = "Zwei Ã–ffnungszeiten Ã¼berschneiden sich.";
902            $processTemplate->status = 'conflict';
903            $appointment = $processTemplate->getFirstAppointment();
904            $appointment->availability = $this;
905            $appointment->date = $this->getStartDateTime()->getTimestamp();
906            $thisStart = $this->getStartDateTime()->getSecondsOfDay();
907            $thisEnd = $this->getEndDateTime()->getSecondsOfDay();
908            $availabilityStart = $availability->getStartDateTime()->getSecondsOfDay();
909            $availabilityEnd = $availability->getEndDateTime()->getSecondsOfDay();
910
911            $isEqual = ($availabilityStart == $thisStart && $availabilityEnd == $thisEnd);
912
913            if ($availabilityStart < $thisEnd && $thisStart < $availabilityEnd && ! $isEqual) {
914                $process = clone $processTemplate;
915                $process->getFirstAppointment()->date = $this
916                    ->getStartDateTime()
917                    ->modify($currentDate->format("Y-m-d"))
918                    ->getTimestamp();
919                $processList->addEntity($process);
920            } elseif ($thisEnd < $availabilityStart && $availabilityEnd < $thisStart && ! $isEqual) {
921                $process = clone $processTemplate;
922                $process->getFirstAppointment()->date = $availability
923                    ->getStartDateTime()
924                    ->modify($currentDate->format("Y-m-d"))
925                    ->getTimestamp();
926                $processList->addEntity($process);
927            } elseif ($isEqual) {
928                $process = clone $processTemplate;
929                $process->amendment = "Zwei Ã–ffnungszeiten sind gleich.";
930                $process->getFirstAppointment()->date = $availability
931                    ->getStartDateTime()
932                    ->modify($currentDate->format("Y-m-d"))
933                    ->getTimestamp();
934                $processList->addEntity($process);
935            }
936        }
937        return $processList;
938    }
939
940    /**
941     * Update workstationCount to number of calculated appointments
942     *
943     * @return self cloned
944     */
945    public function withCalculatedSlots()
946    {
947        $availability = clone $this;
948        $startTime = Helper\DateTime::create($this['startTime']);
949        $stopTime = Helper\DateTime::create($this['endTime']);
950        $openingSeconds = $stopTime->getTimestamp() - $startTime->getTimestamp();
951        $openingMinutes = floor($openingSeconds / 60);
952        $slices = 0;
953        if ($this['slotTimeInMinutes'] > 0) {
954            $slices = floor($openingMinutes / $this['slotTimeInMinutes']);
955        }
956        $slot = new Slot([
957            'type' => Slot::FREE,
958            'intern' => $this['workstationCount']['intern'] * $slices,
959            'public' => $this['workstationCount']['public'] * $slices,
960        ]);
961        $availability['workstationCount'] = $slot;
962        return $availability;
963    }
964
965    public function withScope(\BO\Zmsentities\Scope $scope): static
966    {
967        $availability = clone $this;
968        $availability->scope = $scope;
969        return $availability;
970    }
971
972    public function __toString()
973    {
974        $info = "Availability." . $this['type'] . " #" . $this['id'];
975        $info .= " starting " . $this->startDate . $this->getStartDateTime()->format(' Y-m-d');
976        $info .= "||now+" . $this['bookable']['startInDays'] . " ";
977        $info .= " until " . $this->getEndDateTime()->format('Y-m-d');
978        $info .= "||now+" . $this['bookable']['endInDays'] . " ";
979        if ($this['repeat']['afterWeeks']) {
980            $info .= " every " . $this['repeat']['afterWeeks'] . " week(s)";
981        }
982        if ($this['repeat']['weekOfMonth']) {
983            $info .= " each " . $this['repeat']['weekOfMonth'] . ". weekOfMonth";
984        }
985        $info .= " on ";
986        $weekdays = array_filter($this['weekday'], function (mixed $value) {
987            return $value > 0;
988        });
989        $info .= implode(',', array_keys($weekdays));
990        $info .= " from " . $this->getStartDateTime()->format('H:i');
991        $info .= " to " . $this->getEndDateTime()->format('H:i');
992        $info .= " using " . $this['slotTimeInMinutes'] . "min slots";
993        $info .= " with p{$this['workstationCount']['public']}/";
994        $info .= "i{$this['workstationCount']['intern']}";
995        $day = $this->getSlotList()->getSummerizedSlot();
996        $info .= " day $day";
997        return $info;
998    }
999
1000    /**
1001     * Delete cache on changes
1002     *
1003     */
1004    #[\Override]
1005    public function offsetSet(mixed $key, mixed $value): void
1006    {
1007        $this->startTimeCache = null;
1008        $this->endTimeCache = null;
1009        parent::offsetSet($key, $value);
1010    }
1011
1012    /**
1013     * Check if availability is newer than given time
1014     *
1015     * @return bool
1016     */
1017    public function isNewerThan(\DateTimeInterface $dateTime)
1018    {
1019        return ($dateTime->getTimestamp() < $this->lastChange);
1020    }
1021
1022    /**
1023     * Reduce data of dereferenced entities to a required minimum
1024     *
1025     * @return static
1026     */
1027    #[\Override]
1028    public function withLessData(array $keepArray = [])
1029    {
1030        $entity = clone $this;
1031        if (! in_array('repeat', $keepArray)) {
1032            unset($entity['repeat']);
1033        }
1034        if (! in_array('id', $keepArray)) {
1035            unset($entity['id']);
1036        }
1037        if (! in_array('bookable', $keepArray)) {
1038            unset($entity['bookable']);
1039        }
1040        if (! in_array('workstationCount', $keepArray)) {
1041            unset($entity['workstationCount']);
1042        }
1043        if (! in_array('multipleSlotsAllowed', $keepArray)) {
1044            unset($entity['multipleSlotsAllowed']);
1045        }
1046        if (! in_array('lastChange', $keepArray)) {
1047            unset($entity['lastChange']);
1048        }
1049        if (! in_array('slotTimeInMinutes', $keepArray)) {
1050            unset($entity['slotTimeInMinutes']);
1051        }
1052        if (! in_array('description', $keepArray)) {
1053            unset($entity['description']);
1054        }
1055
1056        return $entity;
1057    }
1058}