Passed
Push — master ( ae8248...d22304 )
by Davide
86:29 queued 62:08
created

Event::organizers()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar\Models;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Support\Facades\Cache;
8
9
class Event extends Model
10
{
11
    /***************************************************************************/
12
    /**
13
     * The table associated with the model.
14
     *
15
     * @var string
16
     */
17
    protected $table = 'events';
18
19
    /***************************************************************************/
20
21
    protected $fillable = [
22
        'title',
23
        'description',
24
        'organized_by',
25
        'category_id',
26
        'venue_id',
27
        'image',
28
        'facebook_event_link',
29
        'website_event_link',
30
        'status',
31
        'repeat_type',
32
        'repeat_until',
33
        'repeat_weekly_on',
34
        'repeat_monthly_on',
35
        'on_monthly_kind',
36
        'multiple_dates',
37
    ];
38
39
    /***************************************************************************/
40
41
    /**
42
     * Get the teachers for the event.
43
     */
44 21
    public function teachers()
45
    {
46 21
        return $this->belongsToMany('DavideCasiraghi\LaravelEventsCalendar\Models\Teacher', 'event_has_teachers', 'event_id', 'teacher_id');
47
    }
48
49
    /***************************************************************************/
50
51
    /**
52
     * Get the organizers for the event.
53
     */
54 21
    public function organizers()
55
    {
56 21
        return $this->belongsToMany('DavideCasiraghi\LaravelEventsCalendar\Models\Organizer', 'event_has_organizers', 'event_id', 'organizer_id');
57
    }
58
59
    /***************************************************************************/
60
61
    /**
62
     * Get the organizers for the event.
63
     */
64 1
    public function eventRepetitions()
65
    {
66 1
        return $this->hasMany('DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition', 'event_id');
67
    }
68
69
    /***************************************************************************/
70
71
    /**
72
     * Delete all the previous repetitions from the event_repetitions table.
73
     *
74
     * @param int $eventId
75
     * @return void
76
     */
77 21
    public static function deletePreviousRepetitions($eventId)
78
    {
79 21
        EventRepetition::where('event_id', $eventId)->delete();
80 21
    }
81
82
    /***************************************************************************/
83
84
    /**
85
     * Return Start and End dates of the first repetition of an event - By Event ID.
86
     *
87
     * @param int $eventId
88
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition
89
     */
90 2
    public static function getFirstEventRpDatesByEventId($eventId)
91
    {
92
        $ret = EventRepetition::
93 2
                select('start_repeat', 'end_repeat')
94 2
                ->where('event_id', $eventId)
95 2
                ->first();
96
97 2
        return $ret;
98
    }
99
100
    /***************************************************************************/
101
102
    /**
103
     * Return Start and End dates of the first repetition of an event - By Repetition ID.
104
     *
105
     * @param int $repetitionId
106
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition
107
     */
108 3
    public static function getFirstEventRpDatesByRepetitionId($repetitionId)
109
    {
110
        $ret = EventRepetition::
111 3
                select('start_repeat', 'end_repeat')
112 3
                ->where('id', $repetitionId)
113 3
                ->first();
114
115 3
        return $ret;
116
    }
117
118
    /***************************************************************************/
119
120
    /**
121
     * Return the all the active events.
122
     *
123
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event
124
     */
125 1
    public static function getActiveEvents()
126
    {
127 1
        $cacheExpireMinutes = 15; // Set the duration time of the cache
128
129
        $ret = Cache::remember('active_events', $cacheExpireMinutes, function () {
130 1
            date_default_timezone_set('Europe/Rome');
131 1
            $searchStartDate = date('Y-m-d', time());
132 1
            $lastestEventsRepetitionsQuery = EventRepetition::getLastestEventsRepetitionsQuery($searchStartDate, null);
133
134
            return self::
135 1
                        select('title', 'countries.name AS country_name', 'countries.id AS country_id', 'countries.continent_id AS continent_id', 'event_venues.city AS city')
136 1
                        ->join('event_venues', 'event_venues.id', '=', 'events.venue_id')
137 1
                        ->join('countries', 'countries.id', '=', 'event_venues.country_id')
138
                        ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
139 1
                            $join->on('events.id', '=', 'event_repetitions.event_id');
140 1
                        })
141 1
                        ->get();
142 1
        });
143
144 1
        return $ret;
145
    }
146
147
    /***************************************************************************/
148
149
    /**
150
     * Return the active events based on the search keys provided.
151
     *
152
     * @param array $filters
153
     * @param int $itemPerPage
154
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event
155
     */
156
    //$keywords, $category, $city, $country, $continent, $teacher, $venue, $startDate, $endDate,
157 1
    public static function getEvents(array $filters, $itemPerPage)
