Passed
Push — master ( 9f17bc...20046b )
by Davide
42:05 queued 06:58
created

getFirstFutureEventRpDatesByEventId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar\Models;
4
5
use Carbon\Carbon;
6
use Carbon\CarbonInterval;
7
use Carbon\CarbonPeriod;
8
use DavideCasiraghi\LaravelEventsCalendar\Facades\LaravelEventsCalendar;
9
use Illuminate\Database\Eloquent\Model;
10
11
class EventRepetition extends Model
12
{
13
    /***************************************************************************/
14
    /**
15
     * The table associated with the model.
16
     *
17
     * @var string
18
     */
19
    protected $table = 'event_repetitions';
20
21
    /***************************************************************************/
22
23
    protected $fillable = [
24
        'event_id', 'start_repeat', 'end_repeat',
25
    ];
26
27
    /*public function user()
28
    {
29
        return $this->belongsTo('DavideCasiraghi\LaravelEventsCalendar\Models\Event', 'event_id', 'id');
30
    }*/
31
32
    /***************************************************************************/
33
34
    /**
35
     * Get for each event the first event repetition in the near future (JUST THE QUERY to use as SUBQUERY).
36
     * Parameters are Start date and End date of the interval
37
     * Return the query string,.
38
     * @param  string|null $searchStartDate
39
     * @param  string|null $searchEndDate
40
     * @return string
41
     */
42 14
    public static function getLastestEventsRepetitionsQuery($searchStartDate, $searchEndDate)
43
    {
44
        $ret = self::
45 14
                     selectRaw('event_id, MIN(id) AS rp_id, start_repeat, end_repeat')
46
                     ->when($searchStartDate, function ($query, $searchStartDate) {
47 14
                         return $query->where('event_repetitions.start_repeat', '>=', $searchStartDate);
48 14
                     })
49
                     ->when($searchEndDate, function ($query, $searchEndDate) {
50 1
                         return $query->where('event_repetitions.end_repeat', '<=', $searchEndDate);
51 14
                     })
52 14
                     ->groupBy('event_id');
53
54 14
        return $ret;
55
    }
56
57
    /***************************************************************************/
58
59
    /**
60
     * Save event repetition in the DB.
61
     * $dateStart and $dateEnd are in the format Y-m-d
62
     * $timeStart and $timeEnd are in the format H:i:s.
63
     * @param  int $eventId
64
     * @param  string $dateStart
65
     * @param  string $dateEnd
66
     * @param  string $timeStart
67
     * @param  string $timeEnd
68
     * @return void
69
     */
70 18
    public static function saveEventRepetitionOnDB(int $eventId, string $dateStart, string $dateEnd, string $timeStart, string $timeEnd)
71
    {
72 18
        $eventRepetition = new self();
73 18
        $eventRepetition->event_id = $eventId;
74
75 18
        $eventRepetition->start_repeat = Carbon::createFromFormat('Y-m-d H:i', $dateStart.' '.$timeStart);
76 18
        $eventRepetition->end_repeat = Carbon::createFromFormat('Y-m-d H:i', $dateEnd.' '.$timeEnd);
77
78 18
        $eventRepetition->save();
79 18
    }
80
81
    /***************************************************************************/
82
83
    /**
84
     * Save all the weekly repetitions in the event_repetitions table.
85
     * $dateStart and $dateEnd are in the format Y-m-d
86
     * $timeStart and $timeEnd are in the format H:i:s.
87
     * $weekDays - $request->get('repeat_weekly_on_day').
88
     * @param  int $eventId
89
     * @param  array|null  $weekDays
90
     * @param  string  $startDate
91
     * @param  string  $repeatUntilDate
92
     * @param  string  $timeStart
93
     * @param  string  $timeEnd
94
     * @return void
95
     */
96 3
    public static function saveWeeklyRepeatDates(int $eventId, array $weekDays, string $startDate, string $repeatUntilDate, string $timeStart, string $timeEnd)
97
    {
98 3
        $beginPeriod = Carbon::createFromFormat('Y-m-d', $startDate);
99 3
        $endPeriod = Carbon::createFromFormat('Y-m-d', $repeatUntilDate);
100
        //$interval = CarbonInterval::days(1);
101 3
        $interval = CarbonInterval::make('1day');
102 3
        $period = CarbonPeriod::create($beginPeriod, $interval, $endPeriod);
103 3
        foreach ($period as $day) {  // Iterate for each day of the period
104 3
            foreach ($weekDays as $weekDayNumber) { // Iterate for every day of the week (1:Monday, 2:Tuesday, 3:Wednesday ...)
105 3
                if (LaravelEventsCalendar::isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
0 ignored issues
show
Bug introduced by
The method format() does not exist on null. ( Ignorable by Annotation )

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

105
                if (LaravelEventsCalendar::isWeekDay($day->/** @scrutinizer ignore-call */ format('Y-m-d'), $weekDayNumber)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method isWeekDay() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

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

105
                if (LaravelEventsCalendar::/** @scrutinizer ignore-call */ isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
Loading history...
106 3
                    self::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
107
                }
108
            }
109
        }
110 3
    }
111
112
    /***************************************************************************/
113
114
    /**
115
     * Save all the weekly repetitions in the event_repetitions table
116
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
117
     *
118
     * @param  int  $eventId
119
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
120
     *                      0|28 the 28th day of the month
121
     *                      1|2|2 the 2nd Tuesday of the month
122
     *                      2|17 the 18th to last day of the month
123
     *                      3|1|3 the 2nd to last Wednesday of the month
124
     * @param  string  $startDate (Y-m-d)
125
     * @param  string  $repeatUntilDate (Y-m-d)
126
     * @param  string  $timeStart (H:i:s)
127
     * @param  string  $timeEnd (H:i:s)
128
     * @return void
129
     */
130 9
    public static function saveMonthlyRepeatDates(int $eventId, array $monthRepeatDatas, string $startDate, string $repeatUntilDate, string $timeStart, string $timeEnd)
131
    {
132 9
        $month = Carbon::createFromFormat('Y-m-d', $startDate);
133 9
        $end = Carbon::createFromFormat('Y-m-d', $repeatUntilDate);
134 9
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
135
136
        //$timeStart = $timeStart.":00";
137
        //$timeEnd = $timeEnd.":00";
138
139 9
        switch ($monthRepeatDatas[0]) {
140 9
            case '0':  // Same day number - eg. "the 28th day of the month"
141 3
                while ($month < $end) {
142 3
                    $day = $month;
143
                    //dump("ee_3");
144
                    //dump($timeStart);
145 3
                    self::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
146 3
                    $month = $month->addMonth();
147
                }
148 3
                break;
149 6
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
150 2
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
151 2
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
152
153 2
                while ($month < $end) {
154 2
                    $month_number = (int) Carbon::parse($month)->isoFormat('M');
155 2
                    $year_number = (int) Carbon::parse($month)->isoFormat('YYYY');
156
157 2
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
158
                    //dump("ee_4");
159 2
                    self::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
160
161 2
                    $month = $month->addMonth();
162
                }
163 2
                break;
164 4
            case '2':  // Same day of the month (from the end) - the 3rd to last day (0 if last day, 1 if 2nd to last day, 2 if 3rd to last day)
165 2
                $dayFromTheEnd = $monthRepeatDatas[1];
166 2
                while ($month < $end) {
167 2
                    $month_number = (int) Carbon::parse($month)->isoFormat('M');
168 2
                    $year_number = (int) Carbon::parse($month)->isoFormat('YYYY');
169
170 2
                    $day = Carbon::create($year_number, $month_number, 1, 0, 0, 0)->lastOfMonth()->subDays($dayFromTheEnd);
171
172 2
                    self::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
173 2
                    $month = $month->addMonth();
174
                }
175 2
                break;
176 2
            case '3':  // Same weekday/week of the month (from the end) - the last Friday - (0 if last Friday, 1 if the 2nd to last Friday, 2 if the 3nd to last Friday)
177 2
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
178 2
                $weeksFromTheEnd = $monthRepeatDatas[1];
179
180 2
                while ($month < $end) {
181 2
                    $month_number = (int) Carbon::parse($month)->isoFormat('M');
182 2
                    $year_number = (int) Carbon::parse($month)->isoFormat('YYYY');
183
184 2
                    $day = Carbon::create($year_number, $month_number, 1, 0, 0, 0)->lastOfMonth($weekday)->subWeeks($weeksFromTheEnd);
185
                    //dump("ee_2");
186 2
                    self::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
187 2
                    $month = $month->addMonth();
188
                }
189 2
                break;
190
        }
191 9
    }
192
193
    /***************************************************************************/
194
195
    /**
196
     * Save multiple single dates in the event_repetitions table
197
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
198
     * $singleDaysRepeatDatas - explode of $request->get('multiple_dates') - eg. ["19/03/2020","20/05/2020","29/05/2020"]
199
     * $startDate (Y-m-d)
200
     * $timeStart (H:i:s)
201
     * $timeEnd (H:i:s).
202
     *
203
     * @param  int  $eventId
204
     * @param  array   $singleDaysRepeatDatas
205
     * @param  string  $startDate
206
     * @param  string  $timeStart
207
     * @param  string  $timeEnd
208
     * @return void
209
     */
210 2
    public static function saveMultipleRepeatDates(int $eventId, array $singleDaysRepeatDatas, string $startDate, string $timeStart, string $timeEnd)
211
    {
212 2
        $day = Carbon::createFromFormat('Y-m-d', $startDate);
213
214 2
        self::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
215
216 2
        foreach ($singleDaysRepeatDatas as $key => $singleDayRepeatDatas) {
217 2
            $day = Carbon::createFromFormat('d/m/Y', $singleDayRepeatDatas);
218
219 2
            self::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
220
        }
221 2
    }
222
223
    /***************************************************************************/
224
225
    /**
226
     * Delete all the previous repetitions from the event_repetitions table.
227
     *
228
     * @param int $eventId
229
     * @return void
230
     */
231 32
    public static function deletePreviousRepetitions($eventId)
232
    {
233 32
        self::where('event_id', $eventId)->delete();
234 32
    }
235
236
    /***************************************************************************/
237
238
    /**
239
     * Return Start and End dates of the first repetition of an event - By Event ID.
240
     *
241
     * @param int $eventId
242
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition
243
     */
244 3
    public static function getFirstEventRpDatesByEventId($eventId)
245
    {
246
        $ret = self::
247 3
                select('start_repeat', 'end_repeat')
248 3
                ->where('event_id', $eventId)
249 3
                ->first();
250
251 3
        return $ret;
252
    }
253
    
254
    /***************************************************************************/
255
256
    /**
257
     * Return Start and End dates of the first repetition of an event - By Event ID.
258
     *
259
     * @param int $eventId
260
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition
261
     */
262 3
    public static function getFirstFutureEventRpDatesByEventId($eventId)
263
    {
264
        $ret = self::
265 3
                select('start_repeat', 'end_repeat')
266 3
                ->where('event_id', $eventId)
267 3
                ->where('start_repeat', '>', Carbon::now()->format('Y-m-d'))
268 3
                ->first();
269
270 3
        return $ret;
271
    }
272
273
    /***************************************************************************/
274
275
    /**
276
     * Return Start and End dates of the first repetition of an event - By Repetition ID.
277
     *
278
     * @param int $repetitionId
279
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition
280
     */
281 4
    public static function getFirstEventRpDatesByRepetitionId($repetitionId)
282
    {
283
        $ret = self::
284 4
                select('start_repeat', 'end_repeat')
285 4
                ->where('id', $repetitionId)
286 4
                ->first();
287
288 4
        return $ret;
289
    }
290
291
    /***************************************************************************/
292
293
    /**
294
     * Return the repetition id of the first occurrence of an event in the future - By Event ID.
295
     *
296
     * @param int $eventId
297
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition
298
     */
299 3
    public static function getFirstEventRpIdByEventId($eventId)
300
    {
301
        $ret = self::
302 3
                select('id')
303 3
                ->where('event_id', $eventId)
304 3
                ->where('start_repeat', '>', Carbon::now()->format('Y-m-d'))
305 3
                ->first()->id;
306
307 3
        return $ret;
308
    }
309
}
310