Passed
Push — master ( 83e6c6...5697af )
by Davide
56:57 queued 23:00
created

EventController::index()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 48
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 5.0067

Importance

Changes 0
Metric Value
eloc 32
c 0
b 0
f 0
dl 0
loc 48
ccs 29
cts 31
cp 0.9355
rs 9.0968
cc 5
nc 4
nop 1
crap 5.0067
1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar\Http\Controllers;
4
5
use DavideCasiraghi\LaravelEventsCalendar\Facades\LaravelEventsCalendar;
6
use DavideCasiraghi\LaravelEventsCalendar\Mail\ContactOrganizer;
7
use DavideCasiraghi\LaravelEventsCalendar\Mail\ReportMisuse;
8
use DavideCasiraghi\LaravelEventsCalendar\Models\Continent;
9
use DavideCasiraghi\LaravelEventsCalendar\Models\Country;
10
use DavideCasiraghi\LaravelEventsCalendar\Models\Event;
11
use DavideCasiraghi\LaravelEventsCalendar\Models\EventCategory;
12
use DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition;
13
use DavideCasiraghi\LaravelEventsCalendar\Models\EventVenue;
14
use DavideCasiraghi\LaravelEventsCalendar\Models\Organizer;
15
use DavideCasiraghi\LaravelEventsCalendar\Models\Region;
16
use DavideCasiraghi\LaravelEventsCalendar\Models\Teacher;
17
use Illuminate\Foundation\Auth\User;
18
use Illuminate\Http\Request;
19
use Illuminate\Support\Facades\Auth;
20
use Illuminate\Support\Facades\Cache;
21
use Illuminate\Support\Facades\DB;
22
use Illuminate\Support\Facades\Mail;
23
use Illuminate\Validation\Rule;
24
use Validator;
25
26
class EventController extends Controller
27
{
28
    /***************************************************************************/
29
    /* Restrict the access to this resource just to logged in users except show view */
30 40
    public function __construct()
31
    {
32 40
        $this->middleware('auth', ['except' => ['show', 'reportMisuse', 'reportMisuseThankyou', 'mailToOrganizer', 'mailToOrganizerSent', 'eventBySlug', 'eventBySlugAndRepetition', 'EventsListByCountry', 'calculateMonthlySelectOptions']]);
33 40
    }
34
35
    /***************************************************************************/
36
37
    /**
38
     * Display a listing of the resource.
39
     * @param  \Illuminate\Http\Request  $request
40
     * @return \Illuminate\View\View
41
     */
42 2
    public function index(Request $request)
43
    {
44
        // To show just the events created by the the user - If admin or super admin is set to null show all the events
45 2
        $authorUserId = ($this->getLoggedAuthorId()) ? $this->getLoggedAuthorId() : null; // if is 0 (super admin or admin) it's setted to null to avoid include it in the query
46
47 2
        $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
48 2
        $countries = Country::orderBy('name')->pluck('name', 'id');
49 2
        $venues = EventVenue::pluck('country_id', 'id');
50
51 2
        $searchKeywords = $request->input('keywords');
52 2
        $searchCategory = $request->input('category_id');
53 2
        $searchCountry = $request->input('country_id');
54
55 2
        if ($searchKeywords || $searchCategory || $searchCountry) {
56
            $events = Event::
57
                // Show only the events owned by the user, if the user is an admin or super admin show all the events
58
                when(isset($authorUserId), function ($query, $authorUserId) {
59
                    return $query->where('created_by', $authorUserId);
60 1
                })
61
                ->when($searchKeywords, function ($query, $searchKeywords) {
62 1
                    return $query->where('title', $searchKeywords)->orWhere('title', 'like', '%'.$searchKeywords.'%');
63 1
                })
64
                ->when($searchCategory, function ($query, $searchCategory) {
65 1
                    return $query->where('category_id', '=', $searchCategory);
66 1
                })
67
                ->when($searchCountry, function ($query, $searchCountry) {
68 1
                    return $query->join('event_venues', 'events.venue_id', '=', 'event_venues.id')->where('event_venues.country_id', '=', $searchCountry);
69 1
                })
70 1
                ->select('*', 'events.id as id', 'events.slug as slug', 'events.image as image') // To keep in the join the id of the Events table - https://stackoverflow.com/questions/28062308/laravel-eloquent-getting-id-field-of-joined-tables-in-eloquent
71 1
                ->paginate(20);
72
73
        //dd($events);
74
        } else {
75 1
            $events = Event::latest()
76
                ->when($authorUserId, function ($query, $authorUserId) {
77
                    return $query->where('created_by', $authorUserId);
78 1
                })
79 1
                ->paginate(20);
80
        }
81
82 2
        return view('laravel-events-calendar::events.index', compact('events'))
83 2
            ->with('i', (request()->input('page', 1) - 1) * 20)
84 2
            ->with('eventCategories', $eventCategories)
85 2
            ->with('countries', $countries)
86 2
            ->with('venues', $venues)
87 2
            ->with('searchKeywords', $searchKeywords)
88 2
            ->with('searchCategory', $searchCategory)
89 2
            ->with('searchCountry', $searchCountry);
90
    }
91
92
    /***************************************************************************/
93
94
    /**
95
     * Show the form for creating a new resource.
96
     *
97
     * @return \Illuminate\View\View
98
     */
99 1
    public function create()
100
    {
101 1
        $authorUserId = $this->getLoggedAuthorId();
102
103 1
        $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
104 1
        $users = User::orderBy('name')->pluck('name', 'id');
105 1
        $teachers = Teacher::orderBy('name')->pluck('name', 'id');
106 1
        $organizers = Organizer::orderBy('name')->pluck('name', 'id');
107
        //$venues = EventVenue::pluck('name', 'id');
108 1
        $venues = DB::table('event_venues')
109 1
                ->select('id', 'name', 'city')->orderBy('name')->get();
110
111 1
        $dateTime = [];
112 1
        $dateTime['repeatUntil'] = null;
113 1
        $dateTime['multipleDates'] = null;
114
115 1
        return view('laravel-events-calendar::events.create')
116 1
            ->with('eventCategories', $eventCategories)
117 1
            ->with('users', $users)
118 1
            ->with('teachers', $teachers)
119 1
            ->with('organizers', $organizers)
120 1
            ->with('venues', $venues)
121 1
            ->with('dateTime', $dateTime)
122 1
            ->with('authorUserId', $authorUserId);
123
    }
124
125
    /***************************************************************************/
126
127
    /**
128
     * Store a newly created resource in storage.
129
     *
130
     * @param  \Illuminate\Http\Request  $request
131
     * @return \Illuminate\Http\RedirectResponse
132
     */
133 34
    public function store(Request $request)
134
    {
135
        // Validate form datas
136 34
        $validator = $this->eventsValidator($request);
137 34
        if ($validator->fails()) {
138
            //dd($validator->failed());
139 1
            return back()->withErrors($validator)->withInput();
140
        }
141
142 33
        $event = new Event();
143 33
        $event->preSave($request);
144 33
        $event->save();
145
146 33
        $this->saveEventRepetitions($request, $event->id);
147 33
        $this->updateTeachersMultiRelationships($request->get('multiple_teachers'), $event);
148 33
        $this->updateOrganizersMultiRelationships($request->get('multiple_organizers'), $event);
149
150 33
        $this->cleanActiveEventsCaches();
151
152 33
        return redirect()->route('events.index')
153 33
                        ->with('success', __('laravel-events-calendar::messages.event_added_successfully'));
154
    }
155
156
    /***************************************************************************/
157
158
    /**
159
     * Display the specified resource.
160
     *
161
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
162
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition $firstRpDates
163
     * @return \Illuminate\View\View
164
     */
165 5
    public function show(Event $event, EventRepetition $firstRpDates)
166
    {
167
        //dd($firstRpDates);
168 5
        $category = EventCategory::find($event->category_id);
169 5
        $teachers = $event->teachers()->get();
170 5
        $organizers = $event->organizers()->get();
171
172 5
        $venue = DB::table('event_venues')
173 5
                ->select('id', 'name', 'city', 'address', 'zip_code', 'country_id', 'region_id', 'description', 'website', 'extra_info')
174 5
                ->where('id', $event->venue_id)
175 5
                ->first();
176
177 5
        $country = Country::find($venue->country_id);
178 5
        $region = Region::listsTranslations('name')->find($venue->region_id);
179 5
        $continent = Continent::find($country->continent_id);
180
181 5
        $repetition_text = LaravelEventsCalendar::getRepetitionTextString($event, $firstRpDates);
0 ignored issues
show
Bug introduced by
The method getRepetitionTextString() 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

181
        /** @scrutinizer ignore-call */ 
182
        $repetition_text = LaravelEventsCalendar::getRepetitionTextString($event, $firstRpDates);
Loading history...
182
183
        // True if the repetition start and end on the same day
184 5
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
185
186 5
        return view('laravel-events-calendar::events.show', compact('event'))
187 5
                ->with('category', $category)
188 5
                ->with('teachers', $teachers)
189 5
                ->with('organizers', $organizers)
190 5
                ->with('venue', $venue)
191 5
                ->with('country', $country)
192 5
                ->with('region', $region)
193 5
                ->with('continent', $continent)
194 5
                ->with('datesTimes', $firstRpDates)
195 5
                ->with('repetition_text', $repetition_text)
196 5
                ->with('sameDateStartEnd', $sameDateStartEnd);
197
    }
198
199
    /***************************************************************************/
200
201
    /**
202
     * Show the form for editing the specified resource.
203
     *
204
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
205
     * @return \Illuminate\Http\RedirectResponse | \Illuminate\View\View
206
     */
207 1
    public function edit(Event $event)
208
    {
209
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
210 1
        if (Auth::user()->id == $event->created_by || Auth::user()->group == 1 || Auth::user()->group == 2) {
0 ignored issues
show
Bug introduced by
Accessing group on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
211 1
            $authorUserId = $this->getLoggedAuthorId();
212
213
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
214 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
215
216 1
            $users = User::orderBy('name')->pluck('name', 'id');
217 1
            $teachers = Teacher::orderBy('name')->pluck('name', 'id');
218 1
            $organizers = Organizer::orderBy('name')->pluck('name', 'id');
219 1
            $venues = DB::table('event_venues')
220 1
                    ->select('id', 'name', 'address', 'city')->orderBy('name')->get();
221
222 1
            $eventFirstRepetition = DB::table('event_repetitions')
223 1
                    ->select('id', 'start_repeat', 'end_repeat')
224 1
                    ->where('event_id', '=', $event->id)
225 1
                    ->first();
226
227 1
            $dateTime = [];
228 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
229 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
230 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
231 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
232 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
233 1
            $dateTime['multipleDates'] = $event->multiple_dates;
234
235 1
            $multiple_teachers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->teachers);
0 ignored issues
show
Bug introduced by
The method getCollectionIdsSeparatedByComma() 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

235
            /** @scrutinizer ignore-call */ 
236
            $multiple_teachers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->teachers);
Loading history...
236 1
            $multiple_organizers = LaravelEventsCalendar::getCollectionIdsSeparatedByComma($event->organizers);
237
238 1
            return view('laravel-events-calendar::events.edit', compact('event'))
239 1
                        ->with('eventCategories', $eventCategories)
240 1
                        ->with('users', $users)
241 1
                        ->with('teachers', $teachers)
242 1
                        ->with('multiple_teachers', $multiple_teachers)
243 1
                        ->with('organizers', $organizers)
244 1
                        ->with('multiple_organizers', $multiple_organizers)
245 1
                        ->with('venues', $venues)
246 1
                        ->with('dateTime', $dateTime)
247 1
                        ->with('authorUserId', $authorUserId);
248
        } else {
249
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
250
        }
