Test Failed
Push — master ( 7e8e1b...257e11 )
by Davide
31:30 queued 11s
created

LaravelEventsCalendar::formatDatePickerDateForMysql()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.9666
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
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) {
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'));
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 = self::cleanString($address);
272
        $key = 'Ad5KVnAISxX6aHyj6fAnHcKeh30n4W60';
273 4
        $url = 'http://open.mapquestapi.com/geocoding/v1/address?key='.$key.'&location='.$address;
274 4
        
275 4
        //dump($url);
276
        
277 4
        $response = @file_get_contents($url);
278 4
        $response = json_decode($response, true);
279 4
280
        $ret = [];
281 4
        $ret['lat'] = $response['results'][0]['locations'][0]['latLng']['lat'];
282
        $ret['lng'] = $response['results'][0]['locations'][0]['latLng']['lng'];
283
284
        return $ret;
285
    }
286
287
    /***************************************************************************/
288
289
    /**
290
     * Return a string with the list of the collection id separated by comma.
291
     * without any space. eg. "354,320,310".
292
     *
293 2
     * @param  iterable $items
294
     * @return string $ret
295 2
     */
296 2
    public static function getCollectionIdsSeparatedByComma(iterable $items)
297 1
    {
298
        $itemsIds = [];
299 2
        foreach ($items as $item) {
300
            array_push($itemsIds, $item->id);
301 2
        }
302
        $ret = implode(',', $itemsIds);
303
304
        return $ret;
305
    }
306
307
    /***************************************************************************/
308
309
    /**
310
     * Return a string that describe the report misuse reason.
311
     *
312 1
     * @param  int $reason
313
     * @return string $ret
314 1
     */
315
    public static function getReportMisuseReasonDescription(int $reason)
316 1
    {
317 1
        $ret = '';
318 1
        switch ($reason) {
319 1
            case '1':
320 1
                $ret = 'Not about Contact Improvisation';
321 1
                break;
322 1
            case '2':
323 1
                $ret = 'Contains wrong informations';
324 1
                break;
325 1
            case '3':
326 1
                $ret = 'It is not translated in english';
327 1
                break;
328
            case '4':
329
                $ret = 'Other (specify in the message)';
330 1
                break;
331
        }
332
333
        return $ret;
334
    }
335
336
    /***************************************************************************/
337
338
    /**
339
     * Return a string that describe repetition kind in the event show view.
340
     *
341
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
342 5
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition $firstRpDates
343
     * @return string $ret
344 5
     */
345
    public static function getRepetitionTextString(Event $event, EventRepetition $firstRpDates)
346 5
    {
347 5
        $ret = '';
348 2
349 3
        switch ($event->repeat_type) {
350 1
                case '1': // noRepeat
351
                    break;
352
                case '2': // repeatWeekly
353 1
                    $repeatUntil = new DateTime($event->repeat_until);
354 1
355 1
                    // Get the name of the weekly day when the event repeat, if two days, return like "Thursday and Sunday"
356 1
                        $repetitonWeekdayNumbersArray = explode(',', $event->repeat_weekly_on);
357
                        $repetitonWeekdayNamesArray = [];
358
                        foreach ($repetitonWeekdayNumbersArray as $key => $repetitonWeekdayNumber) {
359 1
                            $repetitonWeekdayNamesArray[] = self::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
360
                        }
361
                        // create from an array a string with all the values divided by " and "
362 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
363 1
364 1
                    //$ret = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
365 2
                    $format = __('laravel-events-calendar::event.the_event_happens_every_x_until_x');
366 1
                    $ret .= sprintf($format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
367 1
                    break;
368
                case '3': //repeatMonthly
369
                    $repeatUntil = new DateTime($event->repeat_until);
370 1
                    $repetitionFrequency = self::decodeOnMonthlyKind($event->on_monthly_kind);
371 1
372 1
                    //$ret = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
373 1
                    $format = __('laravel-events-calendar::event.the_event_happens_x_until_x');
374 1
                    $ret .= sprintf($format, $repetitionFrequency, $repeatUntil->format('d/m/Y'));
375 1
                    break;
376
                case '4': //repeatMultipleDays
377
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
378
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
379 1
380 1
                    // Sort the datas
381
                       usort($singleDaysRepeatDatas, function ($a, $b) {
382 1
                           $a = Carbon::createFromFormat('d/m/Y', $a);
383 1
                           $b = Carbon::createFromFormat('d/m/Y', $b);
384
385 1
                           return strtotime($a) - strtotime($b);
386 1
                       });
387 1
388 1
                    $ret .= __('laravel-events-calendar::event.the_event_happens_on_this_dates');
389
                    $ret .= $dateStart.', ';
390
                    $ret .= self::getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
391 5
                    break;
392
            }
393
394
        return $ret;
395
    }
396
397
    /***************************************************************************/
398
399
    /**
400
     * Return the map marker icon color.
401
     *
402 2
     * @param  int  $eventCategoryId
403
     * @return string $ret
404 2
     */
405 2
    public static function getMapMarkerIconColor(int $eventCategoryId)
406
    {
407
        switch ($eventCategoryId) {
408 2
            case 1: //Regular Jam
409 2
                $ret = 'greenIcon';
410 1
                break;
411 1
            case 2: // Class
412 1
            case 3: // Workshop
413
                $ret = 'goldIcon';
414 1
                break;
415 1
            case 6: // Festival
416
            case 16: // Camp / Journey
417
                $ret = 'redIcon';
418
                break;
419
            case 10: // Special Jam
420
            case 11: // Underscore
421
            case 17: // Other event
422
                $ret = 'yellowIcon';
423
                break;
424
            case 12: // Teachers Meeting
425
                $ret = 'orangeIcon';
426
                break;
427
            case 13: // Performance
428
            case 14: // Lecture / Conference / Film
429
                $ret = 'violetIcon';
430
                break;
431
            case 15: // Lab
432
                $ret = 'greyIcon';
433 2
                break;
434
        }
435
436
        return $ret;
437
    }
438
439
    /***************************************************************************/
440
441
    /**
442
     * Remove all special characters from a string - Remove all special characters from a string.
443
     *
444
     * @param  string  $text
445 5
     * @return string $ret
446
     */    
447 5
    
448
    public static function cleanString(string $text) {
449
        // Transform whitespaces to %20 for the URL
450
        $text = str_replace(' ', '%20', $text);
451
        
452
        $utf8 = array(
453
            '/[áàâãªä]/u'   =>   'a',
454
            '/[ÁÀÂÃÄ]/u'    =>   'A',
455
            '/[ÍÌÎÏ]/u'     =>   'I',
456
            '/[íìîï]/u'     =>   'i',
457
            '/[éèêë]/u'     =>   'e',
458
            '/[ÉÈÊË]/u'     =>   'E',
459
            '/[óòôõºöø]/u'   =>   'o',
460
            '/[ÓÒÔÕÖ]/u'    =>   'O',
461
            '/[úùûü]/u'     =>   'u',
462
            '/[ÚÙÛÜ]/u'     =>   'U',
463
            '/ç/'           =>   'c',
464
            '/Ç/'           =>   'C',
465
            '/ğ/'           =>   'g',
466 5
            '/ñ/'           =>   'n',
467
            '/Ñ/'           =>   'N',
468 5
            '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
469
            '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
470
            '/[“”«»„]/u'    =>   ' ', // Double quote
471
            '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
472
        ];
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ']', expecting ',' or ')' on line 472 at column 8
Loading history...
473
        $ret = preg_replace(array_keys($utf8), array_values($utf8), $text);
474
475
        return $ret;
476
    }
477
}
478