Passed
Push — master ( 693377...95d81f )
by Davide
75:43
created

EventController::calculateMonthlySelectOptions()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 68
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 39
CRAP Score 3.0001

Importance

Changes 16
Bugs 4 Features 7
Metric Value
eloc 40
c 16
b 4
f 7
dl 0
loc 68
ccs 39
cts 40
cp 0.975
rs 9.28
cc 3
nc 4
nop 1
crap 3.0001

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

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

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

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

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

484
        $repeatText = sprintf(/** @scrutinizer ignore-type */ $format, 'day');
Loading history...
485
486 1
        array_push($monthlySelectOptions, [
487 1
            'value' => '0|'.$dayNumber,
488 1
            'text' => $repeatText,
489
        ]);
490
491
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
492 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
493 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

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

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

515
            /** @scrutinizer ignore-call */ 
516
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
516
517 1
            if ($weekOfMonthFromTheEnd == 1) {
518
                $weekValue = 0;
519
            } else {
520 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
521
            }
522
523 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
524 1
        $repeatText = sprintf($format, $dayOfWeekString);
525
526 1
        array_push($monthlySelectOptions, [
527 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
528 1
            'text' => $repeatText,
529
        ]);
530
531
        // GENERATE the HTML to return
532 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
533 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

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