updateEventRepetitions()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 55
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 5.1158

Importance

Changes 0
Metric Value
cc 5
eloc 29
c 0
b 0
f 0
nc 5
nop 2
dl 0
loc 55
ccs 25
cts 30
cp 0.8333
crap 5.1158
rs 9.1448

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
4
namespace App\Repositories;
5
6
use App\Helpers\DateHelpers;
7
use App\Models\EventRepetition;
8
use Carbon\Carbon;
9
use Carbon\CarbonInterval;
10
use Carbon\CarbonPeriod;
11
use Illuminate\Support\Collection;
12
13
class EventRepetitionRepository implements EventRepetitionRepositoryInterface
14
{
15
16
    /**
17
     * Get all EventRepetitions.
18
     *
19
     * @return Collection
20
     */
21
    public function getAll(): Collection
22
    {
23
        return EventRepetition::all();
24
    }
25
26
    /**
27
     * Get EventRepetition by id
28
     *
29
     * @param int $eventRepetitionId
30
     * @return EventRepetition
31
     */
32 1
    public function getById(int $eventRepetitionId): EventRepetition
33
    {
34 1
        return EventRepetition::findOrFail($eventRepetitionId);
35
    }
36
37
    /**
38
     * Get the event first repetition
39
     *
40
     * @param int $eventId
41
     *
42
     * @return EventRepetition
43
     */
44 1
    public function getFirstByEventId(int $eventId): EventRepetition
45
    {
46 1
        return EventRepetition::select('id', 'start_repeat', 'end_repeat')
47 1
            ->where('event_id', '=', $eventId)
48 1
            ->first();
49
50
        /* DB::table('event_repetitions')
51
             ->select('id', 'start_repeat', 'end_repeat')
52
             ->where('event_id', '=', $event->id)
53
             ->first();*/
54
    }
55
56
    /**
57
     * Store EventRepetition
58
     *
59
     * $dateStart and $dateEnd are in the format Y-m-d
60
     * $timeStart and $timeEnd are in the format H:i:s.
61
     *
62
     * @param  int $eventId
63
     * @param  string $dateStart
64
     * @param  string $dateEnd
65
     * @param  string $timeStart
66
     * @param  string $timeEnd
67
     *
68
     * @return \App\Models\EventRepetition
69
     */
70 7
    public static function store(int $eventId, string $dateStart, string $dateEnd, string $timeStart, string $timeEnd): EventRepetition
71
    {
72 7
        $eventRepetition = new EventRepetition();
73 7
        $eventRepetition->event_id = $eventId;
0 ignored issues
show
Bug introduced by
The property event_id does not exist on App\Models\EventRepetition. Did you mean event?
Loading history...
74
        //dd($timeStart);
75
        //dd($dateStart . ' ' . $timeStart);
76 7
        $eventRepetition->start_repeat = Carbon::createFromFormat('Y-m-d H:i:s', $dateStart . ' ' . $timeStart);
77 7
        $eventRepetition->end_repeat = Carbon::createFromFormat('Y-m-d H:i:s', $dateEnd . ' ' . $timeEnd);
78
79 7
        $eventRepetition->save();
80
81 7
        return $eventRepetition->fresh();
82
    }
83
84
85
    /**
86
     * To save event repetitions for create and update methods.
87
     *
88
     * @param array $data
89
     * @param int $eventId
90
     *
91
     * @return void
92
     */
93 5
    public function updateEventRepetitions(array $data, int $eventId): void
94
    {
95 5
        self::deletePreviousRepetitions($eventId);
96
        //dd($data);
97
        /*$timeStart = date('H:i:s', strtotime($data['time_start']));
98
        $timeEnd = date('H:i:s', strtotime($data['time_end']));*/
99
100 5
        $timeStart = date('H:i:s', strtotime($data['timeStartHours'].':'.$data['timeStartMinutes'].' '.$data['timeStartAmpm']));
101 5
        $timeEnd = date('H:i:s', strtotime($data['timeEndHours'].':'.$data['timeEndMinutes'].' '.$data['timeEndAmpm']));
102
103 5
        switch ($data['repeat_type']) {
104 5
            case '1':  // noRepeat
105 3
                $eventRepetition = new EventRepetition();
106 3
                $eventRepetition->event_id = $eventId;
0 ignored issues
show
Bug introduced by
The property event_id does not exist on App\Models\EventRepetition. Did you mean event?
Loading history...
107
108 3
                $dateStart = implode('-', array_reverse(explode('/', $data['startDate'])));
109 3
                $dateEnd = implode('-', array_reverse(explode('/', $data['endDate'])));
110
111 3
                $eventRepetition->start_repeat = $dateStart . ' ' . $timeStart;
112 3
                $eventRepetition->end_repeat = $dateEnd . ' ' . $timeEnd;
113 3
                $eventRepetition->save();
114
115 3
                break;
116
117 2
            case '2':   // repeatWeekly
118
                // Convert the start date in a format that can be used for strtotime
119 1
                $startDate = implode('-', array_reverse(explode('/', $data['startDate'])));
120
121
                // Calculate repeat until day
122 1
                $repeatUntilDate = implode('-', array_reverse(explode('/', $data['repeat_until'])));
123 1
                self::saveWeeklyRepeatDates($eventId, array_keys($data['repeat_weekly_on']), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
124
125 1
                break;
126
127 1
            case '3':  //repeatMonthly
128
                // Same of repeatWeekly
129 1
                $startDate = implode('-', array_reverse(explode('/', $data['startDate'])));
130 1
                $repeatUntilDate = implode('-', array_reverse(explode('/', $data['repeat_until'])));
131
132
                // Get the array with month repeat details
133 1
                $monthRepeatDatas = explode('|', $data['on_monthly_kind']);
134 1
                self::saveMonthlyRepeatDates($eventId, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
135
136 1
                break;
137
138
            case '4':  //repeatMultipleDays
139
                // Same of repeatWeekly
140
                $startDate = implode('-', array_reverse(explode('/', $data['startDate'])));
141
142
                // Get the array with single day repeat details
143
                $singleDaysRepeatDatas = explode(',', $data['multiple_dates']);
144
145
                self::saveMultipleRepeatDates($eventId, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
146
147
                break;
148
        }
149 5
    }
150
151
    /**
152
     * Delete EventRepetition
153
     *
154
     * @param int $id
155
     * @return void
156
     */
157
    /*public function delete(int $id)
158
    {
159
        EventRepetition::destroy($id);
160
    }*/
161
162
163
    /**
164
     * Delete all the previous repetitions from the event_repetitions table.
165
     *
166
     * @param int $eventId
167
     * @return void
168
     */
169 5
    public static function deletePreviousRepetitions($eventId): void
170
    {
171 5
        EventRepetition::where('event_id', $eventId)->delete();
172
        //self::where('event_id', $eventId)->delete();
173 5
    }
174
175
    /**
176
     * Save all the weekly repetitions in the event_repetitions table.
177
     * $dateStart and $dateEnd are in the format Y-m-d
178
     * $timeStart and $timeEnd are in the format H:i:s.
179
     * $weekDays - $request->get('repeat_weekly_on_day').
180
     * @param  int $eventId
181
     * @param  array  $weekDays
182
     * @param  string  $startDate
183
     * @param  string  $repeatUntilDate
184
     * @param  string  $timeStart
185
     * @param  string  $timeEnd
186
     * @return void
187
     */
188 2
    public static function saveWeeklyRepeatDates(int $eventId, array $weekDays, string $startDate, string $repeatUntilDate, string $timeStart, string $timeEnd): void
189
    {
190 2
        $beginPeriod = Carbon::createFromFormat('Y-m-d', $startDate);
191 2
        $endPeriod = Carbon::createFromFormat('Y-m-d', $repeatUntilDate);
192
        //$interval = CarbonInterval::days(1);
193 2
        $interval = CarbonInterval::make('1day');
194 2
        $period = CarbonPeriod::create($beginPeriod, $interval, $endPeriod);
195 2
        foreach ($period as $day) {  // Iterate for each day of the period
196 2
            foreach ($weekDays as $weekDayNumber) { // Iterate for every day of the week (1:Monday, 2:Tuesday, 3:Wednesday ...)
197 2
                if (DateHelpers::isSpecifiedWeekDay($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

197
                if (DateHelpers::isSpecifiedWeekDay($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...
198 2
                    self::store($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
199
                }
200
            }
201
        }
202 2
    }
203
204
    /**
205
     * Save all the weekly repetitions in the event_repetitions table
206
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
207
     *
208
     * @param  int  $eventId
209
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
210
     *                      0|28 the 28th day of the month
211
     *                      1|2|2 the 2nd Tuesday of the month
212
     *                      2|17 the 18th to last day of the month
213
     *                      3|1|3 the 2nd to last Wednesday of the month
214
     * @param  string  $startDate (Y-m-d)
215
     * @param  string  $repeatUntilDate (Y-m-d)
216
     * @param  string  $timeStart (H:i:s)
217
     * @param  string  $timeEnd (H:i:s)
218
     * @return void
219
     */
220 5
    public static function saveMonthlyRepeatDates(int $eventId, array $monthRepeatDatas, string $startDate, string $repeatUntilDate, string $timeStart, string $timeEnd): void
221
    {
222 5
        $month = Carbon::createFromFormat('Y-m-d', $startDate);
223 5
        $end = Carbon::createFromFormat('Y-m-d', $repeatUntilDate);
224 5
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
225
226 5
        switch ($monthRepeatDatas[0]) {
227 5
            case '0':  // Same day number - eg. "the 28th day of the month"
228 1
                while ($month < $end) {
229 1
                    $day = $month;
230 1
                    self::store($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
231 1
                    $month = $month->addMonth();
232
                }
233 1
                break;
234 4
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
235 2
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
236 2
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
237
238 2
                while ($month < $end) {
239 2
                    $month_number = (int) Carbon::parse($month)->isoFormat('M');
240 2
                    $year_number = (int) Carbon::parse($month)->isoFormat('YYYY');
241 2
                    $day = Carbon::create($year_number, $month_number, 1, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
242
243 2
                    self::store($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
244
245 2
                    $month = $month->addMonth();
246
                }
247 2
                break;
248 2
            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)
249 1
                $dayFromTheEnd = $monthRepeatDatas[1];
250 1
                while ($month < $end) {
251 1
                    $month_number = (int) Carbon::parse($month)->isoFormat('M');
252 1
                    $year_number = (int) Carbon::parse($month)->isoFormat('YYYY');
253
254 1
                    $day = Carbon::create($year_number, $month_number, 1, 0, 0, 0)->lastOfMonth()->subDays($dayFromTheEnd);
255
256 1
                    self::store($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
257 1
                    $month = $month->addMonth();
258
                }
259 1
                break;
260 1
            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)
261 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
262 1
                $weeksFromTheEnd = $monthRepeatDatas[1];
263
264 1
                while ($month < $end) {
265 1
                    $month_number = (int) Carbon::parse($month)->isoFormat('M');
266 1
                    $year_number = (int) Carbon::parse($month)->isoFormat('YYYY');
267
268 1
                    $day = Carbon::create($year_number, $month_number, 1, 0, 0, 0)->lastOfMonth($weekday)->subWeeks($weeksFromTheEnd);
269
                    //dump("ee_2");
270 1
                    self::store($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
271 1
                    $month = $month->addMonth();
272
                }
273 1
                break;
274
        }
275 5
    }
276
277
    /**
278
     * Save multiple single dates in the event_repetitions table
279
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
280
     * $singleDaysRepeatDatas - explode of $request->get('multiple_dates') - eg. ["19/03/2020","20/05/2020","29/05/2020"]
281
     * $startDate (Y-m-d)
282
     * $timeStart (H:i:s)
283
     * $timeEnd (H:i:s).
284
     *
285
     * @param  int  $eventId
286
     * @param  array   $singleDaysRepeatDatas
287
     * @param  string  $startDate
288
     * @param  string  $timeStart
289
     * @param  string  $timeEnd
290
     * @return void
291
     */
292
    public static function saveMultipleRepeatDates(int $eventId, array $singleDaysRepeatDatas, string $startDate, string $timeStart, string $timeEnd): void
293
    {
294
        $day = Carbon::createFromFormat('Y-m-d', $startDate);
295
296
        self::store($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
297
298
        foreach ($singleDaysRepeatDatas as $key => $singleDayRepeatDatas) {
299
            $day = Carbon::createFromFormat('d/m/Y', $singleDayRepeatDatas);
300
301
            self::store($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
302
        }
303
    }
304
}
305