251
    }
252
253
    /***************************************************************************/
254
255
    /**
256
     * Update the specified resource in storage.
257
     *
258
     * @param  \Illuminate\Http\Request  $request
259
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
260
     * @return \Illuminate\Http\RedirectResponse
261
     */
262 2
    public function update(Request $request, Event $event)
263
    {
264
        // Validate form datas
265 2
        $validator = $this->eventsValidator($request);
266 2
        if ($validator->fails()) {
267 1
            return back()->withErrors($validator)->withInput();
268
        }
269
270 1
        $event->preSave($request);
271 1
        $event->save();
272
273 1
        $this->saveEventRepetitions($request, $event->id);
274 1
        $this->updateTeachersMultiRelationships($request->get('multiple_teachers'), $event);
275 1
        $this->updateOrganizersMultiRelationships($request->get('multiple_organizers'), $event);
276
277 1
        $this->cleanActiveEventsCaches();
278
279 1
        return redirect()->route('events.index')
280 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
281
    }
282
283
    /***************************************************************************/
284
285
    /**
286
     * Remove the specified resource from storage.
287
     *
288
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
289
     * @return \Illuminate\Http\RedirectResponse
290
     */
291 1
    public function destroy(Event $event)
292
    {
293 1
        DB::table('event_repetitions')
294 1
                ->where('event_id', $event->id)
295 1
                ->delete();
296
297 1
        $event->delete();
298
299 1
        return redirect()->route('events.index')
300 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
301
    }
