Completed
Push — master ( 04f8f5...069d0a )
by Davide
07:11
created

EventController   F

Complexity

Total Complexity 105

Size/Duplication

Total Lines 1170
Duplicated Lines 0 %

Test Coverage

Coverage 81.85%

Importance

Changes 10
Bugs 2 Features 2
Metric Value
wmc 105
eloc 536
c 10
b 2
f 2
dl 0
loc 1170
ccs 451
cts 551
cp 0.8185
rs 2

31 Methods

Rating   Name   Duplication   Size   Complexity  
B saveMonthlyRepeatDates() 0 61 11
A isWeekDay() 0 8 2
B edit() 0 56 10
A update() 0 12 2
A index() 0 47 5
A destroy() 0 10 1
A store() 0 14 2
A saveEventRepetitions() 0 54 5
B show() 0 68 7
A saveWeeklyRepeatDates() 0 11 4
A create() 0 24 1
A __construct() 0 3 1
A decodeRepeatWeeklyOn() 0 6 1
A reportMisuse() 0 34 5
A setEventRepeatFields() 0 30 5
A getOrdinalIndicator() 0 18 4
A saveEventRepetitionOnDB() 0 8 1
A mailToOrganizer() 0 22 1
A mailToOrganizerSent() 0 3 1
A weekdayNumberOfMonth() 0 22 5
A saveMultipleRepeatDates() 0 11 2
A calculateMonthlySelectOptions() 0 71 4
A dayOfMonthFromTheEnd() 0 7 1
A weekOfMonthFromTheEnd() 0 29 5
A decodeOnMonthlyKind() 0 44 5
A reportMisuseThankyou() 0 3 1
A getCreatorEmail() 0 10 1
A eventsValidator() 0 38 3
A eventBySlugAndRepetition() 0 11 2
A eventBySlug() 0 6 1
B saveOnDb() 0 74 6

How to fix   Complexity   

Complex Class

Complex classes like EventController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use EventController, and based on these observations, apply Extract Interface, too.

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

208
                    $repetition_text .= LaravelEventsCalendar::/** @scrutinizer ignore-call */ getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
Loading history...
209
210
                    break;
211
            }
212
213
        // True if the repetition start and end on the same day
214 4
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
215
216 4
        return view('laravel-events-calendar::events.show', compact('event'))
217 4
                ->with('category', $category)
218 4
                ->with('teachers', $teachers)
219 4
                ->with('organizers', $organizers)
220 4
                ->with('venue', $venue)
221 4
                ->with('country', $country)
222 4
                ->with('continent', $continent)
223 4
                ->with('datesTimes', $firstRpDates)
224 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...
225 4
                ->with('sameDateStartEnd', $sameDateStartEnd);
226
    }
227
228
    /***************************************************************************/
229
230
    /**
231
     * Show the form for editing the specified resource.
232
     *
233
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
234
     * @return \Illuminate\Http\Response
235
     */
236 1
    public function edit(Event $event)
237
    {
238
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
239 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...
240 1
            $authorUserId = $this->getLoggedAuthorId();
241
242
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
243 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
244
245 1
            $users = User::pluck('name', 'id');
246 1
            $teachers = Teacher::pluck('name', 'id');
247 1
            $organizers = Organizer::pluck('name', 'id');
248 1
            $venues = DB::table('event_venues')
249 1
                    ->select('id', 'name', 'address', 'city')->get();
250
251 1
            $eventFirstRepetition = DB::table('event_repetitions')
252 1
                    ->select('id', 'start_repeat', 'end_repeat')
253 1
                    ->where('event_id', '=', $event->id)
254 1
                    ->first();
255
256 1
            $dateTime = [];
257 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
258 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
259 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
260 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
261 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
262 1
            $dateTime['multipleDates'] = $event->multiple_dates;
263
264
            // GET Multiple teachers
265 1
            $teachersDatas = $event->teachers;
266 1
            $teachersSelected = [];
267 1
            foreach ($teachersDatas as $teacherDatas) {
268
                array_push($teachersSelected, $teacherDatas->id);
269
            }
270 1
            $multiple_teachers = implode(',', $teachersSelected);
271
272
            // GET Multiple Organizers
273 1
            $organizersDatas = $event->organizers;
274 1
            $organizersSelected = [];
275 1
            foreach ($organizersDatas as $organizerDatas) {
276
                array_push($organizersSelected, $organizerDatas->id);
277
            }
278 1
            $multiple_organizers = implode(',', $organizersSelected);
279
280 1
            return view('laravel-events-calendar::events.edit', compact('event'))
281 1
                        ->with('eventCategories', $eventCategories)
282 1
                        ->with('users', $users)
283 1
                        ->with('teachers', $teachers)
284 1
                        ->with('multiple_teachers', $multiple_teachers)
285 1
                        ->with('organizers', $organizers)
286 1
                        ->with('multiple_organizers', $multiple_organizers)
287 1
                        ->with('venues', $venues)
288 1
                        ->with('dateTime', $dateTime)
289 1
                        ->with('authorUserId', $authorUserId);
290
        } else {
291
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
292
        }
