Passed
Push — master ( ae8248...d22304 )
by Davide
86:29 queued 62:08
created

EventController::saveMultipleRepeatDates()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

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

189
                            /** @scrutinizer ignore-call */ 
190
                            $repetitonWeekdayNamesArray[] = LaravelEventsCalendar::decodeRepeatWeeklyOn($repetitonWeekdayNumber);
Loading history...
190
                        }
191
                        // create from an array a string with all the values divided by " and "
192 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
193
194
                    //$repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
195 1
                    $format = __('laravel-events-calendar::event.the_event_happens_every_x_until_x');
196 1
                    $repetition_text = sprintf($format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
0 ignored issues
show
Bug introduced by
It seems like $format can also be of type array and array; however, parameter $format of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

196
                    $repetition_text = sprintf(/** @scrutinizer ignore-type */ $format, $nameOfTheRepetitionWeekDays, $repeatUntil->format('d/m/Y'));
Loading history...
197 1
                    break;
198 1
                case '3': //repeatMonthly
199 1
                    $repeatUntil = new DateTime($event->repeat_until);
200 1
                    $repetitionFrequency = LaravelEventsCalendar::decodeOnMonthlyKind($event->on_monthly_kind);
0 ignored issues
show
Bug introduced by
The method decodeOnMonthlyKind() does not exist on DavideCasiraghi\LaravelE...s\LaravelEventsCalendar. Since you implemented __callStatic, consider adding a @method annotation. ( Ignorable by Annotation )

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

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

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

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

393
                        EventRepetition::saveWeeklyRepeatDates($event->id, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, /** @scrutinizer ignore-type */ $timeStart, $timeEnd);
Loading history...
Bug introduced by
It seems like $request->get('repeat_weekly_on_day') can also be of type null; however, parameter $weekDays of DavideCasiraghi\LaravelE...saveWeeklyRepeatDates() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

393
                        EventRepetition::saveWeeklyRepeatDates($event->id, /** @scrutinizer ignore-type */ $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
Loading history...
Bug introduced by
It seems like $timeEnd can also be of type null; however, parameter $timeEnd of DavideCasiraghi\LaravelE...saveWeeklyRepeatDates() 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

393
                        EventRepetition::saveWeeklyRepeatDates($event->id, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, /** @scrutinizer ignore-type */ $timeEnd);
Loading history...
394
395 2
                    break;
396
397 5
                case '3':  //repeatMonthly
398
                    // Same of repeatWeekly
399 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
400 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
401
402
                    // Get the array with month repeat details
403 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
404
                        //dump("pp_1");
405 5
                        Event::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
It seems like $timeEnd can also be of type null; however, parameter $timeEnd of DavideCasiraghi\LaravelE...aveMonthlyRepeatDates() 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

405
                        Event::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, /** @scrutinizer ignore-type */ $timeEnd);
Loading history...
Bug introduced by
It seems like $timeStart can also be of type null; however, parameter $timeStart of DavideCasiraghi\LaravelE...aveMonthlyRepeatDates() 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

405
                        Event::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $startDate, $repeatUntilDate, /** @scrutinizer ignore-type */ $timeStart, $timeEnd);
Loading history...
406
407 5
                    break;
408
409
                case '4':  //repeatMultipleDays
410
                    // Same of repeatWeekly
411
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
412
413
                    // Get the array with single day repeat details
414
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
415
416
                        $this->saveMultipleRepeatDates($event->id, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
It seems like $timeEnd can also be of type null; however, parameter $timeEnd of DavideCasiraghi\LaravelE...veMultipleRepeatDates() 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

416
                        $this->saveMultipleRepeatDates($event->id, $singleDaysRepeatDatas, $startDate, $timeStart, /** @scrutinizer ignore-type */ $timeEnd);
Loading history...
Bug introduced by
$event->id of type integer is incompatible with the type DavideCasiraghi\LaravelEventsCalendar\Models\Event expected by parameter $event of DavideCasiraghi\LaravelE...veMultipleRepeatDates(). ( Ignorable by Annotation )

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

416
                        $this->saveMultipleRepeatDates(/** @scrutinizer ignore-type */ $event->id, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
Loading history...
Bug introduced by
It seems like $timeStart can also be of type null; however, parameter $timeStart of DavideCasiraghi\LaravelE...veMultipleRepeatDates() 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

416
                        $this->saveMultipleRepeatDates($event->id, $singleDaysRepeatDatas, $startDate, /** @scrutinizer ignore-type */ $timeStart, $timeEnd);
Loading history...
417
418
                    break;
419
            }
420 21
    }
421
422
    /***************************************************************************/