302
303
    /***************************************************************************/
304
305
    /**
306
     * To save event repetitions for create and update methods.
307
     *
308
     * @param  \Illuminate\Http\Request  $request
309
     * @param  int  $eventId
310
     * @return void
311
     */
312 33
    public function saveEventRepetitions(Request $request, int $eventId): void
313
    {
314 33
        EventRepetition::deletePreviousRepetitions($eventId);
315
316
        // Saving repetitions - If it's a single event will be stored with just one repetition
317
        //$timeStart = date('H:i:s', strtotime($request->get('time_start')));
318
        //$timeEnd = date('H:i:s', strtotime($request->get('time_end')));
319
        //$timeStart = $request->get('time_start');
320
        //$timeEnd = $request->get('time_end');
321 33
        $timeStart = date('H:i', strtotime($request->get('time_start')));
322 33
        $timeEnd = date('H:i', strtotime($request->get('time_end')));
323
324 33
        switch ($request->get('repeat_type')) {
325 33
                case '1':  // noRepeat
326 25
                    $eventRepetition = new EventRepetition();
327 25
                    $eventRepetition->event_id = $eventId;
328
329 25
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
330 25
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
331
332 25
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
333 25
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
334 25
                    $eventRepetition->save();
335
336 25
                    break;
337
338 8
                case '2':   // repeatWeekly
339
                    // Convert the start date in a format that can be used for strtotime
340 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
341
342
                    // Calculate repeat until day
343 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
344 2
                        EventRepetition::saveWeeklyRepeatDates($eventId, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
It seems like $request->get('repeat_weekly_on_day') can also be of type null; however, parameter $weekDays of DavideCasiraghi\LaravelE...saveWeeklyRepeatDates() does only seem to accept array, 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

344
                        EventRepetition::saveWeeklyRepeatDates($eventId, /** @scrutinizer ignore-type */ $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
Loading history...
345
346 2
                    break;
347
348 6
                case '3':  //repeatMonthly
349
                    // Same of repeatWeekly
350 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
351 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
352
353
                    // Get the array with month repeat details
354 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
355
                        //dump("pp_1");
356 5
                        EventRepetition::saveMonthlyRepeatDates($eventId, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
357
358 5
                    break;
359
360 1
                case '4':  //repeatMultipleDays
361
                    // Same of repeatWeekly
362 1
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
363
364
                    // Get the array with single day repeat details
365 1
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
366
367 1
                        EventRepetition::saveMultipleRepeatDates($eventId, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
368
369 1
                    break;
370
            }
371 33
    }
372
373
    /***************************************************************************/
374
375
    /**
376
     * Send the Misuse mail.
377
     *
378
     * @param  \Illuminate\Http\Request  $request
379
     * @return \Illuminate\Http\RedirectResponse
380
     */
381
    public function reportMisuse(Request $request)
382
    {
383
        $report = [];
384
385
        //$report['senderEmail'] = '[email protected]';
386
        $report['senderEmail'] = $request->user_email;
387
        $report['senderName'] = 'Anonymus User';
388
        $report['subject'] = 'Report misuse form';
389
        //$report['adminEmail'] = env('ADMIN_MAIL');
390
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
391
392
        $report['message_misuse'] = $request->message_misuse;
393
        $report['event_title'] = $request->event_title;
394
        $report['event_id'] = $request->event_id;
395
        $report['event_slug'] = $request->slug;
396
397
        $report['reason'] = LaravelEventsCalendar::getReportMisuseReasonDescription($request->reason);
0 ignored issues
show
Bug introduced by
The method getReportMisuseReasonDescription() 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

397
        /** @scrutinizer ignore-call */ 
398
        $report['reason'] = LaravelEventsCalendar::getReportMisuseReasonDescription($request->reason);
Loading history...
398
399
        //Mail::to($request->user())->send(new ReportMisuse($report));
400
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
401
402
        return redirect()->route('events.misuse-thankyou');
403
    }
404
405
    /***************************************************************************/
406
407
    /**
408
     * Send the mail to the Organizer (from the event modal in the event show view).
409
     *
410
     * @param  \Illuminate\Http\Request  $request
411
     * @return \Illuminate\Http\RedirectResponse
412
     */
413
    public function mailToOrganizer(Request $request)
414
    {
415
        $message = [];
416
        $message['senderEmail'] = $request->user_email;
417
        $message['senderName'] = $request->user_name;
418
        $message['subject'] = 'Request from the Global CI Calendar';
419
        //$message['emailTo'] = $organizersEmails;
420
421
        $message['message'] = $request->message;
422
        $message['event_title'] = $request->event_title;
423
        $message['event_id'] = $request->event_id;
424
        $message['event_slug'] = $request->slug;
425
426
        /*
427
        $eventOrganizers = Event::find($request->event_id)->organizers;
428
        foreach ($eventOrganizers as $eventOrganizer) {
429
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
430
        }*/
431
432
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
433
434
        return redirect()->route('events.organizer-sent');
435
    }
436
437
    /***************************************************************************/
438
439
    /**
440
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
441
     *
442
     * @return \Illuminate\View\View
443
     */
444 1
    public function mailToOrganizerSent()
445
    {
446 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
447
    }
448
449
    /***************************************************************************/
450
451
    /**
452
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
453
     *
454
     * @return \Illuminate\View\View
455
     */
456 1
    public function reportMisuseThankyou()
457
    {
458 1
        return view('laravel-events-calendar::emails.report-thankyou');
459
    }
460
461
    /***************************************************************************/
462
463
    /**
464
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
465
     * - Used by the AJAX in the event repeat view -
466
     * - The HTML contain a <select></select> with four <options></options>.
467
     *
468
     * @param  \Illuminate\Http\Request  $request  - Just the day
469
     * @return string
470
     */
471 1
    public function calculateMonthlySelectOptions(Request $request)
472
    {
473 1
        $monthlySelectOptions = [];
474 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
475 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
476 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
477
478
        // Same day number - eg. "the 28th day of the month"
479 1
        $dateArray = explode('/', $request->day);
480 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
481
482 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
483 1
        $repeatText = sprintf($format, 'day');
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

483
        $repeatText = sprintf(/** @scrutinizer ignore-type */ $format, 'day');
Loading history...
484
485 1
        array_push($monthlySelectOptions, [
486 1
            'value' => '0|'.$dayNumber,
487 1
            'text' => $repeatText,
488
        ]);
489
490
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
491 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
492 1
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
0 ignored issues
show
Bug introduced by
The method weekdayNumberOfMonth() 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

492
            /** @scrutinizer ignore-call */ 
493
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
493
494 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfTheMonth).'_x_of_the_month');
495 1
        $repeatText = sprintf($format, $dayOfWeekString);
496
497 1
        array_push($monthlySelectOptions, [
498 1
            'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
499 1
            'text' => $repeatText,
500
        ]);
501
502
        // 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)
503 1
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
0 ignored issues
show
Bug introduced by
The method dayOfMonthFromTheEnd() 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

503
            /** @scrutinizer ignore-call */ 
504
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
504
505 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($dayOfMonthFromTheEnd + 1).'_to_last_x_of_the_month');
506 1
        $repeatText = sprintf($format, 'day');
507
508 1
        array_push($monthlySelectOptions, [
509 1
            'value' => '2|'.$dayOfMonthFromTheEnd,
510 1
            'text' => $repeatText,
511
        ]);
512
513
        // 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)
514 1
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
0 ignored issues
show
Bug introduced by
The method weekOfMonthFromTheEnd() 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

514
            /** @scrutinizer ignore-call */ 
515
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
515
516 1
            if ($weekOfMonthFromTheEnd == 1) {
517
                $weekValue = 0;
518
            } else {
519 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
520
            }
521
522 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
523 1
        $repeatText = sprintf($format, $dayOfWeekString);
524
525 1
        array_push($monthlySelectOptions, [
526 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
527 1
            'text' => $repeatText,
528
        ]);
529
530
        // GENERATE the HTML to return
531 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
532 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='".$selectTitle."'>";
0 ignored issues
show
Bug introduced by
Are you sure $selectTitle of type array|string 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

532
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='"./** @scrutinizer ignore-type */ $selectTitle."'>";
Loading history...
533 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
534 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
535
        }
536 1
        $onMonthlyKindSelect .= '</select>';
537
538 1
        return $onMonthlyKindSelect;
539
    }