293
    }
294
295
    /***************************************************************************/
296
297
    /**
298
     * Update the specified resource in storage.
299
     *
300
     * @param  \Illuminate\Http\Request  $request
301
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
302
     * @return \Illuminate\Http\Response
303
     */
304 2
    public function update(Request $request, Event $event)
305
    {
306
        // Validate form datas
307 2
        $validator = $this->eventsValidator($request);
308 2
        if ($validator->fails()) {
309 1
            return back()->withErrors($validator)->withInput();
310
        }
311
312 1
        $this->saveOnDb($request, $event);
313
314 1
        return redirect()->route('events.index')
315 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
316
    }
317
318
    /***************************************************************************/
319
320
    /**
321
     * Remove the specified resource from storage.
322
     *
323
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
324
     * @return \Illuminate\Http\Response
325
     */
326 1
    public function destroy(Event $event)
327
    {
328 1
        DB::table('event_repetitions')
329 1
                ->where('event_id', $event->id)
330 1
                ->delete();
331
332 1
        $event->delete();
333
334 1
        return redirect()->route('events.index')
335 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
336
    }
337
338
    /***************************************************************************/
339
340
    /**
341
     * To save event repetitions for create and update methods.
342
     *
343
     * @param  \Illuminate\Http\Request  $request
344
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
345
     * @return void
346
     */
347 20
    public function saveEventRepetitions($request, $event)
