Passed
Push — master ( 854393...4eb6d4 )
by Davide
31:55
created

EventController   F

Complexity

Total Complexity 82

Size/Duplication

Total Lines 975
Duplicated Lines 0 %

Test Coverage

Coverage 79.16%

Importance

Changes 30
Bugs 9 Features 5
Metric Value
wmc 82
eloc 436
c 30
b 9
f 5
dl 0
loc 975
ccs 357
cts 451
cp 0.7916
rs 2

24 Methods

Rating   Name   Duplication   Size   Complexity  
B saveMonthlyRepeatDates() 0 57 9
B edit() 0 56 10
A index() 0 48 5
A update() 0 12 2
A destroy() 0 10 1
A store() 0 14 2
A saveEventRepetitions() 0 54 5
B show() 0 84 7
A saveWeeklyRepeatDates() 0 11 4
A create() 0 24 1
A __construct() 0 3 1
A reportMisuse() 0 35 5
A setEventRepeatFields() 0 30 5
A getCreatorEmail() 0 10 1
A eventsValidator() 0 38 3
A eventBySlugAndRepetition() 0 11 2
A saveEventRepetitionOnDB() 0 8 1
A mailToOrganizer() 0 22 1
A mailToOrganizerSent() 0 3 1
A eventBySlug() 0 6 1
A saveMultipleRepeatDates() 0 9 2
A calculateMonthlySelectOptions() 0 68 4
A reportMisuseThankyou() 0 3 1
B saveOnDb() 0 88 8

How to fix   Complexity   

Complex Class

Complex classes like EventController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EventController, and based on these observations, apply Extract Interface, too.

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

200
                            /** @scrutinizer ignore-call */ 
201
                            $repetitonWeekdayNamesArray[] = LaravelEventsCalendar::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
Loading history...
201
                        }
202
                        // create from an array a string with all the values divided by " and "
203 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
204
205 1
                    $repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
206 1
                    break;
207 1
                case '3': //repeatMonthly
208 1
                    $repeatUntil = new DateTime($event->repeat_until);
209 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

209
                    /** @scrutinizer ignore-call */ 
210
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
Loading history...
210 1
                    $repetition_text = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
211 1
                    break;
212
213
                case '4': //repeatMultipleDays
214
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
215
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
216
217
                    // Sort the datas
218
                       usort($singleDaysRepeatDatas, function ($a, $b) {
219
                           $a = Carbon::createFromFormat('d/m/Y', $a);
220
                           $b = Carbon::createFromFormat('d/m/Y', $b);
221
222
                           return strtotime($a) - strtotime($b);
223
                       });
224
225
                    $repetition_text = 'The event happens on this dates: ';
226
                    $repetition_text .= $dateStart.', ';
227
                    $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

227
                    $repetition_text .= LaravelEventsCalendar::/** @scrutinizer ignore-call */ getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
Loading history...
228
229
                    break;
230
            }
231
232
        // True if the repetition start and end on the same day
233 4
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
234
235 4
        return view('laravel-events-calendar::events.show', compact('event'))
236 4
                ->with('category', $category)
237 4
                ->with('teachers', $teachers)
238 4
                ->with('organizers', $organizers)
239 4
                ->with('venue', $venue)
240 4
                ->with('country', $country)
241 4
                ->with('region', $region)
242 4
                ->with('continent', $continent)
243 4
                ->with('datesTimes', $firstRpDates)
244 4
                ->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...
245 4
                ->with('sameDateStartEnd', $sameDateStartEnd);
246
    }
247
248
    /***************************************************************************/
249
250
    /**
251
     * Show the form for editing the specified resource.
252
     *
253
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
254
     * @return \Illuminate\Http\Response
255
     */
256 1
    public function edit(Event $event)