540
541
    /***********************************************************************/
542
543
    /**
544
     * Get creator email.
545
     *
546
     * @param  int $created_by
547
     * @return \Illuminate\Foundation\Auth\User
548
     */
549
    public function getCreatorEmail(int $created_by)
550
    {
551
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
552
                ->select('email')
553
                ->where('id', $created_by)
554
                ->first();
555
556
        $ret = $creatorEmail->email;
557
558
        return $ret;
559
    }
560
561
    /***************************************************************************/
562
563
    /**
564
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
565
     *
566
     * @param  string  $slug
567
     * @return \Illuminate\View\View
568
     */
569 1
    public function eventBySlug(string $slug)
570
    {
571 1
        $event = Event::where('slug', $slug)->first();
572 1
        $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
573
574 1
        return $this->show($event, $firstRpDates);
575
    }
576
577
    /***************************************************************************/
578
579
    /**
580
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
581
     * @param  string $slug
582
     * @param  int $repetitionId
583
     * @return \Illuminate\View\View
584
     */
585 4
    public function eventBySlugAndRepetition(string $slug, int $repetitionId)
586
    {
587 4
        $event = Event::where('slug', $slug)->first();
588 4
        $firstRpDates = EventRepetition::getFirstEventRpDatesByRepetitionId($repetitionId);
589
590
        // If not found get the first repetion of the event in the future.
591 4
        if (empty($firstRpDates)) {
592 1
            $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
593
        }
594
595 4
        return $this->show($event, $firstRpDates);
596
    }
