Passed
Push — master ( 8edeaa...ea4a1d )
by Davide
77:28 queued 44:42
created

LaravelEventsCalendar::getRepetitionTextString()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 50
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 33
CRAP Score 6

Importance

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

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