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

189
                            /** @scrutinizer ignore-call */ 
190
                            $repetitonWeekdayNamesArray[] = LaravelEventsCalendar::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
Loading history...
190
                        }
191
                        // create from an array a string with all the values divided by " and "
192 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
193
194
                    //$repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
195 1
                    $format = __('laravel-events-calendar::event.the_event_happens_every_x_until_x');
196 1
                    $repetition_text = sprintf($format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
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

196
                    $repetition_text = sprintf(/** @scrutinizer ignore-type */ $format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
Loading history...
197 1
                    break;
198 2
                case '3': //repeatMonthly
199 1
                    $repeatUntil = new DateTime($event->repeat_until);
200 1
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
0 ignored issues
show
Bug introduced by
The method decodeOnMonthlyKind() 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

200
                    /** @scrutinizer ignore-call */ 
201
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
Loading history...
201
202
                    //$repetition_text = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
203 1
                    $format = __('laravel-events-calendar::event.the_event_happens_x_until_x');
204 1
                    $repetition_text = sprintf($format, $repetitionFrequency, $repeatUntil->format('d/m/Y'));
205 1
                    break;
206
207 1
                case '4': //repeatMultipleDays
208 1
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
209 1
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
210
211
                    // Sort the datas
212
                       usort($singleDaysRepeatDatas, function ($a, $b) {
213 1
                           $a = Carbon::createFromFormat('d/m/Y', $a);
214 1
                           $b = Carbon::createFromFormat('d/m/Y', $b);
215
216 1
                           return strtotime($a) - strtotime($b);
217 1
                       });
218
219
                    //$repetition_text = 'The event happens on this dates: ';
220 1
                    $repetition_text = __('laravel-events-calendar::event.the_event_happens_on_this_dates');
221
222 1
                    $repetition_text .= $dateStart.', ';
223 1
                    $repetition_text .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
0 ignored issues
show
Bug introduced by
The method getStringFromArraySeparatedByComma() 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

223
                    $repetition_text .= LaravelEventsCalendar::/** @scrutinizer ignore-call */ getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
Loading history...
224
225 1
                    break;
226
            }
227
228
        // True if the repetition start and end on the same day
229 5
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
230
231 5
        return view('laravel-events-calendar::events.show', compact('event'))
232 5
                ->with('category', $category)
233 5
                ->with('teachers', $teachers)
234 5
                ->with('organizers', $organizers)
235 5
                ->with('venue', $venue)
236 5
                ->with('country', $country)
237 5
                ->with('region', $region)
238 5
                ->with('continent', $continent)
239 5
                ->with('datesTimes', $firstRpDates)
240 5
                ->with('repetition_text', $repetition_text)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $repetition_text does not seem to be defined for all execution paths leading up to this point.
Loading history...
241 5
                ->with('sameDateStartEnd', $sameDateStartEnd);
242
    }
243
244
    /***************************************************************************/
245
246
    /**
247
     * Show the form for editing the specified resource.
248
     *
249
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
250
     * @return \Illuminate\Http\Response
251
     */
252 1
    public function edit(Event $event)
253
    {
254
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
255 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...
256 1
            $authorUserId = $this->getLoggedAuthorId();
257
258
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
259 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
260
261 1
            $users = User::orderBy('name')->pluck('name', 'id');
262 1
            $teachers = Teacher::orderBy('name')->pluck('name', 'id');
263 1
            $organizers = Organizer::orderBy('name')->pluck('name', 'id');
264 1
            $venues = DB::table('event_venues')
265 1
                    ->select('id', 'name', 'address', 'city')->orderBy('name')->get();
266
267 1
            $eventFirstRepetition = DB::table('event_repetitions')
268 1
                    ->select('id', 'start_repeat', 'end_repeat')
269 1
                    ->where('event_id', '=', $event->id)
270 1
                    ->first();
271
272 1
            $dateTime = [];
273 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
274 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
275 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
276 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
277 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
278 1
            $dateTime['multipleDates'] = $event->multiple_dates;
279
280
            // GET Multiple teachers
281 1
            $teachersDatas = $event->teachers;
282 1
            $teachersSelected = [];
283 1
            foreach ($teachersDatas as $teacherDatas) {
284
                array_push($teachersSelected, $teacherDatas->id);
285
            }
286 1
            $multiple_teachers = implode(',', $teachersSelected);
287
288
            // GET Multiple Organizers
289 1
            $organizersDatas = $event->organizers;
290 1
            $organizersSelected = [];
291 1
            foreach ($organizersDatas as $organizerDatas) {
292
                array_push($organizersSelected, $organizerDatas->id);
293
            }
294 1
            $multiple_organizers = implode(',', $organizersSelected);
295
296 1
            return view('laravel-events-calendar::events.edit', compact('event'))
297 1
                        ->with('eventCategories', $eventCategories)
298 1
                        ->with('users', $users)
299 1
                        ->with('teachers', $teachers)
300 1
                        ->with('multiple_teachers', $multiple_teachers)
301 1
                        ->with('organizers', $organizers)
302 1
                        ->with('multiple_organizers', $multiple_organizers)
303 1
                        ->with('venues', $venues)
304 1
                        ->with('dateTime', $dateTime)
305 1
                        ->with('authorUserId', $authorUserId);
306
        } else {
307
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
308
        }
