Passed
Push — master ( 37be1e...50c0b2 )
by Davide
25:45
created

LaravelEventsCalendar   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 316
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 11
Bugs 2 Features 5
Metric Value
wmc 34
eloc 128
c 11
b 2
f 5
dl 0
loc 316
ccs 120
cts 130
cp 0.9231
rs 9.68

10 Methods

Rating   Name   Duplication   Size   Complexity  
A formatDatePickerDateForMysql() 0 13 3
A getStringFromArraySeparatedByComma() 0 15 3
A weekdayNumberOfMonth() 0 22 5
A isWeekDay() 0 8 2
A weekOfMonthFromTheEnd() 0 29 5
A dayOfMonthFromTheEnd() 0 7 1
A decodeRepeatWeeklyOn() 0 15 1
A getVenueGpsCoordinates() 0 11 1
A decodeOnMonthlyKind() 0 59 5
B getOrdinalIndicator() 0 18 8
1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar;
4
5
class LaravelEventsCalendar
6
{
7
    /***************************************************************************/
8
9
    /**
10
     * Format a date from datepicker (d/m/Y) to a format ready to be stored on DB (Y-m-d).
11
     * If the date picker date is null return today's date.
12
     * the PARAM is a date in the d/m/Y format - the RETURN is a date in the Y-m-d format.
13
     * If $todaysDateIfNull = 1, when the date is null return the date of today.
14
     *
15
     * @param  string  $DatePickerDate
16
     * @param  bool  $todaysDateIfNull
17
     * @return string  $ret
18
     */
19 1
    public static function formatDatePickerDateForMysql($DatePickerDate, $todaysDateIfNull = 0)
20
    {
21 1
        if ($DatePickerDate) {
22 1
            [$tid, $tim, $tiy] = explode('/', $DatePickerDate);
23 1
            $ret = "$tiy-$tim-$tid";
24 1
        } elseif ($todaysDateIfNull) {
25 1
            date_default_timezone_set('Europe/Rome');
26 1
            $ret = date('Y-m-d', time());
27
        } else {
28 1
            $ret = null;
29
        }
30
31 1
        return $ret;
32
    }
33
34
    /***************************************************************************/
35
36
    /**
37
     * It returns a string that is composed by the array values separated by a comma.
38
     *
39
     * @param  array  $array
40
     * @return string  $ret
41
     */
42 3
    public function getStringFromArraySeparatedByComma($array)
43
    {
44 3
        $ret = '';
45 3
        $i = 0;
46 3
        $len = count($array); // to put "," to all items except the last
47
48 3
        foreach ($array as $key => $value) {
49 3
            $ret .= $value;
50 3
            if ($i != $len - 1) {  // not last
51 1
                $ret .= ', ';
52
            }
53 3
            $i++;
54
        }
55
56 3
        return $ret;
57
    }
58
59
    /***************************************************************************/
60
61
    /**
62
     * 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
63
     * $dayOfTheWeek: 1|2|3|4|5|6|7 (MONDAY-SUNDAY)
64
     * https://stackoverflow.com/questions/2045736/getting-all-dates-for-mondays-and-tuesdays-for-the-next-year.
65
     *
66
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
67
     * @param  string $date
68
     * @param  int $dayOfTheWeek
69
     * @return void
70
     */
71 3
    public function isWeekDay($date, $dayOfTheWeek)
72
    {
73
        // Fix the bug that was avoiding to save Sunday. Date 'w' identify sunday as 0 and not 7.
74 3
        if ($dayOfTheWeek == 7) {
75 1
            $dayOfTheWeek = 0;
76
        }
77
78 3
        return date('w', strtotime($date)) == $dayOfTheWeek;
79
    }
80
81
    /***************************************************************************/
82
83
    /**
84
     * GET number of the specified weekday in this month (1 for the first).
85
     * $dateTimestamp - unix timestramp of the date specified
86
     * $dayOfWeekValue -  1 (for Monday) through 7 (for Sunday)
87
     * Return the number of the week in the month of the weekday specified.
88
     * @param  string $dateTimestamp
89
     * @param  string $dayOfWeekValue
90
     * @return int
91
     */
92 2
    public function weekdayNumberOfMonth($dateTimestamp, $dayOfWeekValue)
93
    {
94 2
        $cut = substr($dateTimestamp, 0, 8);
95 2
        $daylen = 86400;
96 2
        $timestamp = strtotime($dateTimestamp);
97 2
        $first = strtotime($cut.'01');
98 2
        $elapsed = (($timestamp - $first) / $daylen) + 1;
99 2
        $i = 1;
100 2
        $weeks = 0;
101 2
        for ($i == 1; $i <= $elapsed; $i++) {
102 2
            $dayfind = $cut.(strlen($i) < 2 ? '0'.$i : $i);
103 2
            $daytimestamp = strtotime($dayfind);
104 2
            $day = strtolower(date('N', $daytimestamp));
105 2
            if ($day == strtolower($dayOfWeekValue)) {
106 1
                $weeks++;
107
            }
108
        }
109 2
        if ($weeks == 0) {
0 ignored issues
show
introduced by
The condition $weeks == 0 is always true.
Loading history...
110 1
            $weeks++;
111
        }
112
113 2
        return $weeks;
114
    }
115
116
    /***************************************************************************/
117
118
    /**
119
     * GET number of week from the end of the month - https://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month
120
     * Week of the month = Week of the year - Week of the year of first day of month + 1.
121
     * Return the number of the week in the month of the day specified
122
     * $when - unix timestramp of the date specified.
123
     *
124
     * @param  string $when
125
     * @return int
126
     */
127 2
    public function weekOfMonthFromTheEnd($when = null)
128
    {
129 2
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of strftime() does only seem to accept integer, 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

129
        $numberOfDayOfTheMonth = strftime('%e', /** @scrutinizer ignore-type */ $when); // Day of the month 1-31
Loading history...
130 2
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of date() does only seem to accept integer, 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

130
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', /** @scrutinizer ignore-type */ $when))); // the last day of the month of the specified date
Loading history...
131 2
        $dayDifference = $lastDayOfMonth - $numberOfDayOfTheMonth;
132
133
        switch (true) {
134 2
            case $dayDifference < 7:
135
                $weekFromTheEnd = 1;
136
                break;
137
138 2
            case $dayDifference < 14:
139
                $weekFromTheEnd = 2;
140
                break;
141
142 2
            case $dayDifference < 21:
143 1
                $weekFromTheEnd = 3;
144 1
                break;
145
146 1
            case $dayDifference < 28:
147 1
                $weekFromTheEnd = 4;
148 1
                break;
149
150
            default:
151
                $weekFromTheEnd = 5;
152
                break;
153
        }
154
155 2
        return $weekFromTheEnd;
156
    }
157
158
    /***************************************************************************/
159
160
    /**
161
     * GET number of day from the end of the month.
162
     * $when - unix timestramp of the date specified
163
     * Return the number of day of the month from end.
164
     *
165
     * @param  string $when
166
     * @return int
167
     */
168 2
    public function dayOfMonthFromTheEnd($when = null)
169
    {
170 2
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of strftime() does only seem to accept integer, 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

170
        $numberOfDayOfTheMonth = strftime('%e', /** @scrutinizer ignore-type */ $when); // Day of the month 1-31
Loading history...
171 2
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of date() does only seem to accept integer, 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

171
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', /** @scrutinizer ignore-type */ $when))); // the last day of the month of the specified date
Loading history...
172 2
        $dayDifference = $lastDayOfMonth - $numberOfDayOfTheMonth;
173
174 2
        return $dayDifference;
175
    }
176
177
    /***************************************************************************/
178
179
    /**
180
     * GET the ordinal indicator - for the day of the month.
181
     * Return the ordinal indicator (st, nd, rd, th).
182
     * @param  int $number
183
     * @return string
184
     */
185 1
    public function getOrdinalIndicator($number)
186
    {
187
        switch ($number) {
188 1
            case  $number == 1 || $number == 21 || $number == 31:
189 1
                $ret = 'st';
190 1
                break;
191 1
            case  $number == 2 || $number == 22:
192
                $ret = 'nd';
193
                break;
194 1
            case  $number == 3 || $number == 23:
195
                $ret = 'rd';
196
                break;
197
            default:
198 1
                $ret = 'th';
199 1
                break;
200
        }
201
202 1
        return $ret;
203
    }
204
205
    /***************************************************************************/
206
207
    /**
208
     * Decode the event repeat_weekly_on field - used in event.show.
209
     * Return a string like "Monday".
210
     *
211
     * @param  string $repeatWeeklyOn
212
     * @return string
213
     */
214 2
    public function decodeRepeatWeeklyOn($repeatWeeklyOn)
215
    {
216
        $weekdayArray = [
217 2
            '',
218 2
            __('laravel-events-calendar::general.monday'),
219 2
            __('laravel-events-calendar::general.tuesday'),
220 2
            __('laravel-events-calendar::general.wednesday'),
221 2
            __('laravel-events-calendar::general.thursday'),
222 2
            __('laravel-events-calendar::general.friday'),
223 2
            __('laravel-events-calendar::general.saturday'),
224 2
            __('laravel-events-calendar::general.sunday'),
225
        ];
226 2
        $ret = $weekdayArray[$repeatWeeklyOn];
227
228 2
        return $ret;
229
    }
230
231
    /***************************************************************************/
232
233
    /**
234
     * Decode the event on_monthly_kind field - used in event.show.
235
     * Return a string like "the 4th to last Thursday of the month".
236
     *
237
     * @param  string $onMonthlyKindCode
238
     * @return string
239
     */
240 2
    public function decodeOnMonthlyKind($onMonthlyKindCode)
241
    {
242 2
        $onMonthlyKindCodeArray = explode('|', $onMonthlyKindCode);
243
        $weekDays = [
244 2
            '',
245 2
            __('laravel-events-calendar::general.monday'),
246 2
            __('laravel-events-calendar::general.tuesday'),
247 2
            __('laravel-events-calendar::general.wednesday'),
248 2
            __('laravel-events-calendar::general.thursday'),
249 2
            __('laravel-events-calendar::general.friday'),
250 2
            __('laravel-events-calendar::general.saturday'),
251 2
            __('laravel-events-calendar::general.sunday'),
252
        ];
253
254
        //dd($onMonthlyKindCodeArray);
255 2
        switch ($onMonthlyKindCodeArray[0]) {
256 2
            case '0':  // 0|7 eg. the 7th day of the month
257 2
                $dayNumber = $onMonthlyKindCodeArray[1];    
258 2
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
259 2
                $ret = sprintf($format, "day");
0 ignored issues
show
Bug introduced by
It seems like $format can also be of type 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

259
                $ret = sprintf(/** @scrutinizer ignore-type */ $format, "day");
Loading history...
260 2
                break;
261 1
            case '1':  // 1|2|4 eg. the 2nd Thursday of the month
262 1
                $dayNumber = $onMonthlyKindCodeArray[1];
263 1
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
264 1
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
265 1
                $ret = sprintf($format, $weekDay);
0 ignored issues
show
Bug introduced by
It seems like $weekDay can also be of type 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

265
                $ret = sprintf($format, /** @scrutinizer ignore-type */ $weekDay);
Loading history...
266 1
                break;
267 1
            case '2': // 2|20 eg. the 21st to last day of the month
268 1
                $dayNumber = $onMonthlyKindCodeArray[1] + 1;
269 1
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_to_last_x_of_the_month');
270 1
                $ret = sprintf($format, "day");
271 1
                break;
272 1
            case '3': // 3|3|4 eg. the 4th to last Thursday of the month
273 1
                $dayNumber = $onMonthlyKindCodeArray[1] + 1;
274 1
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
275
                /*$ordinalIndicator = self::getOrdinalIndicator($dayNumber);
276
277
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
278
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
279
280
                if ($dayNumber == 1) {
281
                    //$format = 'the last %s of the month';  // eg. the last Friday of the month until 17/06/2020
282
                    $format = __('laravel-events-calendar::event.the_last_x_of_the_month');
283
284
                    $ret = sprintf($format, $weekDay);
285
                } else {
286
                    //$format = 'the %s to last %s of the month'; // eg. the 2nd to last Friday of the month until 17/06/2020
287
                    $format = __('laravel-events-calendar::event.the_x_to_last_x_of_the_month');
288
289
                    $ret = sprintf($format, $dayNumberOrdinal, $weekDay);
290
                }*/
291
                
292 1
                $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_to_last_x_of_the_month');
293 1
                $ret = sprintf($format, $weekDay);
294
295 1
                break;
296
        }
297
298 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...
299
    }
300
301
    /***************************************************************************/
302
303
    /**
304
     * Return the GPS coordinates of the venue
305
     * https://developer.mapquest.com/.
306
     *
307
     * @param  array $address
308
     * @return array $ret
309
     */
310 4
    public static function getVenueGpsCoordinates($address)
311
    {
312 4
        $key = 'Ad5KVnAISxX6aHyj6fAnHcKeh30n4W60';
313 4
        $response = @file_get_contents('http://open.mapquestapi.com/geocoding/v1/address?key='.$key.'&location='.$address);
0 ignored issues
show
Bug introduced by
Are you sure $address of type array can be used in concatenation? ( Ignorable by Annotation )

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

313
        $response = @file_get_contents('http://open.mapquestapi.com/geocoding/v1/address?key='.$key.'&location='./** @scrutinizer ignore-type */ $address);
Loading history...
314 4
        $response = json_decode($response, true);
315
316 4
        $ret = [];
317 4
        $ret['lat'] = $response['results'][0]['locations'][0]['latLng']['lat'];
318 4
        $ret['lng'] = $response['results'][0]['locations'][0]['latLng']['lng'];
319
320 4
        return $ret;
321
    }
322
}
323