257
    {
258
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
259 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...
260 1
            $authorUserId = $this->getLoggedAuthorId();
261
262
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
263 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
264
265 1
            $users = User::orderBy('name')->pluck('name', 'id');
266 1
            $teachers = Teacher::orderBy('name')->pluck('name', 'id');
267 1
            $organizers = Organizer::orderBy('name')->pluck('name', 'id');
268 1
            $venues = DB::table('event_venues')
269 1
                    ->select('id', 'name', 'address', 'city')->orderBy('name')->get();
270
271 1
            $eventFirstRepetition = DB::table('event_repetitions')
272 1
                    ->select('id', 'start_repeat', 'end_repeat')
273 1
                    ->where('event_id', '=', $event->id)
274 1
                    ->first();
275
276 1
            $dateTime = [];
277 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
278 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
279 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
280 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
281 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
282 1
            $dateTime['multipleDates'] = $event->multiple_dates;
283
284
            // GET Multiple teachers
285 1
            $teachersDatas = $event->teachers;
286 1
            $teachersSelected = [];
287 1
            foreach ($teachersDatas as $teacherDatas) {
288
                array_push($teachersSelected, $teacherDatas->id);
289
            }
290 1
            $multiple_teachers = implode(',', $teachersSelected);
291
292
            // GET Multiple Organizers
293 1
            $organizersDatas = $event->organizers;
294 1
            $organizersSelected = [];
295 1
            foreach ($organizersDatas as $organizerDatas) {
296
                array_push($organizersSelected, $organizerDatas->id);
297
            }
298 1
            $multiple_organizers = implode(',', $organizersSelected);
299
300 1
            return view('laravel-events-calendar::events.edit', compact('event'))
301 1
                        ->with('eventCategories', $eventCategories)
302 1
                        ->with('users', $users)
303 1
                        ->with('teachers', $teachers)
304 1
                        ->with('multiple_teachers', $multiple_teachers)
305 1
                        ->with('organizers', $organizers)
306 1
                        ->with('multiple_organizers', $multiple_organizers)
307 1
                        ->with('venues', $venues)
308 1
                        ->with('dateTime', $dateTime)
309 1
                        ->with('authorUserId', $authorUserId);
310
        } else {
311
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
312
        }
313
    }
314
315
    /***************************************************************************/
316
317
    /**
318
     * Update the specified resource in storage.
319
     *
320
     * @param  \Illuminate\Http\Request  $request
321
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
322
     * @return \Illuminate\Http\Response
323
     */
324 2
    public function update(Request $request, Event $event)
325
    {
326
        // Validate form datas
327 2
        $validator = $this->eventsValidator($request);
328 2
        if ($validator->fails()) {
329 1
            return back()->withErrors($validator)->withInput();
330
        }
331
332 1
        $this->saveOnDb($request, $event);
333
334 1
        return redirect()->route('events.index')
335 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
336
    }
337
338
    /***************************************************************************/
339
340
    /**
341
     * Remove the specified resource from storage.
342
     *
343
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
344
     * @return \Illuminate\Http\Response
345
     */
346 1
    public function destroy(Event $event)
347
    {
348 1
        DB::table('event_repetitions')
349 1
                ->where('event_id', $event->id)
350 1
                ->delete();
351
352 1
        $event->delete();
353
354 1
        return redirect()->route('events.index')
355 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
356
    }
357
358
    /***************************************************************************/
359
360
    /**
361
     * To save event repetitions for create and update methods.
362
     *
363
     * @param  \Illuminate\Http\Request  $request
364
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
365
     * @return void
366
     */
367 20
    public function saveEventRepetitions($request, $event)