309
    }
310
311
    /***************************************************************************/
312
313
    /**
314
     * Update the specified resource in storage.
315
     *
316
     * @param  \Illuminate\Http\Request  $request
317
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
318
     * @return \Illuminate\Http\Response
319
     */
320 2
    public function update(Request $request, Event $event)
321
    {
322
        // Validate form datas
323 2
        $validator = $this->eventsValidator($request);
324 2
        if ($validator->fails()) {
325 1
            return back()->withErrors($validator)->withInput();
326
        }
327
328 1
        $this->saveOnDb($request, $event);
329
330 1
        return redirect()->route('events.index')
331 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
332
    }
333
334
    /***************************************************************************/
335
336
    /**
337
     * Remove the specified resource from storage.
338
     *
339
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
340
     * @return \Illuminate\Http\Response
341
     */
342 1
    public function destroy(Event $event)
343
    {
344 1
        DB::table('event_repetitions')
345 1
                ->where('event_id', $event->id)
346 1
                ->delete();
347
348 1
        $event->delete();
349
350 1
        return redirect()->route('events.index')
351 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
352
    }
353
354
    /***************************************************************************/
355
356
    /**
357
     * To save event repetitions for create and update methods.
358
     *
359
     * @param  \Illuminate\Http\Request  $request
360
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
361
     * @return void
362
     */
363 21
    public function saveEventRepetitions(Request $request, Event $event)
