Passed
Push — master ( c3fe8c...b4b769 )
by Davide
81:00 queued 49:19
created

LaravelEventsCalendar::getMapMarkerIconColor()   C

Complexity

Conditions 13
Paths 13

Size

Total Lines 32
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 53.414

Importance

Changes 0
Metric Value
eloc 28
c 0
b 0
f 0
dl 0
loc 32
ccs 11
cts 29
cp 0.3793
rs 6.6166
cc 13
nc 13
nop 1
crap 53.414

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
        $address = LaravelEventsCalendar::cleanString($address);
272
        
273 4
        $key = 'Ad5KVnAISxX6aHyj6fAnHcKeh30n4W60';
274 4
        $response = @file_get_contents('http://open.mapquestapi.com/geocoding/v1/address?key='.$key.'&location='.$address);
275 4
        $response = json_decode($response, true);
276
277 4
        $ret = [];
278 4
        $ret['lat'] = $response['results'][0]['locations'][0]['latLng']['lat'];
279 4
        $ret['lng'] = $response['results'][0]['locations'][0]['latLng']['lng'];
280
281 4
        return $ret;
282
    }
283
284
    /***************************************************************************/
285
286
    /**
287
     * Return a string with the list of the collection id separated by comma.
288
     * without any space. eg. "354,320,310".
289
     *
290
     * @param  iterable $items
291
     * @return string $ret
292
     */
293 2
    public static function getCollectionIdsSeparatedByComma(iterable $items)
294
    {
295 2
        $itemsIds = [];
296 2
        foreach ($items as $item) {
297 1
            array_push($itemsIds, $item->id);
298
        }
299 2
        $ret = implode(',', $itemsIds);
300
301 2
        return $ret;
302
    }
303
304
    /***************************************************************************/
305
306
    /**
307
     * Return a string that describe the report misuse reason.
308
     *
309
     * @param  int $reason
310
     * @return string $ret
311
     */
312 1
    public static function getReportMisuseReasonDescription(int $reason)
313
    {
314 1
        $ret = '';
315
        switch ($reason) {
316 1
            case '1':
317 1
                $ret = 'Not about Contact Improvisation';
318 1
                break;
319 1
            case '2':
320 1
                $ret = 'Contains wrong informations';
321 1
                break;
322 1
            case '3':
323 1
                $ret = 'It is not translated in english';
324 1
                break;
325 1
            case '4':
326 1
                $ret = 'Other (specify in the message)';
327 1
                break;
328
        }
329
330 1
        return $ret;
331
    }
332
333
    /***************************************************************************/
334
335
    /**
336
     * Return a string that describe repetition kind in the event show view.
337
     *
338
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
339
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition $firstRpDates
340
     * @return string $ret
341
     */
342 5
    public static function getRepetitionTextString(Event $event, EventRepetition $firstRpDates)
