Completed
Pull Request — master (#243)
by Luc
05:28
created

CalendarFactory::openingHoursToArray()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 12
nc 2
nop 1
1
<?php
2
3
namespace CultuurNet\UDB3;
4
5
use CultuurNet\UDB3\Cdb\DateTimeFactory;
6
use ValueObjects\DateTime\Time;
7
use ValueObjects\DateTime\WeekDay;
8
9
class CalendarFactory implements CalendarFactoryInterface
10
{
11
    /**
12
     * @inheritdoc
13
     */
14
    public function createFromCdbCalendar(\CultureFeed_Cdb_Data_Calendar $cdbCalendar)
15
    {
16
        //
17
        // Get the calendar type.
18
        //
19
        $calendarType = '';
20
        if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_Permanent) {
21
            $calendarType = 'permanent';
22
        } else if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_PeriodList) {
23
            $calendarType = 'periodic';
24
        } else if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_TimestampList) {
25
            $calendarType = 'single';
26
            if (iterator_count($cdbCalendar) > 1) {
27
                $calendarType = 'multiple';
28
            }
29
        }
30
31
        //
32
        // Get the start day.
33
        //
34
        $cdbCalendar->rewind();
35
        $startDateString = '';
36
        if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_PeriodList) {
37
            /** @var \CultureFeed_Cdb_Data_Calendar_Period $period */
38
            $period = $cdbCalendar->current();
39
            $startDateString = $period->getDateFrom() . 'T00:00:00';
40 View Code Duplication
        } else if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_TimestampList) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
41
            /** @var \CultureFeed_Cdb_Data_Calendar_Timestamp $timestamp */
42
            $timestamp = $cdbCalendar->current();
43
            if ($timestamp->getStartTime()) {
44
                $startDateString = $timestamp->getDate() . 'T' . $timestamp->getStartTime();
45
            } else {
46
                $startDateString = $timestamp->getDate() . 'T00:00:00';
47
            }
48
        }
49
        $startDate = !empty($startDateString) ? DateTimeFactory::dateTimeFromDateString($startDateString) : null;
50
51
        //
52
        // Get the end day.
53
        //
54
        $cdbCalendar->rewind();
55
        $endDateString = '';
56
        if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_PeriodList) {
57
            /** @var \CultureFeed_Cdb_Data_Calendar_Period $period */
58
            $period = $cdbCalendar->current();
59
            $endDateString = $period->getDateTo() . 'T00:00:00';
60
        } else if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_TimestampList) {
61
            $firstTimestamp = $cdbCalendar->current();
62
            /** @var \CultureFeed_Cdb_Data_Calendar_Timestamp $timestamp */
63
            $cdbCalendarAsArray = iterator_to_array($cdbCalendar);
64
            $timestamp = iterator_count($cdbCalendar) > 1 ? end($cdbCalendarAsArray) : $firstTimestamp;
65 View Code Duplication
            if ($timestamp->getEndTime()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
66
                $endDateString = $timestamp->getDate() . 'T' . $timestamp->getEndTime();
67
            } else {
68
                $endTime = $timestamp->getStartTime() ? $timestamp->getStartTime() : '00:00:00';
69
                $endDateString = $timestamp->getDate() . 'T' . $endTime;
70
            }
71
        }
72
        $endDate = !empty($endDateString) ? DateTimeFactory::dateTimeFromDateString($endDateString) : null;
73
74
        //
75
        // Get the time stamps.
76
        //
77
        $cdbCalendar->rewind();
78
        $timestamps = [];
79
        if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_TimestampList) {
80
            while ($cdbCalendar->valid()) {
81
                /** @var \CultureFeed_Cdb_Data_Calendar_Timestamp $timestamp */
82
                $timestamp = $cdbCalendar->current();
83
                $cdbCalendar->next();
84
85
                if ($timestamp->getStartTime()) {
86
                    $startDateString = $timestamp->getDate() . 'T' . $timestamp->getStartTime();
87
88 View Code Duplication
                    if ($timestamp->getEndTime()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
                        $endDateString = $timestamp->getDate() . 'T' . $timestamp->getEndTime();
90
                    } else {
91
                        $endTime = $timestamp->getStartTime() ? $timestamp->getStartTime() : '00:00:00';
92
                        $endDateString = $timestamp->getDate() . 'T' . $endTime;
93
                    }
94
                }
95
96
                $timestamps[] = new Timestamp(
97
                    DateTimeFactory::dateTimeFromDateString($startDateString),
98
                    DateTimeFactory::dateTimeFromDateString($endDateString)
99
                );
100
            }
101
        }
102
103
        //
104
        // Get the opening hours.
105
        //
106
        $cdbCalendar->rewind();
107
        $openingHoursAsArray = [];
108
109
        $weekSchema = null;