364
    {
365 21
        EventRepetition::deletePreviousRepetitions($event->id);
366
367
        // Saving repetitions - If it's a single event will be stored with just one repetition
368
        //$timeStart = date('H:i:s', strtotime($request->get('time_start')));
369
        //$timeEnd = date('H:i:s', strtotime($request->get('time_end')));
370
        //$timeStart = $request->get('time_start');
371
        //$timeEnd = $request->get('time_end');
372 21
        $timeStart = date('H:i', strtotime($request->get('time_start')));
373 21
        $timeEnd = date('H:i', strtotime($request->get('time_end')));
374
375 21
        switch ($request->get('repeat_type')) {
376 21
                case '1':  // noRepeat
377 13
                    $eventRepetition = new EventRepetition();
378 13
                    $eventRepetition->event_id = $event->id;
379
380 13
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
381 13
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
382
383 13
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
384 13
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
385 13
                    $eventRepetition->save();
386
387 13
                    break;
388
389 8
                case '2':   // repeatWeekly
390
                    // Convert the start date in a format that can be used for strtotime
391 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
392
393
                    // Calculate repeat until day
394 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
395 2
                        EventRepetition::saveWeeklyRepeatDates($event->id, $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

395
                        EventRepetition::saveWeeklyRepeatDates($event->id, /** @scrutinizer ignore-type */ $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
Loading history...
396
397 2
                    break;
398
399 6
                case '3':  //repeatMonthly
400
                    // Same of repeatWeekly
401 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
402 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
403
404
                    // Get the array with month repeat details
405 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
406
                        //dump("pp_1");
407 5
                        EventRepetition::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
408
409 5
                    break;
410
411 1
                case '4':  //repeatMultipleDays
412
                    // Same of repeatWeekly
413 1
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
414
415
                    // Get the array with single day repeat details
416 1
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
417
418 1
                        EventRepetition::saveMultipleRepeatDates($event->id, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
419
420 1
                    break;
421
            }
422 21
    }
423
424
    /***************************************************************************/
425
426
    /**
427
     * Send the Misuse mail.
428
     *
429
     * @param  \Illuminate\Http\Request  $request
430
     * @return \Illuminate\Http\Response
431
     */
432
    public function reportMisuse(Request $request)
433
    {
434
        $report = [];
435
436
        //$report['senderEmail'] = '[email protected]';
437
        $report['senderEmail'] = $request->user_email;
438
        $report['senderName'] = 'Anonymus User';
439
        $report['subject'] = 'Report misuse form';
440
        //$report['adminEmail'] = env('ADMIN_MAIL');
441
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
442
443
        $report['message_misuse'] = $request->message_misuse;
444
        $report['event_title'] = $request->event_title;
445
        $report['event_id'] = $request->event_id;
446
        $report['event_slug'] = $request->slug;
447
448
        switch ($request->reason) {
449
            case '1':
450
                $report['reason'] = 'Not about Contact Improvisation';
451
                break;
452
            case '2':
453
                $report['reason'] = 'Contains wrong informations';
454
                break;
455
            case '3':
456
                $report['reason'] = 'It is not translated in english';
457
                break;
458
            case '4':
459
                $report['reason'] = 'Other (specify in the message)';
460
                break;
461
        }
462
463
        //Mail::to($request->user())->send(new ReportMisuse($report));
464
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
465
466
        return redirect()->route('events.misuse-thankyou');
467
    }
468
469
    /***************************************************************************/
470
471
    /**
472
     * Send the mail to the Organizer (from the event modal in the event show view).
473
     *
474
     * @param  \Illuminate\Http\Request  $request
475
     * @return \Illuminate\Http\Response
476
     */
477
    public function mailToOrganizer(Request $request)
478
    {
479
        $message = [];
480
        $message['senderEmail'] = $request->user_email;
481
        $message['senderName'] = $request->user_name;
482
        $message['subject'] = 'Request from the Global CI Calendar';
483
        //$message['emailTo'] = $organizersEmails;
484
485
        $message['message'] = $request->message;
486
        $message['event_title'] = $request->event_title;
487
        $message['event_id'] = $request->event_id;
488
        $message['event_slug'] = $request->slug;
489
490
        /*
491
        $eventOrganizers = Event::find($request->event_id)->organizers;
492
        foreach ($eventOrganizers as $eventOrganizer) {
493
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
494
        }*/
495
496
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
497
498
        return redirect()->route('events.organizer-sent');
499
    }
500
501
    /***************************************************************************/
502
503
    /**
504
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
505
     *
506
     * @return \Illuminate\Http\Response
507
     */
508 1
    public function mailToOrganizerSent()
509
    {
510 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
511
    }
512
513
    /***************************************************************************/
514
515
    /**
516
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
517
     *
518
     * @return \Illuminate\Http\Response
519
     */
520 1
    public function reportMisuseThankyou()
521
    {
522 1
        return view('laravel-events-calendar::emails.report-thankyou');
523
    }
524
525
    /***************************************************************************/
526
527
    /**
528
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
529
     *
530
     * @param  \Illuminate\Http\Request  $request
531
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
532
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
533
     */
534 21
    public function setEventRepeatFields(Request $request, Event $event)
535
    {
536
        // Set Repeat Until
537 21
        $event->repeat_type = $request->get('repeat_type');
538 21
        if ($request->get('repeat_until')) {
539 7
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
540 7
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
541
        }
542
543
        // Weekely - Set multiple week days
544 21
        if ($request->get('repeat_weekly_on_day')) {
545 2
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
546
            //dd($repeat_weekly_on_day);
547 2
            $i = 0;
548 2
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
549 2
            $event->repeat_weekly_on = '';
550 2
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
551 2
                $event->repeat_weekly_on .= $weeek_day;
552 2
                if ($i != $len - 1) {  // not last
553 2
                    $event->repeat_weekly_on .= ',';
554
                }
555 2
                $i++;
556
            }
557
        }
558
559
        // Monthly
560
561
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
562
563 21
        return $event;
564
    }
565
566
    /***************************************************************************/
567
568
    /**
569
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
570
     * - Used by the AJAX in the event repeat view -
571
     * - The HTML contain a <select></select> with four <options></options>.
572
     *
573
     * @param  \Illuminate\Http\Request  $request  - Just the day
574
     * @return string
575
     */
576 1
    public function calculateMonthlySelectOptions(Request $request)
577
    {
578 1
        $monthlySelectOptions = [];
579 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
580 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
581 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
582
583
        // Same day number - eg. "the 28th day of the month"
584 1
        $dateArray = explode('/', $request->day);
585 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
586
587 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
588 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

588
        $repeatText = sprintf(/** @scrutinizer ignore-type */ $format, 'day');
Loading history...
589
590 1
        array_push($monthlySelectOptions, [
591 1
            'value' => '0|'.$dayNumber,
592 1
            'text' => $repeatText,
593
        ]);
594
595
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
596 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
597 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

597
            /** @scrutinizer ignore-call */ 
598
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
598
599 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfTheMonth).'_x_of_the_month');
600 1
        $repeatText = sprintf($format, $dayOfWeekString);
601
602 1
        array_push($monthlySelectOptions, [
603 1
            'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
604 1
            'text' => $repeatText,
605
        ]);
606
607
        // 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)
608 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

608
            /** @scrutinizer ignore-call */ 
609
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
609
610 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($dayOfMonthFromTheEnd + 1).'_to_last_x_of_the_month');
611 1
        $repeatText = sprintf($format, 'day');
