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