110
        if ($cdbCalendar instanceof \CultureFeed_Cdb_Data_Calendar_PeriodList) {
111
            $period = $cdbCalendar->current();
112
            $weekSchema = $period->getWeekScheme();
113
        } else if ($cdbCalendar instanceof  \CultureFeed_Cdb_Data_Calendar_Permanent) {
114
            $weekSchema = $cdbCalendar->getWeekScheme();
115
        }
116
117
        if ($weekSchema) {
118
            $openingHours = $this->createOpeningHoursFromWeekScheme(
119
                $weekSchema
120
            );
121
122
            $openingHoursAsArray = $this->openingHoursToArray($openingHours);
123
        }
124
125
        //
126
        // Create the calendar value object.
127
        //
128
        return new Calendar(
129
            CalendarType::fromNative($calendarType),
130
            $startDate,
131
            $endDate,
132
            $timestamps,
133
            $openingHoursAsArray
134
        );
135
    }
136
137
    /**
138
     * @param \CultureFeed_Cdb_Data_Calendar_Weekscheme|null $weekScheme
139
     * @return Calendar
140
     */
141
    public function createFromWeekScheme(
142
        \CultureFeed_Cdb_Data_Calendar_Weekscheme $weekScheme = null
143
    ) {
144
        $openingHoursAsArray = [];
145
146
        if ($weekScheme) {
147
            $openingHours = $this->createOpeningHoursFromWeekScheme($weekScheme);
148
            $openingHoursAsArray = $this->openingHoursToArray($openingHours);
149
        }
150
151
        return new Calendar(
152
            CalendarType::PERMANENT(),
153
            null,
154
            null,
155
            [],
156
            $openingHoursAsArray
157
        );
158
    }
159
160
    /**
161
     * @param \CultureFeed_Cdb_Data_Calendar_Weekscheme $weekScheme
162
     * @return OpeningHour[]
163
     */
164
    private function createOpeningHoursFromWeekScheme(
165
        \CultureFeed_Cdb_Data_Calendar_Weekscheme $weekScheme
166
    ) {
167
        $days = $weekScheme->getDays();
168
169
        /** @var OpeningHour[] $openingHours */
170
        $openingHours = [];
171
        foreach ($days as $day) {
172
            if ($day->isOpen()) {
173
                /** @var \CultureFeed_Cdb_Data_Calendar_OpeningTime[] $openingTimes */
174
                $openingTimes = $day->getOpeningTimes();
175
176
                $opens = \DateTime::createFromFormat(
177
                    'H:i:s',
178
                    $openingTimes ? $openingTimes[0]->getOpenFrom() : '00:00:00'
179
                );
180
                $closes = \DateTime::createFromFormat(
181
                    'H:i:s',
182
                    $openingTimes ? $openingTimes[0]->getOpenTill() : '00:00:00'
183
                );
184
185
                $newOpeningHour = new OpeningHour(
186
                    WeekDay::fromNative(ucfirst($day->getDayName())),
187
                    Time::fromNativeDateTime($opens),
0 ignored issues
show
Security Bug introduced by
It seems like $opens defined by \DateTime::createFromFor...penFrom() : '00:00:00') on line 176 can also be of type false; however, ValueObjects\DateTime\Time::fromNativeDateTime() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
188
                    $closes ? Time::fromNativeDateTime($closes) : Time::fromNativeDateTime($opens)
0 ignored issues
show
Security Bug introduced by
It seems like $opens defined by \DateTime::createFromFor...penFrom() : '00:00:00') on line 176 can also be of type false; however, ValueObjects\DateTime\Time::fromNativeDateTime() does only seem to accept object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
189
                );
190
191
                $merged = false;
192
                foreach ($openingHours as $openingHour) {
193
                    if ($openingHour->equalHours($newOpeningHour)) {
194
                        $openingHour->mergeWeekday($newOpeningHour);
195
                        $merged = true;
196
                        break;
197
                    }
198
                }
199
200
                if (!$merged) {
201
                    $openingHours[] = $newOpeningHour;
202
                }
203
            }
204
        }
205
206
        return $openingHours;
207
    }
208
209
    /**
210
     * @param array $openingHours
211
     * @return array
212
     */
213
    private function openingHoursToArray(array $openingHours)
214
    {
215
        $openingHoursAsArray = [];
216
217
        if (count($openingHours) > 0) {
218
            foreach ($openingHours as $openingHour) {
219
                $openingHoursAsArray[] = [
220
                    'dayOfWeek' => array_map(
221
                        function (WeekDay $weekDay) {
222
                            return strtolower($weekDay->toNative());
223
                        },
224
                        $openingHour->getWeekDays()
225
                    ),
226
                    'opens' => $openingHour->getOpens()->toNativeDateTime()->format('H:i'),
227
                    'closes' => (string)$openingHour->getCloses()->toNativeDateTime()->format('H:i'),
228
                ];
229
            }
230
        }
231
232
        return $openingHoursAsArray;
233
    }
234
}
235