158
    {
159 1
        if (! array_key_exists('startDate', $filters) || ! $filters['startDate']) {
160 1
            $filters['startDate'] = Carbon::now()->format('Y-m-d');
161
        }
162
163
        // Sub-Query Joins - https://laravel.com/docs/5.7/queries
164 1
        $lastestEventsRepetitionsQuery = EventRepetition::getLastestEventsRepetitionsQuery($filters['startDate'], $filters['endDate']);
165
166
        // Retrieve the events that correspond to the selected filters
167 1
        if ($filters['keywords'] || $filters['category'] || $filters['city'] || $filters['country'] || $filters['region'] || $filters['continent'] || $filters['teacher'] || $filters['venue'] || $filters['endDate']) {
168
169
        //$start = microtime(true);
170
            //DB::enableQueryLog();
171
            $ret = self::
172 1
                    select('events.title', 'events.category_id', 'events.slug', 'event_venues.name as venue_name', 'event_venues.city as city_name', 'countries.name as country_name', 'events.sc_teachers_names', 'event_repetitions.start_repeat', 'event_repetitions.end_repeat')
173
                    ->when($filters['keywords'], function ($query, $keywords) {
174 1
                        return $query->where('title', 'like', '%'.$keywords.'%');
175 1
                    })
176
                    ->when($filters['category'], function ($query, $category) {
177 1
                        return $query->where('category_id', '=', $category);
178 1
                    })
179
                    ->when($filters['teacher'], function ($query, $teacher) {
180
                        return $query->whereRaw('json_contains(sc_teachers_id, \'["'.$teacher.'"]\')');
181 1
                    })
182
                    ->when($filters['country'], function ($query, $country) {
183 1
                        return $query->where('event_venues.country_id', '=', $country);
184 1
                    })
185
                    ->when($filters['region'], function ($query, $region) {
186
                        return $query->where('event_venues.region_id', '=', $region);
187 1
                    })
188
                    ->when($filters['continent'], function ($query, $continent) {
189 1
                        return $query->where('event_venues.continent_id', '=', $continent);  //sc_continent_id
190 1
                    })
191
                    ->when($filters['city'], function ($query, $city) {
192
                        return $query->where('event_venues.city', 'like', '%'.$city.'%');
193 1
                    })
194
                    ->when($filters['venue'], function ($query, $venue) {
195
                        return $query->where('event_venues.name', 'like', '%'.$venue.'%');
196 1
                    })
197
                    ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
198 1
                        $join->on('events.id', '=', 'event_repetitions.event_id');
199 1
                    })
200
201 1
                    ->leftJoin('event_venues', 'events.venue_id', '=', 'event_venues.id')
202 1
                    ->leftJoin('continents', 'event_venues.continent_id', '=', 'continents.id')
203 1
                    ->leftJoin('countries', 'event_venues.country_id', '=', 'countries.id')
204 1
                    ->leftJoin('regions', 'event_venues.region_id', '=', 'regions.id')
205
                    //->leftJoin('region_translations', 'regions.id', '=', 'region_translations.region_id')
206
207 1
                    ->orderBy('event_repetitions.start_repeat', 'asc')
208 1
                    ->paginate($itemPerPage);
209
        //dd(DB::getQueryLog());
210
211
        //$time = microtime(true) - $start;
212
        //dd($time);
213
        }
214
        // If no filter selected retrieve all the events
215
        else {
216
            $ret = self::
217
                        select('events.title', 'events.category_id', 'events.slug', 'event_venues.name as venue_name', 'event_venues.city as city_name', 'countries.name as country_name', 'events.sc_teachers_names', 'event_repetitions.start_repeat', 'event_repetitions.end_repeat')
218
                        ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
219
                            $join->on('events.id', '=', 'event_repetitions.event_id');
220
                        })
221
                        ->leftJoin('event_venues', 'events.venue_id', '=', 'event_venues.id')
222
                        ->leftJoin('continents', 'event_venues.continent_id', '=', 'continents.id')
223
                        ->leftJoin('countries', 'event_venues.country_id', '=', 'countries.id')
224
                        ->leftJoin('regions', 'event_venues.region_id', '=', 'regions.id')
225
                        ->leftJoin('region_translations', 'regions.id', '=', 'region_translations.region_id')
226
227
                        ->orderBy('event_repetitions.start_repeat', 'asc')
228
                        ->paginate($itemPerPage);
229
230
            // It works, but I don't use it now to develop
231
                /*$cacheExpireMinutes = 15;
232
                $events = Cache::remember('all_events', $cacheExpireTime, function () {
233
                    return DB::table('events')->latest()->paginate(20);
234
                });*/
235
        }
236
237 1
        return $ret;
238
    }
239
240
    /***************************************************************************/
241
242
    /*
243
     * Format the start date to be used in the search query.
244
     * If the start date is null return today's date.
245
     *
246
     * @param string $DatePickerStartDate
247
     * @return string
248
     */
