Completed
Push — master ( 61ea84...4ec686 )
by Davide
07:23
created

EventController   F

Complexity

Total Complexity 82

Size/Duplication

Total Lines 966
Duplicated Lines 0 %

Test Coverage

Coverage 79.82%

Importance

Changes 26
Bugs 7 Features 3
Metric Value
wmc 82
eloc 436
c 26
b 7
f 3
dl 0
loc 966
ccs 360
cts 451
cp 0.7982
rs 2

24 Methods

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

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

208
                    /** @scrutinizer ignore-call */ 
209
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
Loading history...
209 1
                    $repetition_text = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
210 1
                    break;
211
212
                case '4': //repeatMultipleDays
213
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
214
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
215
                    //$repetition_text = 'The event happens on this dates: '.$event->multiple_dates;
216
                    $repetition_text = 'The event happens on this dates: ';
217
                    $repetition_text .= $dateStart.', ';
218
                    $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

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

438
                if (LaravelEventsCalendar::/** @scrutinizer ignore-call */ isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
Loading history...
439 2
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
440
                }
441
            }
442
        }
443 2
    }
444
445
    /***************************************************************************/
446
447
    /**
448
     * Save all the weekly repetitions inthe event_repetitions table
449
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
450
     *
451
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
452
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
453
     *                      0|28 the 28th day of the month
454
     *                      1|2|2 the 2nd Tuesday of the month
455
     *                      2|17 the 18th to last day of the month
456
     *                      3|1|3 the 2nd to last Wednesday of the month
457
     * @param  string  $startDate (Y-m-d)
458
     * @param  string  $repeatUntilDate (Y-m-d)
459
     * @param  string  $timeStart (H:i:s)
460
     * @param  string  $timeEnd (H:i:s)
461
     * @return void
462
     */
463 5
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
464
    {
465 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

465
        $start = $month = Carbon::create(/** @scrutinizer ignore-type */ $startDate);
Loading history...
466 5
        $end = Carbon::create($repeatUntilDate);
467
468 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...
469 5
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
470
471 5
        switch ($monthRepeatDatas[0]) {
472 5
            case '0':  // Same day number - eg. "the 28th day of the month"
473 2
                while ($month < $end) {
474 2
                    $day = $month->format('Y-m-d');
475
476 2
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
477 2
                    $month = $month->addMonth();
478
                }
479 2
                break;
480 3
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
481 1
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
482 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
483
484 1
                while ($month < $end) {
485 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
486 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
487
488 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

488
                    $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...
489
490 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

490
                    $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

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

734
        /** @scrutinizer ignore-call */ 
735
        $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($dayNumber);
Loading history...
735
736 1
        array_push($monthlySelectOptions, [
737 1
                'value' => '0|'.$dayNumber,
738 1
                'text' => 'the '.$dayNumber.$ordinalIndicator.' day of the month',
739
            ]);
740
741
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
742 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
743 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

743
            /** @scrutinizer ignore-call */ 
744
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
744 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfTheMonth); //st, nd, rd, th
745
746 1
            array_push($monthlySelectOptions, [
747 1
                'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
748 1
                'text' => 'the '.$weekOfTheMonth.$ordinalIndicator.' '.$dayOfWeekString.' of the month',
749
            ]);
750
751
        // 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)
752 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

752
            /** @scrutinizer ignore-call */ 
753
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
753
754 1
        if ($dayOfMonthFromTheEnd == 0) {
755
            $dayText = 'last';
756
        } else {
757 1
            $numberOfTheDay = $dayOfMonthFromTheEnd + 1;
758 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($numberOfTheDay);
759 1
            $dayText = $numberOfTheDay.$ordinalIndicator.' to last';
760
        }
761
        
762 1
        array_push($monthlySelectOptions, [
763 1
                'value' => '2|'.$dayOfMonthFromTheEnd,
764 1
                'text' => 'the '.$dayText.' day of the month',
765
            ]);
766
767
        // 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)
768 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

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

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