Passed
Push — master ( 8b97cd...97b9a3 )
by Davide
07:49
created

EventController::weekOfMonthFromTheEnd()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.7873

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 29
ccs 13
cts 19
cp 0.6842
rs 9.2888
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 5.7873
1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar\Http\Controllers;
4
5
use DateTime;
6
use Validator;
7
use DatePeriod;
8
use DateInterval;
9
use Carbon\Carbon;
10
use Illuminate\Support\Str;
11
use Illuminate\Http\Request;
12
use Illuminate\Validation\Rule;
13
use Illuminate\Support\Facades\DB;
14
use Illuminate\Foundation\Auth\User;
15
use Illuminate\Support\Facades\Auth;
16
use Illuminate\Support\Facades\Mail;
17
use DavideCasiraghi\LaravelEventsCalendar\Models\Event;
18
use DavideCasiraghi\LaravelEventsCalendar\Models\Country;
19
use DavideCasiraghi\LaravelEventsCalendar\Models\Teacher;
20
use DavideCasiraghi\LaravelEventsCalendar\Models\Organizer;
21
use DavideCasiraghi\LaravelEventsCalendar\Mail\ReportMisuse;
22
use DavideCasiraghi\LaravelEventsCalendar\Models\EventVenue;
23
use DavideCasiraghi\LaravelEventsCalendar\Models\EventCategory;
24
use DavideCasiraghi\LaravelEventsCalendar\Mail\ContactOrganizer;
25
use DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition;
26
use DavideCasiraghi\LaravelEventsCalendar\Facades\LaravelEventsCalendar;
27
28
class EventController extends Controller
29
{
30
    /***************************************************************************/
31
    /* Restrict the access to this resource just to logged in users except show view */
32 33
    public function __construct()
33
    {
34 33
        $this->middleware('auth', ['except' => ['show', 'reportMisuse', 'reportMisuseThankyou', 'mailToOrganizer', 'mailToOrganizerSent', 'eventBySlug', 'eventBySlugAndRepetition', 'EventsListByCountry', 'calculateMonthlySelectOptions']]);
35 33
    }
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 21
    public function store(Request $request)
136
    {
137
        // Validate form datas
138 21
        $validator = $this->eventsValidator($request);
139 21
        if ($validator->fails()) {
140
            //dd($validator->failed());
141 1
            return back()->withErrors($validator)->withInput();
142
        }
143
144 20
        $event = new Event();
145 20
        $this->saveOnDb($request, $event);
146
147 20
        return redirect()->route('events.index')
148 20
                        ->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, $firstRpDates)
161
    {
162 4
        $category = EventCategory::find($event->category_id);
163 4
        $teachers = $event->teachers()->get();
164 4
        $organizers = $event->organizers()->get();
165
166 4
        $venue = DB::table('event_venues')
167 4
                ->select('id', 'name', 'city', 'address', 'zip_code', 'country_id', 'description', 'website')
168 4
                ->where('id', $event->venue_id)
169 4
                ->first();
170
171 4
        $country = DB::table('countries')
172 4
                ->select('id', 'name', 'continent_id')
173 4
                ->where('id', $venue->country_id)
174 4
                ->first();
175
176 4
        $continent = DB::table('continents')
177 4
                ->select('id', 'name')
178 4
                ->where('id', $country->continent_id)
179 4
                ->first();
180
181
        // Repetition text to show
182 4
        switch ($event->repeat_type) {
183 4
                case '1': // noRepeat
184 2
                    $repetition_text = null;
185 2
                    break;
186 2
                case '2': // repeatWeekly
187 1
                    $repeatUntil = new DateTime($event->repeat_until);
188
189
                    // Get the name of the weekly day when the event repeat, if two days, return like "Thursday and Sunday"
190 1
                        $repetitonWeekdayNumbersArray = explode(',', $event->repeat_weekly_on);
191 1
                        $repetitonWeekdayNamesArray = [];
192 1
                        foreach ($repetitonWeekdayNumbersArray as $key => $repetitonWeekdayNumber) {
193 1
                            $repetitonWeekdayNamesArray[] = $this->decodeRepeatWeeklyOn($repetitonWeekdayNumber);
194
                        }
195
                        // create from an array a string with all the values divided by " and "
196 1
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
197
198 1
                    $repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
199 1
                    break;
200 1
                case '3': //repeatMonthly
201 1
                    $repeatUntil = new DateTime($event->repeat_until);
202 1
                    $repetitionFrequency = $this->decodeOnMonthlyKind($event->on_monthly_kind);
203 1
                    $repetition_text = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
204 1
                    break;
205
206
                case '4': //repeatMultipleDays
207
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
208
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
209
                    //$repetition_text = 'The event happens on this dates: '.$event->multiple_dates;
210
                    $repetition_text = 'The event happens on this dates: ';
211
                    $repetition_text .= $dateStart.', ';
212
                    $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

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

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

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

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

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

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

504
                    $day = Carbon::create($year_number, /** @scrutinizer ignore-type */ $month_number, 30, 0, 0, 0)->nthOfMonth($numberOfTheWeek, $weekday);  // eg. Carbon::create(2014, 5, 30, 0, 0, 0)->nthOfQuarter(2, Carbon::SATURDAY);
Loading history...
505
506 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
0 ignored issues
show
Bug introduced by
It seems like $day can also be of type false; however, parameter $dateStart of DavideCasiraghi\LaravelE...veEventRepetitionOnDB() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

506
                    $this->saveEventRepetitionOnDB($event->id, /** @scrutinizer ignore-type */ $day, $day, $timeStart, $timeEnd);
Loading history...
Bug introduced by
It seems like $day can also be of type false; however, parameter $dateEnd of DavideCasiraghi\LaravelE...veEventRepetitionOnDB() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

750
        $ordinalIndicator = $this->getOrdinalIndicator(/** @scrutinizer ignore-type */ $dayNumber);
Loading history...
751
752 1
        array_push($monthlySelectOptions, [
753 1
                'value' => '0|'.$dayNumber,
754 1
                'text' => 'the '.$dayNumber.$ordinalIndicator.' day of the month',
755
            ]);
756
757
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
758 1
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
759 1
            $weekOfTheMonth = $this->weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
760 1
            $ordinalIndicator = $this->getOrdinalIndicator($weekOfTheMonth); //st, nd, rd, th
761
762 1
            array_push($monthlySelectOptions, [
763 1
                'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
764 1
                'text' => 'the '.$weekOfTheMonth.$ordinalIndicator.' '.$dayOfWeekString.' of the month',
765
            ]);
766
767
        // Same day of the month (from the end) - the 3rd to last day (0 if last day, 1 if 2nd to last day, , 2 if 3rd to last day)
768 1
            $dayOfMonthFromTheEnd = $this->dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
769 1
            $ordinalIndicator = $this->getOrdinalIndicator($dayOfMonthFromTheEnd);
770
771 1
        if ($dayOfMonthFromTheEnd == 0) {
772
            $dayText = 'last';
773
        } else {
774 1
            $numberOfTheDay = $dayOfMonthFromTheEnd + 1;
775 1
            $dayText = $numberOfTheDay.$ordinalIndicator.' to last';
776
        }
777
778 1
        array_push($monthlySelectOptions, [
779 1
                'value' => '2|'.$dayOfMonthFromTheEnd,
780 1
                'text' => 'the '.$dayText.' day of the month',
781
            ]);
782
783
        // Same weekday/week of the month (from the end) - the last Friday - (0 if last Friday, 1 if the 2nd to last Friday, 2 if the 3nd to last Friday)
784 1
            $weekOfMonthFromTheEnd = $this->weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
785 1
            $ordinalIndicator = $this->getOrdinalIndicator($weekOfMonthFromTheEnd);
786
787 1
        if ($weekOfMonthFromTheEnd == 1) {
788
            $weekText = 'last ';
789
            $weekValue = 0;
790
        } else {
791 1
            $weekText = $weekOfMonthFromTheEnd.$ordinalIndicator.' to last ';
792 1
            $weekValue = $weekOfMonthFromTheEnd - 1;
793
        }
794
795 1
        array_push($monthlySelectOptions, [
796 1
                'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
797 1
                'text' => 'the '.$weekText.$dayOfWeekString.' of the month',
798
            ]);
799
800
        // GENERATE the HTML to return
801 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='Select repeat monthly kind'>";
802 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
803 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
804
        }
805 1
        $onMonthlyKindSelect .= '</select>';
806
807 1
        return $onMonthlyKindSelect;
808
    }
809
810
    /***************************************************************************/
811
812
    /**
813
     * GET number of the specified weekday in this month (1 for the first).
814
     * $dateTimestamp - unix timestramp of the date specified
815
     * $dayOfWeekValue -  1 (for Monday) through 7 (for Sunday)
816
     * Return the number of the week in the month of the weekday specified.
817
     * @param  string $dateTimestamp
818
     * @param  string $dayOfWeekValue
819
     * @return int
820
     */
821 2
    public function weekdayNumberOfMonth($dateTimestamp, $dayOfWeekValue)
822
    {
823 2
        $cut = substr($dateTimestamp, 0, 8);
824 2
        $daylen = 86400;
825 2
        $timestamp = strtotime($dateTimestamp);
826 2
        $first = strtotime($cut.'01');
827 2
        $elapsed = (($timestamp - $first) / $daylen) + 1;
828 2
        $i = 1;
829 2
        $weeks = 0;
830 2
        for ($i == 1; $i <= $elapsed; $i++) {
831 2
            $dayfind = $cut.(strlen($i) < 2 ? '0'.$i : $i);
832 2
            $daytimestamp = strtotime($dayfind);
833 2
            $day = strtolower(date('N', $daytimestamp));
834 2
            if ($day == strtolower($dayOfWeekValue)) {
835 1
                $weeks++;
836
            }
837
        }
838 2
        if ($weeks == 0) {
0 ignored issues
show
introduced by
The condition $weeks == 0 is always true.
Loading history...
839 1
            $weeks++;
840
        }
841
842 2
        return $weeks;
843
    }
844
845
    /***************************************************************************/
846
847
    /**
848
     * GET number of week from the end of the month - https://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month
849
     * Week of the month = Week of the year - Week of the year of first day of month + 1.
850
     * Return the number of the week in the month of the day specified
851
     * $when - unix timestramp of the date specified.
852
     *
853
     * @param  string $when
854
     * @return int
855
     */
856 2
    public function weekOfMonthFromTheEnd($when = null)
857
    {
858 2
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of strftime() does only seem to accept integer, 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

858
        $numberOfDayOfTheMonth = strftime('%e', /** @scrutinizer ignore-type */ $when); // Day of the month 1-31
Loading history...
859 2
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of date() does only seem to accept integer, 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

859
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', /** @scrutinizer ignore-type */ $when))); // the last day of the month of the specified date
Loading history...
860 2
        $dayDifference = $lastDayOfMonth - $numberOfDayOfTheMonth;
861
862
        switch (true) {
863 2
            case $dayDifference < 7:
864
                $weekFromTheEnd = 1;
865
                break;
866
867 2
            case $dayDifference < 14:
868
                $weekFromTheEnd = 2;
869
                break;
870
871 2
            case $dayDifference < 21:
872 1
                $weekFromTheEnd = 3;
873 1
                break;
874
875 1
            case $dayDifference < 28:
876 1
                $weekFromTheEnd = 4;
877 1
                break;
878
879
            default:
880
                $weekFromTheEnd = 5;
881
                break;
882
        }
883
884 2
        return $weekFromTheEnd;
885
    }
886
887
    /***************************************************************************/
888
889
    /**
890
     * GET number of day from the end of the month.
891
     * $when - unix timestramp of the date specified
892
     * Return the number of day of the month from end.
893
     *
894
     * @param  string $when
895
     * @return int
896
     */
897 2
    public function dayOfMonthFromTheEnd($when = null)
898
    {
899 2
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of strftime() does only seem to accept integer, 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

899
        $numberOfDayOfTheMonth = strftime('%e', /** @scrutinizer ignore-type */ $when); // Day of the month 1-31
Loading history...
900 2
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
0 ignored issues
show
Bug introduced by
It seems like $when can also be of type string; however, parameter $timestamp of date() does only seem to accept integer, 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

900
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', /** @scrutinizer ignore-type */ $when))); // the last day of the month of the specified date
Loading history...
901 2
        $dayDifference = $lastDayOfMonth - $numberOfDayOfTheMonth;
902
903 2
        return $dayDifference;
904
    }
905
906
    /***************************************************************************/
907
908
    /**
909
     * GET the ordinal indicator - for the day of the month.
910
     * Return the ordinal indicator (st, nd, rd, th).
911
     * @param  int $number
912
     * @return string
913
     */
914 4
    public function getOrdinalIndicator($number)
915
    {
916
        switch ($number) {
917 4
            case  1:
918 1
                $ret = 'st';
919 1
                break;
920 4
            case  2:
921 2
                $ret = 'nd';
922 2
                break;
923 4
            case  3:
924 1
                $ret = 'rd';
925 1
                break;
926
            default:
927 4
                $ret = 'th';
928 4
                break;
929
        }
930
931 4
        return $ret;
932
    }
933
934
    /***************************************************************************/
935
936
    /**
937
     * Decode the event repeat_weekly_on field - used in event.show.
938
     * Return a string like "Monday".
939
     *
940
     * @param  string $repeatWeeklyOn
941
     * @return string
942
     */
943 2
    public function decodeRepeatWeeklyOn($repeatWeeklyOn)
944
    {
945 2
        $weekdayArray = ['', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
946 2
        $ret = $weekdayArray[$repeatWeeklyOn];
947
948 2
        return $ret;
949
    }
950
951
    /***************************************************************************/
952
953
    /**
954
     * Decode the event on_monthly_kind field - used in event.show.
955
     * Return a string like "the 4th to last Thursday of the month".
956
     *
957
     * @param  string $onMonthlyKindCode
958
     * @return string
959
     */
960 2
    public function decodeOnMonthlyKind($onMonthlyKindCode)
961
    {
962 2
        $onMonthlyKindCodeArray = explode('|', $onMonthlyKindCode);
963 2
        $weekDays = ['', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
964
965
        //dd($onMonthlyKindCodeArray);
966 2
        switch ($onMonthlyKindCodeArray[0]) {
967 2
            case '0':  // 0|7 eg. the 7th day of the month
968 2
                $dayNumber = $onMonthlyKindCodeArray[1];
969 2
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
0 ignored issues
show
Bug introduced by
$dayNumber of type string is incompatible with the type integer expected by parameter $number of DavideCasiraghi\LaravelE...::getOrdinalIndicator(). ( Ignorable by Annotation )

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

969
                $ordinalIndicator = $this->getOrdinalIndicator(/** @scrutinizer ignore-type */ $dayNumber);
Loading history...
970
971 2
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
972 2
                $format = 'the %s day of the month';
973 2
                $ret = sprintf($format, $dayNumberOrdinal);
974 2
                break;
975 1
            case '1':  // 1|2|4 eg. the 2nd Thursday of the month
976 1
                $dayNumber = $onMonthlyKindCodeArray[1];
977 1
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
978
979 1
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
980 1
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
981 1
                $format = 'the %s %s of the month';
982 1
                $ret = sprintf($format, $dayNumberOrdinal, $weekDay);
983 1
                break;
984 1
            case '2': // 2|20 eg. the 21th to last day of the month
985 1
                $dayNumber = $onMonthlyKindCodeArray[1] + 1;
986 1
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
987
988 1
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
989 1
                $format = 'the %s to last day of the month';
990 1
                $ret = sprintf($format, $dayNumberOrdinal);
991 1
                break;
992 1
            case '3': // 3|3|4 eg. the 4th to last Thursday of the month
993 1
                $dayNumber = $onMonthlyKindCodeArray[1] + 1;
994 1
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
995
996 1
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
997 1
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
998 1
                $format = 'the %s to last %s of the month';
999 1
                $ret = sprintf($format, $dayNumberOrdinal, $weekDay);
1000 1
                break;
1001
        }
1002
1003 2
        return $ret;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ret does not seem to be defined for all execution paths leading up to this point.
Loading history...
1004
    }
1005
1006
    // **********************************************************************
1007
1008
    /**
1009
     * Save/Update the record on DB.
1010
     *
1011
     * @param  \Illuminate\Http\Request $request
1012
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event $event
1013
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
1014
     */
1015 20
    public function saveOnDb($request, $event)
1016
    {
1017 20
        $countries = Country::getCountries();
1018 20
        $teachers = Teacher::pluck('name', 'id');
1019
1020 20
        $venue = DB::table('event_venues')
1021 20
                ->select('event_venues.id AS venue_id', 'event_venues.name AS venue_name', 'event_venues.country_id AS country_id', 'event_venues.continent_id', 'event_venues.city')
1022 20
                ->where('event_venues.id', '=', $request->get('venue_id'))
1023 20
                ->first();
1024
1025 20
        $event->title = $request->get('title');
1026 20
        $event->description = clean($request->get('description'));
1027
1028
        //$event->created_by = (isset(Auth::id())) ? Auth::id() : null;
1029
        //$event->created_by = Auth::id();
1030 20
        if ($request->get('created_by')) {
1031 20
            $event->created_by = $request->get('created_by');
1032
        }
1033
1034 20
        if (! $event->slug) {
1035 20
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
1036
        }
1037 20
        $event->category_id = $request->get('category_id');
1038 20
        $event->venue_id = $request->get('venue_id');
1039 20
        $event->image = $request->get('image');
1040 20
        $event->contact_email = $request->get('contact_email');
1041 20
        $event->website_event_link = $request->get('website_event_link');
1042 20
        $event->facebook_event_link = $request->get('facebook_event_link');
1043 20
        $event->status = $request->get('status');
1044 20
        $event->on_monthly_kind = $request->get('on_monthly_kind');
1045 20
        $event->multiple_dates = $request->get('multiple_dates');
1046
1047
        // Event teaser image upload
1048
        //dd($request->file('image'));
1049 20
        if ($request->file('image')) {
1050
            $imageFile = $request->file('image');
1051
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
1052
            $imageSubdir = 'events_teaser';
1053
            $imageWidth = '968';
1054
            $thumbWidth = '310';
1055
1056
            $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

1056
            $this->uploadImageOnServer(/** @scrutinizer ignore-type */ $imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
Loading history...
1057
            $event->image = $imageName;
1058
        } else {
1059 20
            $event->image = $request->get('image');
1060
        }
1061
1062
        // Support columns for homepage search (we need this to show events in HP with less use of resources)
1063 20
        $event->sc_country_id = $venue->country_id;
1064 20
        $event->sc_country_name = $countries[$venue->country_id];
1065 20
        $event->sc_city_name = $venue->city;
1066 20
        $event->sc_venue_name = $venue->venue_name;
1067 20
        $event->sc_teachers_id = json_encode(explode(',', $request->get('multiple_teachers')));
1068 20
        $event->sc_continent_id = $venue->continent_id;
1069
1070
        // Multiple teachers - populate support column field
1071 20
        $event->sc_teachers_names = '';
1072 20
        if ($request->get('multiple_teachers')) {
1073 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
1074
1075 2
            $multiple_teachers_names = [];
1076 2
            foreach ($multiple_teachers as $key => $teacher_id) {
1077 2
                $multiple_teachers_names[] = $teachers[$teacher_id];
1078
            }
1079
1080 2
            $event->sc_teachers_names .= LaravelEventsCalendar::getStringFromArraySeparatedByComma($multiple_teachers_names);
1081
        }
1082
1083
        // Set the Event attributes about repeating (repeat until field and multiple days)
1084 20
        $event = $this->setEventRepeatFields($request, $event);
1085
1086
        // Save event and repetitions
1087 20
        $event->save();
1088 20
        $this->saveEventRepetitions($request, $event);
1089
1090
        // Update multi relationships with teachers and organizers tables.
1091 20
        if ($request->get('multiple_teachers')) {
1092 2
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
1093 2
            $event->teachers()->sync($multiple_teachers);
1094
        } else {
1095 18
            $event->teachers()->sync([]);
1096
        }
1097 20
        if ($request->get('multiple_organizers')) {
1098
            $multiple_organizers = explode(',', $request->get('multiple_organizers'));
1099
            $event->organizers()->sync($multiple_organizers);
1100
        } else {
1101 20
            $event->organizers()->sync([]);
1102
        }
1103 20
    }
1104
1105
    /***********************************************************************/
1106
1107
    /**
1108
     * Get creator email.
1109
     *
1110
     * @param  int $created_by
1111
     * @return \Illuminate\Foundation\Auth\User
1112
     */
1113
    public function getCreatorEmail($created_by)
1114
    {
1115
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
1116
                ->select('email')
1117
                ->where('id', $created_by)
1118
                ->first();
1119
1120
        $ret = $creatorEmail->email;
1121
1122
        return $ret;
1123
    }
1124
1125
    /***************************************************************************/
1126
1127
    /**
1128
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
1129
     *
1130
     * @param  string  $slug
1131
     * @return \Illuminate\Http\Response
1132
     */
1133 1
    public function eventBySlug($slug)
1134
    {
1135 1
        $event = Event::where('slug', $slug)->first();
1136 1
        $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
1137
1138 1
        return $this->show($event, $firstRpDates);
1139
    }
1140
1141
    /***************************************************************************/
1142
1143
    /**
1144
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
1145
     * @param  string $slug
1146
     * @param  int $repetitionId
1147
     * @return \Illuminate\Http\Response
1148
     */
1149 3
    public function eventBySlugAndRepetition($slug, $repetitionId)
1150
    {
1151 3
        $event = Event::where('slug', $slug)->first();
1152 3
        $firstRpDates = Event::getFirstEventRpDatesByRepetitionId($repetitionId);
1153
1154
        // If not found get the first repetion of the event in the future.
1155 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...
1156 1
            $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
1157
        }
1158
1159 3
        return $this->show($event, $firstRpDates);
1160
    }
1161
1162
    /***************************************************************************/
1163
1164
    /**
1165
     * Return the Event validator with all the defined constraint.
1166
     * @param  \Illuminate\Http\Request  $request
1167
     * @return \Illuminate\Http\Response
1168
     */
1169 21
    public function eventsValidator($request)
1170
    {
1171
        $rules = [
1172 21
            'title' => 'required',
1173 21
            'description' => 'required',
1174 21
            'category_id' => 'required',
1175 21
            'venue_id' => 'required',
1176 21
            'startDate' => 'required',
1177 21
            'endDate' => 'required',
1178 21
            'repeat_until' => Rule::requiredIf($request->repeat_type == 2 || $request->repeat_type == 3),
1179 21
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
1180 21
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
1181 21
            'contact_email' => 'nullable|email',
1182 21
            'facebook_event_link' => 'nullable|url',
1183 21
            'website_event_link' => 'nullable|url',
1184
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
1185
        ];
1186 21
        if ($request->hasFile('image')) {
1187
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
1188
        }
1189
1190
        $messages = [
1191 21
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
1192
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
1193
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
1194
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
1195
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
1196
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
1197
        ];
1198
1199 21
        $validator = Validator::make($request->all(), $rules, $messages);
1200
1201
        // End date and start date must match if the event is repetitive
1202
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
1203 21
            return $input->repeat_type > 1;
1204 21
        });
1205
1206 21
        return $validator;
1207
    }
1208
}
1209