Passed
Push — master ( 693377...95d81f )
by Davide
75:43
created

LaravelEventsCalendar::uploadImageOnServer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

369
                    $ret .= sprintf(/** @scrutinizer ignore-type */ $format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
Loading history...
370 1
                    break;
371 2
                case '3': //repeatMonthly
372 1
                    $repeatUntil = new DateTime($event->repeat_until);
373 1
                    $repetitionFrequency = self::decodeOnMonthlyKind($event->on_monthly_kind);
374
375
                    //$ret = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
376 1
                    $format = __('laravel-events-calendar::event.the_event_happens_x_until_x');
377 1
                    $ret .= sprintf($format, $repetitionFrequency, $repeatUntil->format('d/m/Y'));
378 1
                    break;
379 1
                case '4': //repeatMultipleDays
380 1
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
381 1
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
382
383
                    // Sort the datas
384
                       usort($singleDaysRepeatDatas, function ($a, $b) {
385 1
                           $a = Carbon::createFromFormat('d/m/Y', $a);
386 1
                           $b = Carbon::createFromFormat('d/m/Y', $b);
387
388 1
                           return strtotime($a) - strtotime($b);
389 1
                       });
390
391 1
                    $ret .= __('laravel-events-calendar::event.the_event_happens_on_this_dates');
392 1
                    $ret .= $dateStart.', ';
393 1
                    $ret .= self::getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
394 1
                    break;
395
            }
396
397 5
        return $ret;
398
    }
399
400
    /***************************************************************************/
401
402
    /**
403
     * Return the map marker icon color.
404
     *
405
     * @param  int  $eventCategoryId
406
     * @return string $ret
407
     */
408 3
    public static function getMapMarkerIconColor(int $eventCategoryId)
409
    {
410 3
        switch ($eventCategoryId) {
411 3
            case 1: //Regular Jam
412
                $ret = 'greenIcon';
413
                break;
414 3
            case 10: // Special Jam
415
                $ret = 'yellowIcon';
416
                break;
417 3
            case 2: // Class
418
                $ret = 'goldIcon';
419
                break;
420 3
            case 3: // Workshop
421 1
                $ret = 'orangeIcon';
422 1
                break;
423 2
            case 6: // Festival
424
            case 16: // Camp / Journey
425 2
                $ret = 'redIcon';
426 2
                break;
427
            case 11: // Underscore
428
                $ret = 'blueIcon';
429
                break;
430
            case 13: // Performance
431
            case 14: // Lecture / Conference / Film
432
            case 17: // Other event
433
                $ret = 'violetIcon';
434
                break;
435
            case 15: // Lab
436
                $ret = 'greyIcon';
437
                break;
438
            case 12: // Teachers Meeting
439
                $ret = 'blackIcon';
440
                break;
441
        }
442
443 3
        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...
444
    }
445
446
    /***************************************************************************/
447
448
    /**
449
     * Remove all special characters from a string - Remove all special characters from a string.
450
     *
451
     * @param  string  $text
452
     * @return string $ret
453
     */
454 5
    public static function cleanString(string $text)
455
    {
456
        // Transform whitespaces to %20 for the URL
457 5
        $text = str_replace(' ', '%20', $text);
458 5
        $text = str_replace('ß', '%DF', $text);
459
460
        $utf8 = [
461 5
            '/[áàâãªä]/u'   =>   'a',
462
            '/[ÁÀÂÃÄ]/u'    =>   'A',
463
            '/[ÍÌÎÏİ]/u'     =>   'I',
464
            '/[íìîïı]/u'     =>   'i',
465
            '/[éèêëěė]/u'     =>   'e',
466
            '/[ÉÈÊË]/u'     =>   'E',
467
            '/[óòôõºöø]/u'   =>   'o',
468
            '/[ÓÒÔÕÖ]/u'    =>   'O',
469
            '/[úùûüüū]/u'     =>   'u',
470
            '/[ÚÙÛÜ]/u'     =>   'U',
471
            '/[çć]/u'       =>   'c',
472
            '/Ç/'           =>   'C',
473
            '/ğ/'           =>   'g',
474
            '/ñ/'           =>   'n',
475
            '/Ñ/'           =>   'N',
476
            '/ř/'           =>   'r',
477
            '/[šş]/u'       =>   's',
478
            '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
479
            '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
480
            '/[“”«»„]/u'    =>   ' ', // Double quote
481
            '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
482
        ];
483 5
        $ret = preg_replace(array_keys($utf8), array_values($utf8), $text);
484
485 5
        return $ret;
486
    }
487
    
488
    // **********************************************************************
489
490
    /**
491
     * Upload image on server.
492
     * $imageFile - the file to upload
493
     * $imageSubdir is the subdir in /storage/app/public/images/..
494
     *
495
     * @param  mixed $imageFile
496
     * @param  string $imageName
497
     * @param  string $imageSubdir
498
     * @param  int $imageWidth
499
     * @param  int $thumbWidth
500
     * @return void
501
     */
502
    public static function uploadImageOnServer($imageFile, string $imageName, string $imageSubdir, int $imageWidth, int $thumbWidth): void
503
    {
504
505
        // Create dir if not exist (in /storage/app/public/images/..)
506
        if (! Storage::disk('public')->has('images/'.$imageSubdir.'/')) {
0 ignored issues
show
Bug introduced by
The type DavideCasiraghi\LaravelEventsCalendar\Storage was not found. Did you mean Storage? If so, make sure to prefix the type with \.
Loading history...
507
            Storage::disk('public')->makeDirectory('images/'.$imageSubdir.'/');
508
        }
509
510
        $destinationPath = 'app/public/images/'.$imageSubdir.'/';
511
512
        // Resize the image with Intervention - http://image.intervention.io/api/resize
513
        // -  resize and store the image to a width of 300 and constrain aspect ratio (auto height)
514
        // - save file as jpg with medium quality
515
        $image = Image::make($imageFile->getRealPath())
0 ignored issues
show
Bug introduced by
The type DavideCasiraghi\LaravelEventsCalendar\Image was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
516
                                ->resize($imageWidth, null,
517
                                    function ($constraint) {
518
                                        $constraint->aspectRatio();
519
                                    })
520
                                ->save(storage_path($destinationPath.$imageName), 75);
521
522
        // Create the thumb
523
        $image->resize($thumbWidth, null,
524
                    function ($constraint) {
525
                        $constraint->aspectRatio();
526
                    })
527
                ->save(storage_path($destinationPath.'thumb_'.$imageName), 75);
528
    }
529
}
530