423
424
    /**
425
     * Save all the weekly repetitions inthe event_repetitions table
426
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
427
     *
428
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
429
     * @param  array   $singleDaysRepeatDatas - explode of $request->get('multiple_dates')
430
     * @param  string  $startDate (Y-m-d)
431
     * @param  string  $timeStart (H:i:s)
432
     * @param  string  $timeEnd (H:i:s)
433
     * @return void
434
     */
435
    public function saveMultipleRepeatDates(Event $event, array $singleDaysRepeatDatas, string $startDate, string $timeStart, string $timeEnd)
436
    {
437
        $dateTime = strtotime($startDate);
438
        $day = date('Y-m-d', $dateTime);
439
440
        EventRepetition::saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
441
442
        foreach ($singleDaysRepeatDatas as $key => $singleDayRepeatDatas) {
443
            $day = Carbon::createFromFormat('d/m/Y', $singleDayRepeatDatas);
444
            EventRepetition::saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
445
        }
446
    }
447
448
    /***************************************************************************/
449
450
    /**
451
     * Send the Misuse mail.
452
     *
453
     * @param  \Illuminate\Http\Request  $request
454
     * @return \Illuminate\Http\Response
455
     */
456
    public function reportMisuse(Request $request)
457
    {
458
        $report = [];
459
460
        //$report['senderEmail'] = '[email protected]';
461
        $report['senderEmail'] = $request->user_email;
462
        $report['senderName'] = 'Anonymus User';
463
        $report['subject'] = 'Report misuse form';
464
        //$report['adminEmail'] = env('ADMIN_MAIL');
465
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
466
467
        $report['message_misuse'] = $request->message_misuse;
468
        $report['event_title'] = $request->event_title;
469
        $report['event_id'] = $request->event_id;
470
        $report['event_slug'] = $request->slug;
471
472
        switch ($request->reason) {
473
            case '1':
474
                $report['reason'] = 'Not about Contact Improvisation';
475
                break;
476
            case '2':
477
                $report['reason'] = 'Contains wrong informations';
478
                break;
479
            case '3':
480
                $report['reason'] = 'It is not translated in english';
481
                break;
482
            case '4':
483
                $report['reason'] = 'Other (specify in the message)';
484
                break;
485
        }
486
487
        //Mail::to($request->user())->send(new ReportMisuse($report));
488
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
489
490
        return redirect()->route('events.misuse-thankyou');
491
    }
492
493
    /***************************************************************************/
494
495
    /**
496
     * Send the mail to the Organizer (from the event modal in the event show view).
497
     *
498
     * @param  \Illuminate\Http\Request  $request
499
     * @return \Illuminate\Http\Response
500
     */
501
    public function mailToOrganizer(Request $request)
502
    {
503
        $message = [];
504
        $message['senderEmail'] = $request->user_email;
505
        $message['senderName'] = $request->user_name;
506
        $message['subject'] = 'Request from the Global CI Calendar';
507
        //$message['emailTo'] = $organizersEmails;
508
509
        $message['message'] = $request->message;
510
        $message['event_title'] = $request->event_title;
511
        $message['event_id'] = $request->event_id;
512
        $message['event_slug'] = $request->slug;
513
514
        /*
515
        $eventOrganizers = Event::find($request->event_id)->organizers;
516
        foreach ($eventOrganizers as $eventOrganizer) {
517
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
518
        }*/
519
520
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
521
522
        return redirect()->route('events.organizer-sent');
523
    }
524
525
    /***************************************************************************/
526
527
    /**
528
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
529
     *
530
     * @return \Illuminate\Http\Response
531
     */
532 1
    public function mailToOrganizerSent()
533
    {
534 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
535
    }
536
537
    /***************************************************************************/
538
539
    /**
540
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
541
     *
542
     * @return \Illuminate\Http\Response
543
     */
544 1
    public function reportMisuseThankyou()
545
    {
546 1
        return view('laravel-events-calendar::emails.report-thankyou');
547
    }
548
549
    /***************************************************************************/
550
551
    /**
552
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
553
     *
554
     * @param  \Illuminate\Http\Request  $request
555
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
556
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
557
     */
558 21
    public function setEventRepeatFields(Request $request, Event $event)
559
    {
560
        // Set Repeat Until
561 21
        $event->repeat_type = $request->get('repeat_type');
562 21
        if ($request->get('repeat_until')) {
563 7
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
564 7
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
565
        }
566
567
        // Weekely - Set multiple week days
568 21
        if ($request->get('repeat_weekly_on_day')) {
569 2
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
570
            //dd($repeat_weekly_on_day);
571 2
            $i = 0;
572 2
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
573 2
            $event->repeat_weekly_on = '';
574 2
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
575 2
                $event->repeat_weekly_on .= $weeek_day;
576 2
                if ($i != $len - 1) {  // not last
577 2
                    $event->repeat_weekly_on .= ',';
578
                }
579 2
                $i++;
580
            }
581
        }
582
583
        // Monthly
584
585
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
586
587 21
        return $event;