348
    {
349 20
        Event::deletePreviousRepetitions($event->id);
350
351
        // Saving repetitions - If it's a single event will be stored with just one repetition
352 20
        $timeStart = date('H:i:s', strtotime($request->get('time_start')));
353 20
        $timeEnd = date('H:i:s', strtotime($request->get('time_end')));
354 20
        switch ($request->get('repeat_type')) {
355 20
                case '1':  // noRepeat
356 13
                    $eventRepetition = new EventRepetition();
357 13
                    $eventRepetition->event_id = $event->id;
358
359 13
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
360 13
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
361
362 13
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
363 13
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
364 13
                    $eventRepetition->save();
365
366 13
                    break;
367
368 7
                case '2':   // repeatWeekly
369
370
                    // Convert the start date in a format that can be used for strtotime
371 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
372
373
                    // Calculate repeat until day
374 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
375 2
                        $this->saveWeeklyRepeatDates($event, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
376
377 2
                    break;
378
379 5
                case '3':  //repeatMonthly
380
                    // Same of repeatWeekly
381 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
382 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
383
384
                    // Get the array with month repeat details
385 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
386
387 5
                        $this->saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
388
389 5
                    break;
390
391
                case '4':  //repeatMultipleDays
392
                    // Same of repeatWeekly
393
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
394
395
                    // Get the array with single day repeat details
396
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
397
398
                        $this->saveMultipleRepeatDates($event, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
399
400
                    break;
401
            }
402 20
    }
403
404
    /***************************************************************************/
405
406
    /**
407
     * 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
408
     * $dayOfTheWeek: 1|2|3|4|5|6|7 (MONDAY-SUNDAY)
409
     * https://stackoverflow.com/questions/2045736/getting-all-dates-for-mondays-and-tuesdays-for-the-next-year.
410
     *
411
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
412
     * @param  string $date
413
     * @param  int $dayOfTheWeek
414
     * @return void
415
     */
416 3
    public function isWeekDay($date, $dayOfTheWeek)
417
    {
418
        // Fix the bug that was avoiding to save Sunday. Date 'w' identify sunday as 0 and not 7.
419 3
        if ($dayOfTheWeek == 7) {
420 1
            $dayOfTheWeek = 0;
421
        }
422
423 3
        return date('w', strtotime($date)) == $dayOfTheWeek;
424
    }
425
426
    /***************************************************************************/
427
428
    /**
429
     * Save all the weekly repetitions in the event_repetitions table.
430
     * $dateStart and $dateEnd are in the format Y-m-d
431
     * $timeStart and $timeEnd are in the format H:i:s.
432
     * $weekDays - $request->get('repeat_weekly_on_day').
433
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
434
     * @param  string  $weekDays
435
     * @param  string  $startDate
436
     * @param  string  $repeatUntilDate
437
     * @param  string  $timeStart
438
     * @param  string  $timeEnd
439
     * @return void
440
     */
441 2
    public function saveWeeklyRepeatDates($event, $weekDays, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
442
    {
443 2
        $beginPeriod = new DateTime($startDate);
444 2
        $endPeriod = new DateTime($repeatUntilDate);
445 2
        $interval = DateInterval::createFromDateString('1 day');
446 2
        $period = new DatePeriod($beginPeriod, $interval, $endPeriod);
447
448 2
        foreach ($period as $day) {  // Iterate for each day of the period
449 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...
450 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...
451 2
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
452
                }
453
            }
454
        }
455 2
    }
456
457
    /***************************************************************************/
458
459
    /**
460
     * Save all the weekly repetitions inthe event_repetitions table
461
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
462
     *
463
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
464
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
465
     *                      0|28 the 28th day of the month
466
     *                      1|2|2 the 2nd Tuesday of the month
467
     *                      2|17 the 18th to last day of the month
468
     *                      3|1|3 the 2nd to last Wednesday of the month
469
     * @param  string  $startDate (Y-m-d)
470
     * @param  string  $repeatUntilDate (Y-m-d)
471
     * @param  string  $timeStart (H:i:s)
472
     * @param  string  $timeEnd (H:i:s)
473
     * @return void
474
     */
475 5
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
476
    {
477 5
        $start = $month = strtotime($startDate);
0 ignored issues
show
Unused Code introduced by
The assignment to $start is dead and can be removed.
Loading history...
478 5
        $end = strtotime($repeatUntilDate);
479
480 5
        $numberOfTheWeekArray = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
481 5
        $weekdayArray = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
482
483 5
        switch ($monthRepeatDatas[0]) {
484 5
            case '0':  // Same day number - eg. "the 28th day of the month"
485 2
                while ($month < $end) {
486 2
                    $day = date('Y-m-d', $month);
487 2
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
488 2
                    $month = strtotime('+1 month', $month);
489
                }
490 2
                break;
491 3
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
492 1
                $numberOfTheWeek = $numberOfTheWeekArray[$monthRepeatDatas[1] - 1]; //eg. first | second | third | fourth | fifth
493 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
494
495 1
                while ($month < $end) {
496 1
                    $monthString = date('Y-m', $month);  //eg. 2015-12
497
498
                    // The day to pick
499
                        //dd($numberOfTheWeek." ".$weekday." ".$monthString);
500 1
                    $day = date('Y-m-d', strtotime($numberOfTheWeek.' '.$weekday.' '.$monthString));  // get the first weekday of a month eg. strtotime("first wednesday 2015-12")
501 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
502 1
                    $month = strtotime('+1 month', $month);
503
                }
504 1
                break;
505 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)
506 1
                while ($month < $end) {
507 1
                    $monthString = date('Y-m', $month);  //eg. 2015-12
508 1
                    $day = date('Y-m-d', strtotime('last day of '.$monthString));  // get the last day of a month eg. strtotime("last day of 2015-12")
509 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
510 1
                    $month = strtotime('+1 month', $month);
511
                }
512 1
                break;
513 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)
514 1
                $numberOfTheWeekFromTheEnd = $monthRepeatDatas[1]; //eg. 0(last) | 1 | 2 | 3 | 4
515 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
516 1
                while ($month < $end) {
517 1
                    $monthString = date('Y-m', $month);  //eg. 2015-12
518 1
                    $timestamp = strtotime(date('Y-m-d', strtotime('last '.$weekday.' of '.$monthString))); // get the last weekday of a month eg. strtotime("last wednesday 2015-12")
519
                    //dd(date("Y-m-d", strtotime("last ".$weekday." of ".$monthString)));
520
                    switch ($numberOfTheWeekFromTheEnd) {
521 1
                        case '0':
522
                            $day = date('Y-m-d', $timestamp);
523
                            break;
524 1
                        case '1':
525 1
                            $day = date('Y-m-d', strtotime('-1 week', $timestamp));
526 1
                            break;
527
                        default:
528
                            $day = date('Y-m-d', strtotime('-'.$numberOfTheWeekFromTheEnd.' weeks', $timestamp));
529
                            break;
530
                    }
531
532 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
533 1
                    $month = strtotime('+1 month', $month);
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
        $report['event_slug'] = $request->slug;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$report was never initialized. Although not strictly required by PHP, it is generally a good practice to add $report = array(); before regardless.
Loading history...
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 == 1) {
772
            $dayText = 'last';
773
            $dayValue = 0;
774
        } else {
775 1
            $dayText = $dayOfMonthFromTheEnd.$ordinalIndicator.' to last';
776 1
            $dayValue = $dayOfMonthFromTheEnd - 1;
777
        }
778
779 1
        array_push($monthlySelectOptions, [
780 1
            'value' => '2|'.$dayValue,
781 1
            'text' => 'the '.$dayText.' day of the month',
782
        ]);
783
784
        // 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)
785
786
        // Get the date parameters
787 1
                $weekOfMonthFromTheEnd = $this->weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
788 1
                $ordinalIndicator = $this->getOrdinalIndicator($weekOfMonthFromTheEnd);
789
790 1
        if ($weekOfMonthFromTheEnd == 1) {
791
            $weekText = 'last ';
792
            $weekValue = 0;
793
        } else {
794 1
            $weekText = $weekOfMonthFromTheEnd.$ordinalIndicator.' to last ';
795 1
            $weekValue = $weekOfMonthFromTheEnd - 1;
796
        }
797
798 1
        array_push($monthlySelectOptions, [
799 1
                'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
800 1
                'text' => 'the '.$weekText.$dayOfWeekString.' of the month',
801
            ]);
802
803
        // GENERATE the HTML to return
804 1
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='Select repeat monthly kind'>";
805 1
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
806 1
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
807
        }
