Passed
Push — master ( e51595...429e88 )
by Davide
32:08
created

EventController::eventBySlug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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', 'extra_info')
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
                    //$repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
206 1
                    $format = __('laravel-events-calendar::event.the_event_happens_every_x_until');
207 1
                    $repetition_text = sprintf($format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
0 ignored issues
show
Bug introduced by
It seems like $format can also be of type array; however, parameter $format of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

207
                    $repetition_text = sprintf(/** @scrutinizer ignore-type */ $format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
Loading history...
208 1
                    break;
209 1
                case '3': //repeatMonthly
210 1
                    $repeatUntil = new DateTime($event->repeat_until);
211 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

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

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

455
                if (LaravelEventsCalendar::/** @scrutinizer ignore-call */ isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
Loading history...
456 2
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
457
                }
458
            }
459
        }
460 2
    }
461
462
    /***************************************************************************/
463
464
    /**
465
     * Save all the weekly repetitions inthe event_repetitions table
466
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
467
     *
468
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
469
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
470
     *                      0|28 the 28th day of the month
471
     *                      1|2|2 the 2nd Tuesday of the month
472
     *                      2|17 the 18th to last day of the month
473
     *                      3|1|3 the 2nd to last Wednesday of the month
474
     * @param  string  $startDate (Y-m-d)
475
     * @param  string  $repeatUntilDate (Y-m-d)
476
     * @param  string  $timeStart (H:i:s)
477
     * @param  string  $timeEnd (H:i:s)
478
     * @return void
479
     */
480 5
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
481
    {
482 5
        $start = $month = Carbon::create($startDate);
0 ignored issues
show
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

482
        $start = $month = Carbon::create(/** @scrutinizer ignore-type */ $startDate);
Loading history...
Unused Code introduced by
The assignment to $start is dead and can be removed.
Loading history...
483 5
        $end = Carbon::create($repeatUntilDate);
484
485 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...
486 5
        $weekdayArray = [Carbon::MONDAY, Carbon::TUESDAY, Carbon::WEDNESDAY, Carbon::THURSDAY, Carbon::FRIDAY, Carbon::SATURDAY, Carbon::SUNDAY];
487
488 5
        switch ($monthRepeatDatas[0]) {
489 5
            case '0':  // Same day number - eg. "the 28th day of the month"
490 2
                while ($month < $end) {
491 2
                    $day = $month->format('Y-m-d');
492
493 2
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
494 2
                    $month = $month->addMonth();
495
                }
496 2
                break;
497 3
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
498 1
                $numberOfTheWeek = $monthRepeatDatas[1]; // eg. 1(first) | 2(second) | 3(third) | 4(fourth) | 5(fifth)
499 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
500
501 1
                while ($month < $end) {
502 1
                    $month_number = Carbon::parse($month)->isoFormat('M');
503 1
                    $year_number = Carbon::parse($month)->isoFormat('YYYY');
504
505 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

505
                    $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...
506
507 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 $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

507
                    $this->saveEventRepetitionOnDB($event->id, $day, /** @scrutinizer ignore-type */ $day, $timeStart, $timeEnd);
Loading history...
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

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

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

759
            /** @scrutinizer ignore-call */ 
760
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
760 1
            $ordinalIndicator = LaravelEventsCalendar::getOrdinalIndicator($weekOfTheMonth); //st, nd, rd, th
761
762 1
            array_push($monthlySelectOptions, [
763 1
                'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
764 1
                'text' => 'the '.$weekOfTheMonth.$ordinalIndicator.' '.$dayOfWeekString.' of the month',
765
            ]);
766
767
        // 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)
768 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

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

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

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