Passed
Push — master ( 5ecd82...7f6e89 )
by Davide
30:09
created

EventController::saveMonthlyRepeatDates()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 57
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 9

Importance

Changes 11
Bugs 1 Features 1
Metric Value
eloc 40
c 11
b 1
f 1
dl 0
loc 57
ccs 41
cts 41
cp 1
rs 7.7244
cc 9
nc 9
nop 6
crap 9

1 Method

Rating   Name   Duplication   Size   Complexity  
A EventController::mailToOrganizer() 0 22 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar\Http\Controllers;
4
5
use Carbon\Carbon;
6
use 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 27
    public function __construct()
35
    {
36 27
        $this->middleware('auth', ['except' => ['show', 'reportMisuse', 'reportMisuseThankyou', 'mailToOrganizer', 'mailToOrganizerSent', 'eventBySlug', 'eventBySlugAndRepetition', 'EventsListByCountry', 'calculateMonthlySelectOptions']]);
37 27
    }
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 22
    public function store(Request $request)
138
    {
139
        // Validate form datas
140 22
        $validator = $this->eventsValidator($request);
141 22
        if ($validator->fails()) {
142
            //dd($validator->failed());
143 1
            return back()->withErrors($validator)->withInput();
144
        }
145
146 21
        $event = new Event();
147 21
        $this->saveOnDb($request, $event);
148
149 21
        return redirect()->route('events.index')
150 21
                        ->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, EventRepetition $firstRpDates)
163
    {
164
        //dd($firstRpDates);
165 4
        $category = EventCategory::find($event->category_id);
166 4
        $teachers = $event->teachers()->get();
167 4
        $organizers = $event->organizers()->get();
168
169 4
        $venue = DB::table('event_venues')
170 4
                ->select('id', 'name', 'city', 'address', 'zip_code', 'country_id', 'region_id', 'description', 'website', 'extra_info')
171 4
                ->where('id', $event->venue_id)
172 4
                ->first();
173
174 4
        $country = Country::find($venue->country_id);
175 4
        $region = Region::listsTranslations('name')->find($venue->region_id);
176
177 4
        $continent = Continent::find($country->continent_id);
178
        
179
        // Repetition text to show
180 4
        switch ($event->repeat_type) {
181 4
                case '1': // noRepeat
182 2
                    $repetition_text = null;
183 2
                    break;
184 2
                case '2': // repeatWeekly
185 1
                    $repeatUntil = new DateTime($event->repeat_until);
186
187
                    // Get the name of the weekly day when the event repeat, if two days, return like "Thursday and Sunday"
188 1
                        $repetitonWeekdayNumbersArray = explode(',', $event->repeat_weekly_on);
189 1
                        $repetitonWeekdayNamesArray = [];
190 1
                        foreach ($repetitonWeekdayNumbersArray as $key => $repetitonWeekdayNumber) {
191 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

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

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

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

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

395
                        EventRepetition::saveWeeklyRepeatDates($event->id, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, /** @scrutinizer ignore-type */ $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

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

395
                        EventRepetition::saveWeeklyRepeatDates($event->id, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, /** @scrutinizer ignore-type */ $timeStart, $timeEnd);
Loading history...
396
397 2
                    break;
398
399 5
                case '3':  //repeatMonthly
400
                    // Same of repeatWeekly
401 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
402 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
403
404
                    // Get the array with month repeat details
405 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
406
                        //dump("pp_1");
407 5
                        Event::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $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...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

407
                        Event::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $startDate, $repeatUntilDate, /** @scrutinizer ignore-type */ $timeStart, $timeEnd);
Loading history...
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

407
                        Event::saveMonthlyRepeatDates($event->id, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, /** @scrutinizer ignore-type */ $timeEnd);
Loading history...
408
409 5
                    break;
410
411
                case '4':  //repeatMultipleDays
412
                    // Same of repeatWeekly
413
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
414
415
                    // Get the array with single day repeat details
416
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
417
418
                        $this->saveMultipleRepeatDates($event->id, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
0 ignored issues
show
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

418
                        $this->saveMultipleRepeatDates(/** @scrutinizer ignore-type */ $event->id, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
Loading history...
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

418
                        $this->saveMultipleRepeatDates($event->id, $singleDaysRepeatDatas, $startDate, $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...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

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

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

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

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

645
            /** @scrutinizer ignore-call */ 
646
            $weekOfMonthFromTheEnd = LaravelEventsCalendar::weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
Loading history...
646
647 1
            if ($weekOfMonthFromTheEnd == 1) {
648
                $weekValue = 0;
649
            } else {
650 1
                $weekValue = $weekOfMonthFromTheEnd - 1;
651
            }
652
653 1
        $format = __('laravel-events-calendar::ordinalDays.the_'.($weekOfMonthFromTheEnd).'_to_last_x_of_the_month');
654 1
        $repeatText = sprintf($format, $dayOfWeekString);
655
656 1
        array_push($monthlySelectOptions, [
657 1
            'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
658 1
            'text' => $repeatText,
659
        ]);
660
661
        // GENERATE the HTML to return
662 1
        $selectTitle = __('laravel-events-calendar::general.select_repeat_monthly_kind');
663 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

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

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