368
    {
369 20
        Event::deletePreviousRepetitions($event->id);
370
371
        // Saving repetitions - If it's a single event will be stored with just one repetition
372 20
        $timeStart = date('H:i:s', strtotime($request->get('time_start')));
373 20
        $timeEnd = date('H:i:s', strtotime($request->get('time_end')));
374 20
        switch ($request->get('repeat_type')) {
375 20
                case '1':  // noRepeat
376 13
                    $eventRepetition = new EventRepetition();
377 13
                    $eventRepetition->event_id = $event->id;
378
379 13
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
380 13
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
381
382 13
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
383 13
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
384 13
                    $eventRepetition->save();
385
386 13
                    break;
387
388 7
                case '2':   // repeatWeekly
389
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
                        $this->saveWeeklyRepeatDates($event, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
396
397 2
                    break;
398
399 5
                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
407 5
                        $this->saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
408
409 5
                    break;
410
411
                case '4':  //repeatMultipleDays
412
                    // Same of repeatWeekly
413
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
414
415
                    // Get the array with single day repeat details
416
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
417
418
                        $this->saveMultipleRepeatDates($event, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
419
420
                    break;
421
            }
422 20
    }
423
424
    /***************************************************************************/
425
426
    /**
427
     * Save all the weekly repetitions in the event_repetitions table.
428
     * $dateStart and $dateEnd are in the format Y-m-d
429
     * $timeStart and $timeEnd are in the format H:i:s.
430
     * $weekDays - $request->get('repeat_weekly_on_day').
431
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
432
     * @param  string  $weekDays
433
     * @param  string  $startDate
434
     * @param  string  $repeatUntilDate
435
     * @param  string  $timeStart
436
     * @param  string  $timeEnd
437
     * @return void
438
     */
439 2
    public function saveWeeklyRepeatDates($event, $weekDays, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
440
    {
441 2
        $beginPeriod = new DateTime($startDate);
442 2
        $endPeriod = new DateTime($repeatUntilDate);
443 2
        $interval = DateInterval::createFromDateString('1 day');
444 2
        $period = new DatePeriod($beginPeriod, $interval, $endPeriod);
445
446 2
        foreach ($period as $day) {  // Iterate for each day of the period
447 2
            foreach ($weekDays as $weekDayNumber) { // Iterate for every day of the week (1:Monday, 2:Tuesday, 3:Wednesday ...)
0 ignored issues
show
Bug introduced by
The expression $weekDays of type string is not traversable.
Loading history...
448 2
                if (LaravelEventsCalendar::isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
0 ignored issues
show
Bug introduced by
The method isWeekDay() 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

448
                if (LaravelEventsCalendar::/** @scrutinizer ignore-call */ isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
Loading history...
449 2
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
450
                }
451
            }
452
        }
453 2
    }
454
455
    /***************************************************************************/
456
457
    /**
458
     * Save all the weekly repetitions inthe event_repetitions table
459
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
460
     *
461
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
462
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
463
     *                      0|28 the 28th day of the month
464
     *                      1|2|2 the 2nd Tuesday of the month
465
     *                      2|17 the 18th to last day of the month
466
     *                      3|1|3 the 2nd to last Wednesday of the month
467
     * @param  string  $startDate (Y-m-d)
468
     * @param  string  $repeatUntilDate (Y-m-d)
469
     * @param  string  $timeStart (H:i:s)
470
     * @param  string  $timeEnd (H:i:s)
471
     * @return void
472
     */
473 5
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
474
    {
475 5
        $start = $month = Carbon::create($startDate);
0 ignored issues
show
Unused Code introduced by
The assignment to $start is dead and can be removed.
Loading history...
Bug introduced by
$startDate of type string is incompatible with the type integer|null expected by parameter $year of Carbon\Carbon::create(). ( Ignorable by Annotation )

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

475
        $start = $month = Carbon::create(/** @scrutinizer ignore-type */ $startDate);
Loading history...
476 5
        $end = Carbon::create($repeatUntilDate);
477
478 5
        $numberOfTheWeekArray = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
0 ignored issues
show
Unused Code introduced by
The assignment to $numberOfTheWeekArray is dead and can be removed.
Loading history...
479 5
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
480
481 5
        switch ($monthRepeatDatas[0]) {
482 5
            case '0':  // Same day number - eg. "the 28th day of the month"
483 2
                while ($month < $end) {
484 2
                    $day = $month->format('Y-m-d');
485
486 2
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
487 2
                    $month = $month->addMonth();
488
                }
489 2
                break;
490 3
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
491 1
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
492 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
493
494 1
                while ($month < $end) {
495 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
496 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
497
498 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
0 ignored issues
show
Bug introduced by
$month_number of type string is incompatible with the type integer|null expected by parameter $month of Carbon\Carbon::create(). ( Ignorable by Annotation )

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

498
                    $day = Carbon::create($year_number, /** @scrutinizer ignore-type */ $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
Loading history...
499
500 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
It seems like $day can also be of type false; however, parameter $dateStart of DavideCasiraghi\LaravelE...veEventRepetitionOnDB() 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

500
                    $this->saveEventRepetitionOnDB($event->id, /** @scrutinizer ignore-type */ $day, $day, $timeStart, $timeEnd);
Loading history...
Bug introduced by
It seems like $day can also be of type false; however, parameter $dateEnd of DavideCasiraghi\LaravelE...veEventRepetitionOnDB() 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

500
                    $this->saveEventRepetitionOnDB($event->id, $day, /** @scrutinizer ignore-type */ $day, $timeStart, $timeEnd);
Loading history...
501 1
                    $month = $month->addMonth();
502
                }
503 1
                break;
504 2
            case '2':  // Same day of the month (from the end) - the 3rd to last day (0 if last day, 1 if 2nd to last day, 2 if 3rd to last day)
505 1
                $dayFromTheEnd = $monthRepeatDatas[1];
506 1
                while ($month < $end) {
507 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
508 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
509
510 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->lastOfMonth()->subDays($dayFromTheEnd);
511
512 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
513 1
                    $month = $month->addMonth();
514
                }
515 1
                break;
516 1
            case '3':  // Same weekday/week of the month (from the end) - the last Friday - (0 if last Friday, 1 if the 2nd to last Friday, 2 if the 3nd to last Friday)
517 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
518 1
                $weeksFromTheEnd = $monthRepeatDatas[1];
519
520 1
                while ($month < $end) {
521 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
522 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
523
524 1
                    $day = Carbon::create($year_number, $month_number, 30, 0, 0, 0)->lastOfMonth($weekday)->subWeeks($weeksFromTheEnd);
525
526 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
527 1
                    $month = $month->addMonth();
528
                }
529 1
                break;
530
        }
531 5
    }
532
533
    /***************************************************************************/
534
535
    /**
536
     * Save all the weekly repetitions inthe event_repetitions table
537
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
538
     *
539
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
540
     * @param  array   $singleDaysRepeatDatas - explode of $request->get('multiple_dates')
541
     * @param  string  $startDate (Y-m-d)
542
     * @param  string  $timeStart (H:i:s)
543
     * @param  string  $timeEnd (H:i:s)
544
     * @return void
545
     */
546
    public function saveMultipleRepeatDates($event, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd)
547
    {
548
        $dateTime = strtotime($startDate);
549
        $day = date('Y-m-d', $dateTime);
550
        $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
551
552
        foreach ($singleDaysRepeatDatas as $key => $singleDayRepeatDatas) {
553
            $day = Carbon::createFromFormat('d/m/Y', $singleDayRepeatDatas);
554
            $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
555
        }
556
    }
557
558
    /***************************************************************************/
559
560
    /**
561
     * Save event repetition in the DB.
562
     * $dateStart and $dateEnd are in the format Y-m-d
563
     * $timeStart and $timeEnd are in the format H:i:s.
564
     * @param  int $eventId
565
     * @param  string $dateStart
566
     * @param  string $dateEnd
567
     * @param  string $timeStart
568
     * @param  string $timeEnd
569
     * @return void
570
     */
571 7
    public function saveEventRepetitionOnDB($eventId, $dateStart, $dateEnd, $timeStart, $timeEnd)
572
    {
573 7
        $eventRepetition = new EventRepetition();
574 7
        $eventRepetition->event_id = $eventId;
575
576 7
        $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
577 7
        $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
578 7
        $eventRepetition->save();
579 7
    }
580
581
    /***************************************************************************/
582
583
    /**
584
     * Send the Misuse mail.
585
     *
586
     * @param  \Illuminate\Http\Request  $request
587
     * @return \Illuminate\Http\Response
588
     */
589
    public function reportMisuse(Request $request)
590
    {
591
        $report = [];
592
593
        //$report['senderEmail'] = '[email protected]';
594
        $report['senderEmail'] = $request->user_email;
595
        $report['senderName'] = 'Anonymus User';
596
        $report['subject'] = 'Report misuse form';
597
        //$report['adminEmail'] = env('ADMIN_MAIL');
598
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
599
600
        $report['message'] = $request->message;
601
        $report['event_title'] = $request->event_title;
602
        $report['event_id'] = $request->event_id;
603
        $report['event_slug'] = $request->slug;
604
605
        switch ($request->reason) {
606
            case '1':
607
                $report['reason'] = 'Not about Contact Improvisation';
608
                break;
609
            case '2':
610
                $report['reason'] = 'Contains wrong informations';
611
                break;
612
            case '3':
613
                $report['reason'] = 'It is not translated in english';
614
                break;
615
            case '4':
616
                $report['reason'] = 'Other (specify in the message)';
617
                break;
618
        }
619
620
        //Mail::to($request->user())->send(new ReportMisuse($report));
621
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
622
623
        return redirect()->route('events.misuse-thankyou');
624
    }
625
626
    /***************************************************************************/
627
628
    /**
629
     * Send the mail to the Organizer (from the event modal in the event show view).
630
     *
631
     * @param  \Illuminate\Http\Request  $request
632
     * @return \Illuminate\Http\Response
633
     */
634
    public function mailToOrganizer(Request $request)
635
    {
636
        $message = [];
637
        $message['senderEmail'] = $request->user_email;
638
        $message['senderName'] = $request->user_name;
639
        $message['subject'] = 'Request from the Global CI Calendar';
640
        //$message['emailTo'] = $organizersEmails;
641
642
        $message['message'] = $request->message;
643
        $message['event_title'] = $request->event_title;
644
        $message['event_id'] = $request->event_id;
645
        $message['event_slug'] = $request->slug;
646
647
        /*
648
        $eventOrganizers = Event::find($request->event_id)->organizers;
649
        foreach ($eventOrganizers as $eventOrganizer) {
650
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
651
        }*/
652
653
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
654
655
        return redirect()->route('events.organizer-sent');
656
    }
657
658
    /***************************************************************************/
659
660
    /**
661
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
662
     *
663
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
664
     * @return \Illuminate\Http\Response
665
     */
666 1
    public function mailToOrganizerSent()
667
    {
668 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
669
    }
670
671
    /***************************************************************************/
672
673
    /**
674
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
675
     * @return \Illuminate\Http\Response
676
     */
677 1
    public function reportMisuseThankyou()
678
    {
679 1
        return view('laravel-events-calendar::emails.report-thankyou');
680
    }
681
682
    /***************************************************************************/
683
684
    /**
685
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
686
     *
687
     * @param  \Illuminate\Http\Request  $request
688
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
689
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
690
     */
691 20
    public function setEventRepeatFields($request, $event)
692
    {
693
        // Set Repeat Until
694 20
        $event->repeat_type = $request->get('repeat_type');
695 20
        if ($request->get('repeat_until')) {
696 7
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
697 7
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
698
        }
699
700
        // Weekely - Set multiple week days
701 20
        if ($request->get('repeat_weekly_on_day')) {
702 2
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
703
            //dd($repeat_weekly_on_day);
704 2
            $i = 0;
705 2
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
706 2
            $event->repeat_weekly_on = '';
707 2
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
708 2
                $event->repeat_weekly_on .= $weeek_day;
709 2
                if ($i != $len - 1) {  // not last
710 2
                    $event->repeat_weekly_on .= ',';
711
                }
712 2
                $i++;
713
            }
714
        }
715
716
        // Monthly
717
718
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
719
720 20
        return $event;
721
    }
722
723
    /***************************************************************************/
724
725
    /**
726
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
727
     * - Used by the AJAX in the event repeat view -
728
     * - The HTML contain a <select></select> with four <options></options>.
729
     *
730
     * @param  \Illuminate\Http\Request  $request  - Just the day
731
     * @return string
732
     */
733 1
    public function calculateMonthlySelectOptions(Request $request)
734
    {
735 1
        $monthlySelectOptions = [];
736 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
737 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
738 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
739
740
        // Same day number - eg. "the 28th day of the month"
741 1
        $dateArray = explode('/', $request->day);
742 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
743 1
        $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($dayNumber);
0 ignored issues
show
Bug introduced by
The method getOrdinalIndicator() 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

743
        /** @scrutinizer ignore-call */ 
744
        $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($dayNumber);
Loading history...
744
745 1
        array_push($monthlySelectOptions, [
746 1
            'value' => '0|'.$dayNumber,
747 1
            'text' => 'the '.$dayNumber.$ordinalIndicator.' day of the month',
748
        ]);
749
750
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
751 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
752 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

752
            /** @scrutinizer ignore-call */ 
753
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
753 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfTheMonth); //st, nd, rd, th
754
755 1
            array_push($monthlySelectOptions, [
756 1
                'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
757 1
                'text' => 'the '.$weekOfTheMonth.$ordinalIndicator.' '.$dayOfWeekString.' of the month',
758
            ]);
759
760
        // 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)
761 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

761
            /** @scrutinizer ignore-call */ 
762
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
762
763 1
        if ($dayOfMonthFromTheEnd == 0) {
764
            $dayText = 'last';
765
        } else {
766 1
            $numberOfTheDay = $dayOfMonthFromTheEnd + 1;
767 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($numberOfTheDay);
768 1
            $dayText = $numberOfTheDay.$ordinalIndicator.' to last';
769
        }
770
771 1
        array_push($monthlySelectOptions, [
772 1
            'value' => '2|'.$dayOfMonthFromTheEnd,
773 1
            'text' => 'the '.$dayText.' day of the month',
774
        ]);
775
776
        // 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)
777 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

777
            /** @scrutinizer ignore-call */ 
778
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
778
779 1
        if ($weekOfMonthFromTheEnd == 1) {
780
            $weekText = 'last ';
781
            $weekValue = 0;
782
        } else {
783 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfMonthFromTheEnd);
784 1
            $weekText = $weekOfMonthFromTheEnd.$ordinalIndicator.' to last ';
785 1
            $weekValue = $weekOfMonthFromTheEnd - 1;
786
        }
787
788 1
        array_push($monthlySelectOptions, [
789 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
790 1
            'text' => 'the '.$weekText.$dayOfWeekString.' of the month',
791
        ]);
792
793
        // GENERATE the HTML to return
794 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='Select repeat monthly kind'>";
795 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
796 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
797
        }
798 1
        $onMonthlyKindSelect .= '</select>';
799
800 1
        return $onMonthlyKindSelect;
801
    }
802
803
    // **********************************************************************
804
805
    /**
806
     * Save/Update the record on DB.
807
     *
808
     * @param  \Illuminate\Http\Request $request
809
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
810
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
811
     */
812 20
    public function saveOnDb($request, $event)
813
    {
814 20
        $countries = Country::getCountries();
0 ignored issues
show
Unused Code introduced by
The assignment to $countries is dead and can be removed.
Loading history...
815 20
        $teachers = Teacher::pluck('name', 'id');
816
817 20
        $venue = DB::table('event_venues')
0 ignored issues
show
Unused Code introduced by
The assignment to $venue is dead and can be removed.
Loading history...
818 20
                ->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')
819 20
                ->where('event_venues.id', '=', $request->get('venue_id'))
820 20
                ->first();
821
822 20
        $event->title = $request->get('title');
823 20
        $event->description = clean($request->get('description'));
824
825
        //$event->created_by = (isset(Auth::id())) ? Auth::id() : null;
826
        //$event->created_by = Auth::id();
827 20
        if ($request->get('created_by')) {
828 20
            $event->created_by = $request->get('created_by');
829
        }
830
831 20
        if (! $event->slug) {
832 20
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
833
        }
834 20
        $event->category_id = $request->get('category_id');
835 20
        $event->venue_id = $request->get('venue_id');
836 20
        $event->image = $request->get('image');
837 20
        $event->contact_email = $request->get('contact_email');
838 20
        $event->website_event_link = $request->get('website_event_link');
839 20
        $event->facebook_event_link = $request->get('facebook_event_link');
840 20
        $event->status = $request->get('status');
841 20
        $event->on_monthly_kind = $request->get('on_monthly_kind');
842 20
        $event->multiple_dates = $request->get('multiple_dates');
843
844
        // Event teaser image upload
845
        //dd($request->file('image'));
846 20
        if ($request->file('image')) {
847
            $imageFile = $request->file('image');
848
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
849
            $imageSubdir = 'events_teaser';
850
            $imageWidth = '968';
851
            $thumbWidth = '310';
852
853
            $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; however, parameter $imageFile of DavideCasiraghi\LaravelE...::uploadImageOnServer() 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

853
            $this->uploadImageOnServer(/** @scrutinizer ignore-type */ $imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
Loading history...
854
            $event->image = $imageName;
855
        } else {
856 20
            $event->image = $request->get('image');
857
        }
858
859
        // Support columns for homepage search (we need this to show events in HP with less use of resources)
860
        /*$event->sc_country_id = $venue->country_id;
861
        $event->sc_region_id = $venue->region_id;
862
        $event->sc_country_name = $countries[$venue->country_id];
863
        $event->sc_city_name = $venue->city;
864
        $event->sc_venue_name = $venue->venue_name;*/
865 20
        $event->sc_teachers_id = json_encode(explode(',', $request->get('multiple_teachers'))); // keep just this SC
866
        /*$event->sc_continent_id = $venue->continent_id;*/
867
868
        // Multiple teachers - populate support column field
869 20
        $event->sc_teachers_names = '';
870 20
        if ($request->get('multiple_teachers')) {
871 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
872
873 2
            $multiple_teachers_names = [];
874 2
            foreach ($multiple_teachers as $key => $teacher_id) {
875 2
                $multiple_teachers_names[] = $teachers[$teacher_id];
876
            }
877
878 2
            $event->sc_teachers_names .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($multiple_teachers_names);
879
        }
880
881
        // Set the Event attributes about repeating (repeat until field and multiple days)
882 20
        $event = $this->setEventRepeatFields($request, $event);
883
884
        // Save event and repetitions
885 20
        $event->save();
886 20
        $this->saveEventRepetitions($request, $event);
887
888
        // Update multi relationships with teachers and organizers tables.
889 20
        if ($request->get('multiple_teachers')) {
890 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
891 2
            $event->teachers()->sync($multiple_teachers);
892
        } else {
893 18
            $event->teachers()->sync([]);
894
        }
895 20
        if ($request->get('multiple_organizers')) {
896
            $multiple_organizers = explode(',', $request->get('multiple_organizers'));
897
            $event->organizers()->sync($multiple_organizers);
898
        } else {
899 20
            $event->organizers()->sync([]);
900
        }
901 20
    }
902
903
    /***********************************************************************/
904
905
    /**
906
     * Get creator email.
907
     *
908
     * @param  int $created_by
909
     * @return \Illuminate\Foundation\Auth\User
910
     */
911
    public function getCreatorEmail($created_by)
912
    {
913
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
914
                ->select('email')
915
                ->where('id', $created_by)
916
                ->first();
917
918
        $ret = $creatorEmail->email;
919
920
        return $ret;
921
    }
922
923
    /***************************************************************************/
924
925
    /**
926
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
927
     *
928
     * @param  string  $slug
929
     * @return \Illuminate\Http\Response
930
     */
931 1
    public function eventBySlug($slug)
932
    {
933 1
        $event = Event::where('slug', $slug)->first();
934 1
        $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
935
936 1
        return $this->show($event, $firstRpDates);
937
    }
938
939
    /***************************************************************************/
940
941
    /**
942
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
943
     * @param  string $slug
944
     * @param  int $repetitionId
945
     * @return \Illuminate\Http\Response
946
     */
947 3
    public function eventBySlugAndRepetition($slug, $repetitionId)
948
    {
949 3
        $event = Event::where('slug', $slug)->first();
950 3
        $firstRpDates = Event::getFirstEventRpDatesByRepetitionId($repetitionId);
951
952
        // If not found get the first repetion of the event in the future.
953 3
        if (! $firstRpDates) {
0 ignored issues
show
introduced by
$firstRpDates is of type DavideCasiraghi\LaravelE...\Models\EventRepetition, thus it always evaluated to true.
Loading history...
954 1
            $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
955
        }
956
957 3
        return $this->show($event, $firstRpDates);
958
    }
959
960
    /***************************************************************************/
961
962
    /**
963
     * Return the Event validator with all the defined constraint.
964
     * @param  \Illuminate\Http\Request  $request
965
     * @return \Illuminate\Http\Response
966
     */
967 21
    public function eventsValidator($request)
968
    {
969
        $rules = [
970 21
            'title' => 'required',
971 21
            'description' => 'required',
972 21
            'category_id' => 'required',
973 21
            'venue_id' => 'required',
974 21
            'startDate' => 'required',
975 21
            'endDate' => 'required',
976 21
            'repeat_until' => Rule::requiredIf($request->repeat_type == 2 || $request->repeat_type == 3),
977 21
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
978 21
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
979 21
            'contact_email' => 'nullable|email',
980 21
            'facebook_event_link' => 'nullable|url',
981 21
            'website_event_link' => 'nullable|url',
982
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
983
        ];
984 21
        if ($request->hasFile('image')) {
985
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
986
        }
987
988
        $messages = [
989 21
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
990
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
991
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
992
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
993
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
994
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
995
        ];
996
997 21
        $validator = Validator::make($request->all(), $rules, $messages);
998
999
        // End date and start date must match if the event is repetitive
1000
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
1001 21
            return $input->repeat_type > 1;
1002 21
        });
1003
1004 21
        return $validator;
1005
    }
1006
}
1007