612
613 1
        array_push($monthlySelectOptions, [
614 1
            'value' => '2|'.$dayOfMonthFromTheEnd,
615 1
            'text' => $repeatText,
616
        ]);
617
618
        // 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)
619 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

619
            /** @scrutinizer ignore-call */ 
620
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
620
621 1
            if ($weekOfMonthFromTheEnd == 1) {
622
                $weekValue = 0;
623
            } else {
624 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
625
            }
626
627 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
628 1
        $repeatText = sprintf($format, $dayOfWeekString);
629
630 1
        array_push($monthlySelectOptions, [
631 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
632 1
            'text' => $repeatText,
633
        ]);
634
635
        // GENERATE the HTML to return
636 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
637 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

637
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='"./** @scrutinizer ignore-type */ $selectTitle."'>";
Loading history...
638 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
639 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
640
        }
641 1
        $onMonthlyKindSelect .= '</select>';
642
643 1
        return $onMonthlyKindSelect;
644
    }
645
646
    // **********************************************************************
647
648
    /**
649
     * Save/Update the record on DB.
650
     *
651
     * @param  \Illuminate\Http\Request $request
652
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
653
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
654
     */
655 21
    public function saveOnDb(Request $request, Event $event)
656
    {
657
        //$countries = Country::getCountries();
658 21
        $teachers = Teacher::pluck('name', 'id');
659
660
        /*$venue = DB::table('event_venues')
661
                ->select('event_venues.id AS venue_id', 'event_venues.name AS venue_name', 'event_venues.country_id AS country_id', 'event_venues.continent_id', 'event_venues.city')
662
                ->where('event_venues.id', '=', $request->get('venue_id'))
663
                ->first();*/
664
665 21
        $event->title = $request->get('title');
666 21
        $event->description = clean($request->get('description'));
667
668 21
        if ($request->get('created_by')) {
669 21
            $event->created_by = $request->get('created_by');
670
        }
671
672 21
        if (! $event->slug) {
673 21
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
674
        }
675 21
        $event->category_id = $request->get('category_id');
676 21
        $event->venue_id = $request->get('venue_id');
677 21
        $event->image = $request->get('image');
678 21
        $event->contact_email = $request->get('contact_email');
679 21
        $event->website_event_link = $request->get('website_event_link');
680 21
        $event->facebook_event_link = $request->get('facebook_event_link');
681 21
        $event->status = $request->get('status');
682 21
        $event->on_monthly_kind = $request->get('on_monthly_kind');
683 21
        $event->multiple_dates = $request->get('multiple_dates');
684
685
        // Event teaser image upload
686 21
        if ($request->file('image')) {
687
            $imageFile = $request->file('image');
688
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
689
            $imageSubdir = 'events_teaser';
690
            $imageWidth = 968;
691
            $thumbWidth = 310;
692
693
            $this->uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
0 ignored issues
show
Bug introduced by
It seems like $imageFile can also be of type Illuminate\Http\UploadedFile[] and array and null; however, parameter $imageFile of DavideCasiraghi\LaravelE...::uploadImageOnServer() does only seem to accept Illuminate\Http\UploadedFile, 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

693
            $this->uploadImageOnServer(/** @scrutinizer ignore-type */ $imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
Loading history...
694
            $event->image = $imageName;
695
        } else {
696 21
            $event->image = $request->get('image');
697
        }
698
699
        // Support columns for homepage search (we need this to show events in HP with less use of resources)
700 21
        $event->sc_teachers_id = json_encode(explode(',', $request->get('multiple_teachers'))); // keep just this SC
701
702
        // Multiple teachers - populate support column field
703 21
        $event->sc_teachers_names = '';
704 21
        if ($request->get('multiple_teachers')) {
705 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
706
707 2
            $multiple_teachers_names = [];
708 2
            foreach ($multiple_teachers as $key => $teacher_id) {
709 2
                $multiple_teachers_names[] = $teachers[$teacher_id];
710
            }
711
712 2
            $event->sc_teachers_names .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($multiple_teachers_names);
713
        }
714
715
        // Set the Event attributes about repeating (repeat until field and multiple days)
716 21
        $event = $this->setEventRepeatFields($request, $event);
717
718
        // Save event and repetitions
719 21
        $event->save();
720 21
        $this->saveEventRepetitions($request, $event);
721
722
        // Update multi relationships with teachers and organizers tables.
723 21
        if ($request->get('multiple_teachers')) {
724 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
725 2
            $event->teachers()->sync($multiple_teachers);
726
        } else {
727 19
            $event->teachers()->sync([]);
728
        }
729 21
        if ($request->get('multiple_organizers')) {
730
            $multiple_organizers = explode(',', $request->get('multiple_organizers'));
731
            $event->organizers()->sync($multiple_organizers);
732
        } else {
733 21
            $event->organizers()->sync([]);
734
        }
735 21
    }
736
737
    /***********************************************************************/
738
739
    /**
740
     * Get creator email.
741
     *
742
     * @param  int $created_by
743
     * @return \Illuminate\Foundation\Auth\User
744
     */
745
    public function getCreatorEmail(int $created_by)
746
    {
747
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
748
                ->select('email')
749
                ->where('id', $created_by)
750
                ->first();
751
752
        $ret = $creatorEmail->email;
753
754
        return $ret;
755
    }
756
757
    /***************************************************************************/
758
759
    /**
760
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
761
     *
762
     * @param  string  $slug
763
     * @return \Illuminate\Http\Response
764
     */
765 1
    public function eventBySlug(string $slug)
766
    {
767 1
        $event = Event::where('slug', $slug)->first();
768 1
        $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
769
770 1
        return $this->show($event, $firstRpDates);
771
    }
772
773
    /***************************************************************************/
774
775
    /**
776
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
777
     * @param  string $slug
778
     * @param  int $repetitionId
779
     * @return \Illuminate\Http\Response
780
     */
781 4
    public function eventBySlugAndRepetition(string $slug, int $repetitionId)
782
    {
783 4
        $event = Event::where('slug', $slug)->first();
784 4
        $firstRpDates = EventRepetition::getFirstEventRpDatesByRepetitionId($repetitionId);
785
786
        // If not found get the first repetion of the event in the future.
787 4
        if (! $firstRpDates) {
0 ignored issues
show
introduced by
$firstRpDates is of type DavideCasiraghi\LaravelE...\Models\EventRepetition, thus it always evaluated to true.
Loading history...
788 1
            $firstRpDates = EventRepetition::getFirstEventRpDatesByEventId($event->id);
789
        }
790
791 4
        return $this->show($event, $firstRpDates);
792
    }
793
794
    /***************************************************************************/
795
796
    /**
797
     * Return the Event validator with all the defined constraint.
798
     * @param  \Illuminate\Http\Request  $request
799
     * @return \Illuminate\Http\Response
800
     */
801 22
    public function eventsValidator(Request $request)
802
    {
803
        $rules = [
804 22
            'title' => 'required',
805 22
            'description' => 'required',
806 22
            'category_id' => 'required',
807 22
            'venue_id' => 'required',
808 22
            'startDate' => 'required',
809 22
            'endDate' => 'required',
810 22
            'repeat_until' => Rule::requiredIf($request->repeat_type == 2 || $request->repeat_type == 3),
811 22
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
812 22
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
813 22
            'contact_email' => 'nullable|email',
814 22
            'facebook_event_link' => 'nullable|url',
815 22
            'website_event_link' => 'nullable|url',
816
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
817
        ];
818 22
        if ($request->hasFile('image')) {
819
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
820
        }
821
822
        $messages = [
823 22
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
824
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
825
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
826
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
827
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
828
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
829
        ];
830
831 22
        $validator = Validator::make($request->all(), $rules, $messages);
832
833
        // End date and start date must match if the event is repetitive
834
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
835 22
            return $input->repeat_type > 1;
836 22
        });
837
838 22
        return $validator;
839
    }
840
}
841