343
    {
344 5
        $ret = '';
345
346 5
        switch ($event->repeat_type) {
347 5
                case '1': // noRepeat
348 2
                    break;
349 3
                case '2': // repeatWeekly
350 1
                    $repeatUntil = new DateTime($event->repeat_until);
351
352
                    // Get the name of the weekly day when the event repeat, if two days, return like "Thursday and Sunday"
353 1
                        $repetitonWeekdayNumbersArray = explode(',', $event->repeat_weekly_on);
354 1
                        $repetitonWeekdayNamesArray = [];
355 1
                        foreach ($repetitonWeekdayNumbersArray as $key => $repetitonWeekdayNumber) {
356 1
                            $repetitonWeekdayNamesArray[] = self::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
357
                        }
358
                        // create from an array a string with all the values divided by " and "
359 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
360
361
                    //$ret = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
362 1
                    $format = __('laravel-events-calendar::event.the_event_happens_every_x_until_x');
363 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

363
                    $ret .= sprintf(/** @scrutinizer ignore-type */ $format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
Loading history...
364 1
                    break;
365 2
                case '3': //repeatMonthly
366 1
                    $repeatUntil = new DateTime($event->repeat_until);
367 1
                    $repetitionFrequency = self::decodeOnMonthlyKind($event->on_monthly_kind);
368
369
                    //$ret = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
370 1
                    $format = __('laravel-events-calendar::event.the_event_happens_x_until_x');
371 1
                    $ret .= sprintf($format, $repetitionFrequency, $repeatUntil->format('d/m/Y'));
372 1
                    break;
373 1
                case '4': //repeatMultipleDays
374 1
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
375 1
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
376
377
                    // Sort the datas
378
                       usort($singleDaysRepeatDatas, function ($a, $b) {
379 1
                           $a = Carbon::createFromFormat('d/m/Y', $a);
380 1
                           $b = Carbon::createFromFormat('d/m/Y', $b);
381
382 1
                           return strtotime($a) - strtotime($b);
383 1
                       });
384
385 1
                    $ret .= __('laravel-events-calendar::event.the_event_happens_on_this_dates');
386 1
                    $ret .= $dateStart.', ';
387 1
                    $ret .= self::getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
388 1
                    break;
389
            }
390
391 5
        return $ret;
392
    }
393
394
    /***************************************************************************/
395
396
    /**
397
     * Return the map marker icon color.
398
     *
399
     * @param  int  $eventCategoryId
400
     * @return string $ret
401
     */
402 2
    public static function getMapMarkerIconColor(int $eventCategoryId)
403
    {
404 2
        switch ($eventCategoryId) {
405 2
            case 1: //Regular Jam
406
                $ret = 'greenIcon';
407
                break;
408 2
            case 2: // Class
409 2
            case 3: // Workshop
410 1
                $ret = 'goldIcon';
411 1
                break;
412 1
            case 6: // Festival
413
            case 16: // Camp / Journey
414 1
                $ret = 'redIcon';
415 1
                break;
416
            case 10: // Special Jam
417
            case 11: // Underscore
418
            case 17: // Other event
419
                $ret = 'yellowIcon';
420
                break;
421
            case 12: // Teachers Meeting
422
                $ret = 'orangeIcon';
423
                break;
424
            case 13: // Performance
425
            case 14: // Lecture / Conference / Film
426
                $ret = 'violetIcon';
427
                break;
428
            case 15: // Lab
429
                $ret = 'greyIcon';
430
                break;
431
        }
432
433 2
        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...
434
    }
435
    
436
    /***************************************************************************/
437
438
    /**
439
     * Remove all special characters from a string - Remove all special characters from a string
440
     *
441
     * @param  string  $text
442
     * @return string $ret
443
     */    
444
    
445 5
    public static function cleanString(string $text) {
446
        // Transform whitespaces to %20 for the URL
447 5
        $text = str_replace(' ', '%20', $text);
448
        
449
        $utf8 = array(
450 5
            '/[áàâãªä]/u'   =>   'a',
451
            '/[ÁÀÂÃÄ]/u'    =>   'A',
452
            '/[ÍÌÎÏ]/u'     =>   'I',
453
            '/[íìîï]/u'     =>   'i',
454
            '/[éèêë]/u'     =>   'e',
455
            '/[ÉÈÊË]/u'     =>   'E',
456
            '/[óòôõºöø]/u'   =>   'o',
457
            '/[ÓÒÔÕÖ]/u'    =>   'O',
458
            '/[úùûü]/u'     =>   'u',
459
            '/[ÚÙÛÜ]/u'     =>   'U',
460
            '/ç/'           =>   'c',
461
            '/Ç/'           =>   'C',
462
            '/ğ/'           =>   'g',
463
            '/ñ/'           =>   'n',
464
            '/Ñ/'           =>   'N',
465
            '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
466
            '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
467
            '/[“”«»„]/u'    =>   ' ', // Double quote
468
            '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
469
        );
470 5
        $ret = preg_replace(array_keys($utf8), array_values($utf8), $text);
471
        
472 5
        return $ret;
473
    }
474
    
475
}
476