249
    /*public static function prepareStartDate($DatePickerStartDate)
250
    {
251
        if ($DatePickerStartDate) {
252
            list($tid, $tim, $tiy) = explode('/', $DatePickerStartDate);
253
            $ret = "$tiy-$tim-$tid";
254
        } else {
255
            // If no start date selected the search start from today's date
256
            date_default_timezone_set('Europe/Rome');
257
            $ret = date('Y-m-d', time());
258
        }
259
260
        return $ret;
261
    }*/
262
263
    /***************************************************************************/
264
265
    /*
266
     * Format the end date to be used in the search query.
267
     *
268
     * @param string $DatePickerEndDate
269
     * @return string
270
     */
271
    /*public static function prepareEndDate($DatePickerEndDate)
272
    {
273
        if ($DatePickerEndDate) {
274
            list($tid, $tim, $tiy) = explode('/', $DatePickerEndDate);
275
            $ret = "$tiy-$tim-$tid";
276
        } else {
277
            $ret = null;
278
        }
279
280
        return $ret;
281
    }*/
282
283
    /***************************************************************************/
284
285
    /**
286
     * Save all the weekly repetitions in the event_repetitions table
287
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
288
     *
289
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
290
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
291
     *                      0|28 the 28th day of the month
292
     *                      1|2|2 the 2nd Tuesday of the month
293
     *                      2|17 the 18th to last day of the month
294
     *                      3|1|3 the 2nd to last Wednesday of the month
295
     * @param  string  $startDate (Y-m-d)
296
     * @param  string  $repeatUntilDate (Y-m-d)
297
     * @param  string  $timeStart (H:i:s)
298
     * @param  string  $timeEnd (H:i:s)
299
     * @return void
300
     */
301 6
    public static function saveMonthlyRepeatDates(int $eventId, array $monthRepeatDatas, string $startDate, string $repeatUntilDate, string $timeStart, string $timeEnd)
302
    {
303 6
        $start = $month = Carbon::createFromFormat('Y-m-d', $startDate);
0 ignored issues
show
Unused Code introduced by
The assignment to $start is dead and can be removed.
Loading history...
304 6
        $end = Carbon::createFromFormat('Y-m-d', $repeatUntilDate);
305 6
        $numberOfTheWeekArray = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
0 ignored issues
show
Unused Code introduced by
The assignment to $numberOfTheWeekArray is dead and can be removed.
Loading history...
306 6
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
307
308
        //$timeStart = $timeStart.":00";
309
        //$timeEnd = $timeEnd.":00";
310
311 6
        switch ($monthRepeatDatas[0]) {
312 6
            case '0':  // Same day number - eg. "the 28th day of the month"
313 2
                while ($month < $end) {
314 2
                    $day = $month;
315
                    //dump("ee_3");
316
                    //dump($timeStart);
317 2
                    EventRepetition::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
318 2
                    $month = $month->addMonth();
319
                }
320 2
                break;
321 4
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
322 2
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
323 2
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
324
325 2
                while ($month < $end) {
326 2
                    $month_number = Carbon::parse($month)->isoFormat('M');
327 2
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
328
329 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);
0 ignored issues
show
Bug introduced by
$year_number of type string is incompatible with the type integer|null expected by parameter $year of Carbon\Carbon::create(). ( Ignorable by Annotation )

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

329
                    $day = Carbon::create(/** @scrutinizer ignore-type */ $year_number, $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
Loading history...
Bug introduced by
$month_number of type string is incompatible with the type integer|null expected by parameter $month of Carbon\Carbon::create(). ( Ignorable by Annotation )

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

329
                    $day = Carbon::create($year_number, /** @scrutinizer ignore-type */ $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
Loading history...
330
                    //dump("ee_4");
331 2
                    EventRepetition::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
332
333 2
                    $month = $month->addMonth();
334
                }
335 2
                break;
336 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)
337 1
                $dayFromTheEnd = $monthRepeatDatas[1];
338 1
                while ($month < $end) {
339 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
340 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
341
342 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->lastOfMonth()->subDays($dayFromTheEnd);
343
                    //dump("ee_1");
344 1
                    EventRepetition::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
345 1
                    $month = $month->addMonth();
346
                }
347 1
                break;
348 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)
349 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
350 1
                $weeksFromTheEnd = $monthRepeatDatas[1];
351
352 1
                while ($month < $end) {
353 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
354 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
355
356 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->lastOfMonth($weekday)->subWeeks($weeksFromTheEnd);
357
                    //dump("ee_2");
358 1
                    EventRepetition::saveEventRepetitionOnDB($eventId, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
359 1
                    $month = $month->addMonth();
360
                }
361 1
                break;
362
        }
363 6
    }
364
}
365