597
598
    /***************************************************************************/
599
600
    /**
601
     * Return the Event validator with all the defined constraint.
602
     * @param  \Illuminate\Http\Request  $request
603
     * @return \Illuminate\Contracts\Validation\Validator
604
     */
605 34
    public function eventsValidator(Request $request)
606
    {
607
        $rules = [
608 34
            'title' => 'required',
609 34
            'description' => 'required',
610 34
            'category_id' => 'required',
611 34
            'venue_id' => 'required',
612 34
            'startDate' => 'required',
613 34
            'endDate' => 'required',
614 34
            'repeat_until' => Rule::requiredIf($request->repeat_type == 2 || $request->repeat_type == 3),
615 34
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
616 34
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
617 34
            'contact_email' => 'nullable|email',
618 34
            'facebook_event_link' => 'nullable|url',
619 34
            'website_event_link' => 'nullable|url',
620
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
621
        ];
622 34
        if ($request->hasFile('image')) {
623
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
624
        }
625
626
        $messages = [
627 34
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
628
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
629
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
630
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
631
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
632
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
633
        ];
634
635 34
        $validator = Validator::make($request->all(), $rules, $messages);
636
637
        // End date and start date must match if the event is repetitive
638
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
639 34
            return $input->repeat_type > 1;
640 34
        });
