Passed
Push — master ( 3fc2b2...d81b13 )
by Davide
53:21
created

LaravelEventsCalendar   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 421
Duplicated Lines 0 %

Test Coverage

Coverage 89.55%

Importance

Changes 26
Bugs 9 Features 9
Metric Value
wmc 52
eloc 195
c 26
b 9
f 9
dl 0
loc 421
ccs 180
cts 201
cp 0.8955
rs 7.44

13 Methods

Rating   Name   Duplication   Size   Complexity  
A weekdayNumberOfMonth() 0 22 5
A getStringFromArraySeparatedByComma() 0 15 3
A formatDatePickerDateForMysql() 0 13 3
A isWeekDay() 0 8 2
A dayOfMonthFromTheEnd() 0 7 1
A decodeRepeatWeeklyOn() 0 15 1
A weekOfMonthFromTheEnd() 0 29 5
B getRepetitionTextString() 0 50 6
A getVenueGpsCoordinates() 0 11 1
A getReportMisuseReasonDescription() 0 19 5
A getCollectionIdsSeparatedByComma() 0 9 2
A decodeOnMonthlyKind() 0 42 5
C getMapMarkerIconColor() 0 30 13

How to fix   Complexity   

Complex Class

Complex classes like LaravelEventsCalendar often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use LaravelEventsCalendar, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar;
4
5
use Carbon\Carbon;
6
use DateTime;
7
use DavideCasiraghi\LaravelEventsCalendar\Models\Event;
8
use DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition;
9
10
class LaravelEventsCalendar
11
{
12
    /***************************************************************************/
13
14
    /**
15
     * Format a date from datepicker (d/m/Y) to a format ready to be stored on DB (Y-m-d).
16
     * If the date picker date is null return today's date.
17
     * the PARAM is a date in the d/m/Y format - the RETURN is a date in the Y-m-d format.
18
     * If $todaysDateIfNull = 1, when the date is null return the date of today.
19
     *
20
     * @param  string  $DatePickerDate
21
     * @param  bool  $todaysDateIfNull
22
     * @return string  $ret
23
     */
24 1
    public static function formatDatePickerDateForMysql($DatePickerDate, bool $todaysDateIfNull = null)
25
    {
26 1
        if ($DatePickerDate) {
27 1
            [$tid, $tim, $tiy] = explode('/', $DatePickerDate);
28 1
            $ret = "$tiy-$tim-$tid";
29 1
        } elseif ($todaysDateIfNull) {
30 1
            date_default_timezone_set('Europe/Rome');
31 1
            $ret = date('Y-m-d', time());
32
        } else {
33 1
            $ret = '';
34
        }
35
36 1
        return $ret;
37
    }
38
39
    /***************************************************************************/
40
41
    /**
42
     * It returns a string that is composed by the array values separated by a comma.
43
     *
44
     * @param  iterable  $items
45
     * @return string  $ret
46
     */
47 4
    public static function getStringFromArraySeparatedByComma(iterable $items)
48
    {
49 4
        $ret = '';
50 4
        $i = 0;
51 4
        $len = count($items); // to put "," to all items except the last
52
53 4
        foreach ($items as $key => $item) {
54 4
            $ret .= $item;
55 4
            if ($i != $len - 1) {  // not last
56 2
                $ret .= ', ';
57
            }
58 4
            $i++;
59
        }
60
61 4
        return $ret;
62
    }
63
64
    /***************************************************************************/
65
66
    /**
67
     * Check the date and return true if the weekday is the one specified in $dayOfTheWeek. eg. if $dayOfTheWeek = 3, is true if the date is a Wednesday
68
     * $dayOfTheWeek: 1|2|3|4|5|6|7 (MONDAY-SUNDAY)
69
     * https://stackoverflow.com/questions/2045736/getting-all-dates-for-mondays-and-tuesdays-for-the-next-year.
70
     *
71
     * @param  string $date
72
     * @param  int $dayOfTheWeek
73
     * @return bool
74
     */
75 4
    public static function isWeekDay(string $date, int $dayOfTheWeek)
76
    {
77
        // Fix the bug that was avoiding to save Sunday. Date 'w' identify sunday as 0 and not 7.
78 4
        if ($dayOfTheWeek == 7) {
79 1
            $dayOfTheWeek = 0;
80
        }
81
82 4
        return date('w', strtotime($date)) == $dayOfTheWeek;
83
    }
84
85
    /***************************************************************************/
86
87
    /**
88
     * GET number of the specified weekday in this month (1 for the first).
89
     * $dateTimestamp - unix timestramp of the date specified
90
     * $dayOfWeekValue -  1 (for Monday) through 7 (for Sunday)
91
     * Return the number of the week in the month of the weekday specified.
92
     * @param  string $dateTimestamp
93
     * @param  string $dayOfWeekValue
94
     * @return int
95
     */
96 2
    public static function weekdayNumberOfMonth(string $dateTimestamp, string $dayOfWeekValue)
97
    {
98 2
        $cut = substr($dateTimestamp, 0, 8);
99 2
        $daylen = 86400;
100 2
        $timestamp = strtotime($dateTimestamp);
101 2
        $first = strtotime($cut.'01');
102 2
        $elapsed = (($timestamp - $first) / $daylen) + 1;
103 2
        $i = 1;
104 2
        $weeks = 0;
105 2
        for ($i == 1; $i <= $elapsed; $i++) {
106 2
            $dayfind = $cut.(strlen((string) $i) < 2 ? '0'.$i : $i);
107 2
            $daytimestamp = strtotime($dayfind);
108 2
            $day = strtolower(date('N', $daytimestamp));
109 2
            if ($day == strtolower($dayOfWeekValue)) {
110 1
                $weeks++;
111
            }
112
        }
113 2
        if ($weeks == 0) {
0 ignored issues
show
introduced by
The condition $weeks == 0 is always true.
Loading history...
114 1
            $weeks++;
115
        }
116
117 2
        return $weeks;
118
    }
119
120
    /***************************************************************************/
121
122
    /**
123
     * GET number of week from the end of the month - https://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month
124
     * Week of the month = Week of the year - Week of the year of first day of month + 1.
125
     * Return the number of the week in the month of the day specified
126
     * $when - unix timestramp of the date specified.
127
     *
128
     * @param  int $when
129
     * @return int
130
     */
131 2
    public static function weekOfMonthFromTheEnd(int $when)
132
    {
133 2
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
134 2
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
135 2
        $dayDifference = (int) $lastDayOfMonth - (int) $numberOfDayOfTheMonth;
136
137
        switch (true) {
138 2
            case $dayDifference < 7:
139 1
                $weekFromTheEnd = 1;
140 1
                break;
141
142 2
            case $dayDifference < 14:
143 1
                $weekFromTheEnd = 2;
144 1
                break;
145
146 2
            case $dayDifference < 21:
147 2
                $weekFromTheEnd = 3;
148 2
                break;
149
150 1
            case $dayDifference < 28:
151 1
                $weekFromTheEnd = 4;
152 1
                break;
153
154
            default:
155 1
                $weekFromTheEnd = 5;
156 1
                break;
157
        }
158
159 2
        return $weekFromTheEnd;
160
    }
161
162
    /***************************************************************************/
163
164
    /**
165
     * GET number of day from the end of the month.
166
     * $when - unix timestramp of the date specified
167
     * Return the number of day of the month from end.
168
     *
169
     * @param  int $when
170
     * @return int
171
     */
172 2
    public static function dayOfMonthFromTheEnd(int $when)
173
    {
174 2
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
175 2
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
176 2
        $dayDifference = (int) $lastDayOfMonth - (int) $numberOfDayOfTheMonth;
177
178 2
        return $dayDifference;
179
    }
180
181
    /***************************************************************************/
182
183
    /**
184
     * Decode the event repeat_weekly_on field - used in event.show.
185
     * Return a string like "Monday".
186
     *
187
     * @param  string $repeatWeeklyOn
188
     * @return string
189
     */
190 2
    public static function decodeRepeatWeeklyOn(string $repeatWeeklyOn)
191
    {
192
        $weekdayArray = [
193 2
            '',
194 2
            __('laravel-events-calendar::general.monday'),
195 2
            __('laravel-events-calendar::general.tuesday'),
196 2
            __('laravel-events-calendar::general.wednesday'),
197 2
            __('laravel-events-calendar::general.thursday'),
198 2
            __('laravel-events-calendar::general.friday'),
199 2
            __('laravel-events-calendar::general.saturday'),
200 2
            __('laravel-events-calendar::general.sunday'),
201
        ];
202 2
        $ret = $weekdayArray[$repeatWeeklyOn];
203
204 2
        return $ret;
205
    }
206
207
    /***************************************************************************/
208
209
    /**
210
     * Decode the event on_monthly_kind field - used in event.show.
211
     * Return a string like "the 4th to last Thursday of the month".
212
     *
213
     * @param  string $onMonthlyKindCode
214
     * @return string
215
     */
216 2
    public static function decodeOnMonthlyKind(string $onMonthlyKindCode)
217
    {
218 2
        $ret = '';
219 2
        $onMonthlyKindCodeArray = explode('|', $onMonthlyKindCode);
220
        $weekDays = [
221 2
            '',
222 2
            __('laravel-events-calendar::general.monday'),
223 2
            __('laravel-events-calendar::general.tuesday'),
224 2
            __('laravel-events-calendar::general.wednesday'),
225 2
            __('laravel-events-calendar::general.thursday'),
226 2
            __('laravel-events-calendar::general.friday'),
227 2
            __('laravel-events-calendar::general.saturday'),
228 2
            __('laravel-events-calendar::general.sunday'),
229
        ];
230
231
        //dd($onMonthlyKindCodeArray);
232 2
        switch ($onMonthlyKindCodeArray[0]) {
233 2
            case '0':  // 0|7 eg. the 7th day of the month
234 2
                $dayNumber = $onMonthlyKindCodeArray[1];
235 2
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
236 2
                $ret = sprintf($format, __('laravel-events-calendar::general.day'));
0 ignored issues
show
Bug introduced by
It seems like __('laravel-events-calendar::general.day') can also be of type array and array; however, parameter $args of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

236
                $ret = sprintf($format, /** @scrutinizer ignore-type */ __('laravel-events-calendar::general.day'));
Loading history...
Bug introduced by
It seems like $format can also be of type array and array; however, parameter $format of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

236
                $ret = sprintf(/** @scrutinizer ignore-type */ $format, __('laravel-events-calendar::general.day'));
Loading history...
237 2
                break;
238 1
            case '1':  // 1|2|4 eg. the 2nd Thursday of the month
239 1
                $dayNumber = $onMonthlyKindCodeArray[1];
240 1
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
241 1
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
242 1
                $ret = sprintf($format, $weekDay);
243 1
                break;
244 1
            case '2': // 2|20 eg. the 21st to last day of the month
245 1
                $dayNumber = (int) $onMonthlyKindCodeArray[1] + 1;
246 1
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_to_last_x_of_the_month');
247 1
                $ret = sprintf($format, __('laravel-events-calendar::general.day'));
248 1
                break;
249 1
            case '3': // 3|3|4 eg. the 4th to last Thursday of the month
250 1
                $dayNumber = (int) $onMonthlyKindCodeArray[1] + 1;
251 1
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
252 1
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_to_last_x_of_the_month');
253 1
                $ret = sprintf($format, $weekDay);
254 1
                break;
255
        }
256
257 2
        return $ret;
258
    }
259
260
    /***************************************************************************/
261
262
    /**
263
     * Return the GPS coordinates of the venue
264
     * https://developer.mapquest.com/.
265
     *
266
     * @param  string $address
267
     * @return array $ret
268
     */
269 4
    public static function getVenueGpsCoordinates(string $address)
270
    {
271 4
        $key = 'Ad5KVnAISxX6aHyj6fAnHcKeh30n4W60';
272 4
        $response = @file_get_contents('http://open.mapquestapi.com/geocoding/v1/address?key='.$key.'&location='.$address);
273 4
        $response = json_decode($response, true);
274
275 4
        $ret = [];
276 4
        $ret['lat'] = $response['results'][0]['locations'][0]['latLng']['lat'];
277 4
        $ret['lng'] = $response['results'][0]['locations'][0]['latLng']['lng'];
278
279 4
        return $ret;
280
    }
281
282
    /***************************************************************************/
283
284
    /**
285
     * Return a string with the list of the collection id separated by comma.
286
     * without any space. eg. "354,320,310".
287
     *
288
     * @param  iterable $items
289
     * @return string $ret
290
     */
291 2
    public static function getCollectionIdsSeparatedByComma(iterable $items)
292
    {
293 2
        $itemsIds = [];
294 2
        foreach ($items as $item) {
295 1
            array_push($itemsIds, $item->id);
296
        }
297 2
        $ret = implode(',', $itemsIds);
298
299 2
        return $ret;
300
    }
301
302
    /***************************************************************************/
303
304
    /**
305
     * Return a string that describe the report misuse reason.
306
     *
307
     * @param  int $reason
308
     * @return string $ret
309
     */
310 1
    public static function getReportMisuseReasonDescription(int $reason)
311
    {
312 1
        $ret = '';
313
        switch ($reason) {
314 1
            case '1':
315 1
                $ret = 'Not about Contact Improvisation';
316 1
                break;
317 1
            case '2':
318 1
                $ret = 'Contains wrong informations';
319 1
                break;
320 1
            case '3':
321 1
                $ret = 'It is not translated in english';
322 1
                break;
323 1
            case '4':
324 1
                $ret = 'Other (specify in the message)';
325 1
                break;
326
        }
327
328 1
        return $ret;
329
    }
330
331
    /***************************************************************************/
332
333
    /**
334
     * Return a string that describe repetition kind in the event show view.
335
     *
336
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
337
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition $firstRpDates
338
     * @return string $ret
339
     */
340 5
    public static function getRepetitionTextString(Event $event, EventRepetition $firstRpDates)
341
    {
342 5
        $ret = '';
343
344 5
        switch ($event->repeat_type) {
345 5
                case '1': // noRepeat
346 2
                    break;
347 3
                case '2': // repeatWeekly
348 1
                    $repeatUntil = new DateTime($event->repeat_until);
349
350
                    // Get the name of the weekly day when the event repeat, if two days, return like "Thursday and Sunday"
351 1
                        $repetitonWeekdayNumbersArray = explode(',', $event->repeat_weekly_on);
352 1
                        $repetitonWeekdayNamesArray = [];
353 1
                        foreach ($repetitonWeekdayNumbersArray as $key => $repetitonWeekdayNumber) {
354 1
                            $repetitonWeekdayNamesArray[] = self::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
355
                        }
356
                        // create from an array a string with all the values divided by " and "
357 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
358
359
                    //$ret = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
360 1
                    $format = __('laravel-events-calendar::event.the_event_happens_every_x_until_x');
361 1
                    $ret .= sprintf($format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
0 ignored issues
show
Bug introduced by
It seems like $format can also be of type array and array; however, parameter $format of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

361
                    $ret .= sprintf(/** @scrutinizer ignore-type */ $format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
Loading history...
362 1
                    break;
363 2
                case '3': //repeatMonthly
364 1
                    $repeatUntil = new DateTime($event->repeat_until);
365 1
                    $repetitionFrequency = self::decodeOnMonthlyKind($event->on_monthly_kind);
366
367
                    //$ret = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
368 1
                    $format = __('laravel-events-calendar::event.the_event_happens_x_until_x');
369 1
                    $ret .= sprintf($format, $repetitionFrequency, $repeatUntil->format('d/m/Y'));
370 1
                    break;
371 1
                case '4': //repeatMultipleDays
372 1
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
373 1
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
374
375
                    // Sort the datas
376
                       usort($singleDaysRepeatDatas, function ($a, $b) {
377 1
                           $a = Carbon::createFromFormat('d/m/Y', $a);
378 1
                           $b = Carbon::createFromFormat('d/m/Y', $b);
379
380 1
                           return strtotime($a) - strtotime($b);
381 1
                       });
382
383 1
                    $ret .= __('laravel-events-calendar::event.the_event_happens_on_this_dates');
384 1
                    $ret .= $dateStart.', ';
385 1
                    $ret .= self::getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
386 1
                    break;
387
            }
388
389 5
        return $ret;
390
    }
391
    
392
    
393
    /***************************************************************************/
394
395
    /**
396
     * Return the map marker icon color
397
     *
398
     * @param  int  $eventCategoryId
399
     * @return string $ret
400
     */
401 1
    public static function getMapMarkerIconColor(int $eventCategoryId){
402 1
        switch ($eventCategoryId) {
403 1
            case 1: //Regular Jam
404
                $ret = 'greenIcon';
405
                break;
406 1
            case 2: // Class
407 1
            case 3: // Workshop
408 1
                $ret = 'goldIcon';
409 1
                break;
410
            case 6: // Festival
411
            case 16: // Camp / Journey
412
                $ret = 'redIcon';
413
                break;
414
            case 10: // Special Jam
415
            case 11: // Underscore
416
            case 17: // Other event
417
                $ret = 'yellowIcon';
418
                break;
419
            case 12: // Teachers Meeting
420
                $ret = 'orangeIcon';
421
                break;
422
            case 13: // Performance
423
            case 14: // Lecture / Conference / Film
424
                $ret = 'violetIcon';
425
                break; 
426
            case 15: // Lab
427
                $ret = 'greyIcon';
428
                break;   
429
        }
430 1
        return $ret;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ret does not seem to be defined for all execution paths leading up to this point.
Loading history...
431
    }
432
    
433
    
434
}
435