588
    }
589
590
    /***************************************************************************/
591
592
    /**
593
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
594
     * - Used by the AJAX in the event repeat view -
595
     * - The HTML contain a <select></select> with four <options></options>.
596
     *
597
     * @param  \Illuminate\Http\Request  $request  - Just the day
598
     * @return string
599
     */
600 1
    public function calculateMonthlySelectOptions(Request $request)
601
    {
602 1
        $monthlySelectOptions = [];
603 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
604 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
605 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
606
607
        // Same day number - eg. "the 28th day of the month"
608 1
        $dateArray = explode('/', $request->day);
609 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
610
611 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($dayNumber).'_x_of_the_month');
612 1
        $repeatText = sprintf($format, 'day');
0 ignored issues
show
Bug introduced by
It seems like $format can also be of type array and array; however, parameter $format of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

612
        $repeatText = sprintf(/** @scrutinizer ignore-type */ $format, 'day');
Loading history...
613
614 1
        array_push($monthlySelectOptions, [
615 1
            'value' => '0|'.$dayNumber,
616 1
            'text' => $repeatText,
617
        ]);
618
619
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
620 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
621 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

621
            /** @scrutinizer ignore-call */ 
622
            $weekOfTheMonth = LaravelEventsCalendar::weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
Loading history...
622
623 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfTheMonth).'_x_of_the_month');
624 1
        $repeatText = sprintf($format, $dayOfWeekString);
625
626 1
        array_push($monthlySelectOptions, [
627 1
            'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
628 1
            'text' => $repeatText,
629
        ]);
630
631
        // 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)
632 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

632
            /** @scrutinizer ignore-call */ 
633
            $dayOfMonthFromTheEnd = LaravelEventsCalendar::dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
633
634 1
            $format = __('laravel-events-calendar::ordinalDays.the_'.($dayOfMonthFromTheEnd + 1).'_to_last_x_of_the_month');
635 1
        $repeatText = sprintf($format, 'day');
636
637 1
        array_push($monthlySelectOptions, [
638 1
            'value' => '2|'.$dayOfMonthFromTheEnd,
639 1
            'text' => $repeatText,
640
        ]);
641
642
        // 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)
643 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

643
            /** @scrutinizer ignore-call */ 
644
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
644
645 1
            if ($weekOfMonthFromTheEnd == 1) {
646
                $weekValue = 0;
647
            } else {
648 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
649
            }
650
651 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
652 1
        $repeatText = sprintf($format, $dayOfWeekString);
653
654 1
        array_push($monthlySelectOptions, [
655 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
656 1
            'text' => $repeatText,
657
        ]);
658
659
        // GENERATE the HTML to return
660 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
661 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='".$selectTitle."'>";
0 ignored issues
show
Bug introduced by
Are you sure $selectTitle of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

661
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='"./** @scrutinizer ignore-type */ $selectTitle."'>";
Loading history...
662 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
663 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
664
        }
665 1
        $onMonthlyKindSelect .= '</select>';
666
667 1
        return $onMonthlyKindSelect;
668
    }
669
670
    // **********************************************************************
671
672
    /**
673
     * Save/Update the record on DB.
674
     *
675
     * @param  \Illuminate\Http\Request $request
676
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
677
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
678
     */
679 21
    public function saveOnDb(Request $request, Event $event)
680
    {
681 21
        $countries = Country::getCountries();
0 ignored issues
show
Unused Code introduced by
The assignment to $countries is dead and can be removed.
Loading history...
682 21
        $teachers = Teacher::pluck('name', 'id');
683
684 21
        $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...
685 21
                ->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')
686 21
                ->where('event_venues.id', '=', $request->get('venue_id'))
687 21
                ->first();
688
689 21
        $event->title = $request->get('title');
690 21
        $event->description = clean($request->get('description'));
691
692 21
        if ($request->get('created_by')) {
693 21
            $event->created_by = $request->get('created_by');
694
        }
695
696 21
        if (! $event->slug) {
697 21
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
698
        }
699 21
        $event->category_id = $request->get('category_id');
700 21
        $event->venue_id = $request->get('venue_id');
701 21
        $event->image = $request->get('image');
702 21
        $event->contact_email = $request->get('contact_email');
703 21
        $event->website_event_link = $request->get('website_event_link');
704 21
        $event->facebook_event_link = $request->get('facebook_event_link');
705 21
        $event->status = $request->get('status');
706 21
        $event->on_monthly_kind = $request->get('on_monthly_kind');
707 21
        $event->multiple_dates = $request->get('multiple_dates');
708
709
        // Event teaser image upload
710 21
        if ($request->file('image')) {
711
            $imageFile = $request->file('image');
712
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
713
            $imageSubdir = 'events_teaser';
714
            $imageWidth = '968';
715
            $thumbWidth = '310';
716
717
            $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

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