641
642 34
        return $validator;
643
    }
644
645
    /***************************************************************************/
646
647
    /**
648
     * Update multi relationships with teachers table.
649
     *
650
     * @param  string  $multipleTeachers
651
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
652
     * @return void
653
     */
654 33
    public function updateTeachersMultiRelationships($multipleTeachers, $event)
655
    {
656 33
        if ($multipleTeachers) {
657 2
            $multipleTeachersArray = explode(',', $multipleTeachers);
658 2
            $event->teachers()->sync($multipleTeachersArray);
659
        } else {
660 31
            $event->teachers()->sync([]);
661
        }
662 33
    }
663
664
    /***************************************************************************/
665
666
    /**
667
     * Update multi relationships with organizers table.
668
     *
669
     * @param  string  $multipleOrganizers
670
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
671
     * @return void
672
     */
673 33
    public function updateOrganizersMultiRelationships($multipleOrganizers, $event)
674
    {
675 33
        if ($multipleOrganizers) {
676
            $multipleOrganizersArray = explode(',', $multipleOrganizers);
677
            $event->organizers()->sync($multipleOrganizersArray);
678
        } else {
679 33
            $event->organizers()->sync([]);
680
        }
681 33
    }
682
683
    /***************************************************************************/
684
685
    /**
686
     * Clean caches related to active events.
687
     *
688
     * @return void
689
     */
690 33
    public function cleanActiveEventsCaches()
691
    {
692 33
        Cache::forget('active_events');
693 33
        Cache::forget('active_events_map_markers_json');
694 33
        Cache::forget('active_events_map_markers_db_data');
695 33
    }
696
697
    /***************************************************************************/
698
}
699