808 1
        $onMonthlyKindSelect .= '</select>';
809
810 1
        return $onMonthlyKindSelect;
811
    }
812
813
    /***************************************************************************/
814
815
    /**
816
     * GET number of the specified weekday in this month (1 for the first).
817
     * $dateTimestamp - unix timestramp of the date specified
818
     * $dayOfWeekValue -  1 (for Monday) through 7 (for Sunday)
819
     * Return the number of the week in the month of the weekday specified.
820
     * @param  string $dateTimestamp
821
     * @param  string $dayOfWeekValue
822
     * @return int
823
     */
824 2
    public function weekdayNumberOfMonth($dateTimestamp, $dayOfWeekValue)
825
    {
826 2
        $cut = substr($dateTimestamp, 0, 8);
827 2
        $daylen = 86400;
828 2
        $timestamp = strtotime($dateTimestamp);
829 2
        $first = strtotime($cut.'01');
830 2
        $elapsed = (($timestamp - $first) / $daylen) + 1;
831 2
        $i = 1;
832 2
        $weeks = 0;
833 2
        for ($i == 1; $i <= $elapsed; $i++) {
834 2
            $dayfind = $cut.(strlen($i) < 2 ? '0'.$i : $i);
835 2
            $daytimestamp = strtotime($dayfind);
836 2
            $day = strtolower(date('N', $daytimestamp));
837 2
            if ($day == strtolower($dayOfWeekValue)) {
838 1
                $weeks++;
839
            }
840
        }
841 2
        if ($weeks == 0) {
0 ignored issues
show
introduced by
The condition $weeks == 0 is always true.
Loading history...
842 1
            $weeks++;
843
        }
844
845 2
        return $weeks;
846
    }
847
848
    /***************************************************************************/
849
850
    /**
851
     * GET number of week from the end of the month - https://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month
852
     * Week of the month = Week of the year - Week of the year of first day of month + 1.
853
     * Return the number of the week in the month of the day specified
854
     * $when - unix timestramp of the date specified.
855
     *
856
     * @param  string $when
857
     * @return int
858
     */
859 2
    public function weekOfMonthFromTheEnd($when = null)
860
    {
861 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

861
        $numberOfDayOfTheMonth = strftime('%e', /** @scrutinizer ignore-type */ $when); // Day of the month 1-31
Loading history...
862 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

862
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', /** @scrutinizer ignore-type */ $when))); // the last day of the month of the specified date
Loading history...
863 2
        $dayDifference = $lastDayOfMonth - $numberOfDayOfTheMonth;
864
865
        switch (true) {
866 2
            case $dayDifference < 7:
867
                $weekFromTheEnd = 1;
868
                break;
869
870 2
            case $dayDifference < 14:
871
                $weekFromTheEnd = 2;
872
                break;
873
874 2
            case $dayDifference < 21:
875 1
                $weekFromTheEnd = 3;
876 1
                break;
877
878 1
            case $dayDifference < 28:
879 1
                $weekFromTheEnd = 4;
880 1
                break;
881
882
            default:
883
                $weekFromTheEnd = 5;
884
                break;
885
        }
886
887 2
        return $weekFromTheEnd;
888
    }
889
890
    /***************************************************************************/
891
892
    /**
893
     * GET number of day from the end of the month.
894
     * $when - unix timestramp of the date specified
895
     * Return the number of day of the month from end.
896
     *
897
     * @param  string $when
898
     * @return int
899
     */
900 2
    public function dayOfMonthFromTheEnd($when = null)
901
    {
902 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

902
        $numberOfDayOfTheMonth = strftime('%e', /** @scrutinizer ignore-type */ $when); // Day of the month 1-31
Loading history...
903 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

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

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

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