Completed
Push — master ( 633925...7a4edf )
by Davide
08:59
created

EventController::decodeRepeatWeeklyOn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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')->orderBy('name')->pluck('name', 'id');
104 1
        $users = User::orderBy('name')->pluck('name', 'id');
105 1
        $teachers = Teacher::orderBy('name')->pluck('name', 'id');
106 1
        $organizers = Organizer::orderBy('name')->pluck('name', 'id');
107
        //$venues = EventVenue::pluck('name', 'id');
108 1
        $venues = DB::table('event_venues')
109 1
                ->select('id', 'name', 'city')->orderBy('name')->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
                    $dateStart = date('d/m/Y', strtotime($firstRpDates->start_repeat));
206
                    $singleDaysRepeatDatas = explode(',', $event->multiple_dates);
207
                    //$repetition_text = 'The event happens on this dates: '.$event->multiple_dates;
208
                    $repetition_text = 'The event happens on this dates: ';
209
                    $repetition_text .= $dateStart.', ';
210
                    $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

210
                    $repetition_text .= LaravelEventsCalendar::/** @scrutinizer ignore-call */ getStringFromArraySeparatedByComma($singleDaysRepeatDatas);
Loading history...
211
212
                    break;
213
            }
214
215
        // True if the repetition start and end on the same day
216 4
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
217
218 4
        return view('laravel-events-calendar::events.show', compact('event'))
219 4
                ->with('category', $category)
220 4
                ->with('teachers', $teachers)
221 4
                ->with('organizers', $organizers)
222 4
                ->with('venue', $venue)
223 4
                ->with('country', $country)
224 4
                ->with('continent', $continent)
225 4
                ->with('datesTimes', $firstRpDates)
226 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...
227 4
                ->with('sameDateStartEnd', $sameDateStartEnd);
228
    }
229
230
    /***************************************************************************/
231
232
    /**
233
     * Show the form for editing the specified resource.
234
     *
235
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
236
     * @return \Illuminate\Http\Response
237
     */
238 1
    public function edit(Event $event)
239
    {
240
        //if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
241 1
        if (Auth::user()->id == $event->created_by || Auth::user()->group == 1 || Auth::user()->group == 2) {
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
Bug introduced by
Accessing group on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
242 1
            $authorUserId = $this->getLoggedAuthorId();
243
244
            //$eventCategories = EventCategory::pluck('name', 'id');  // removed because was braking the tests
245 1
            $eventCategories = EventCategory::listsTranslations('name')->orderBy('name')->pluck('name', 'id');
246
247 1
            $users = User::orderBy('name')->pluck('name', 'id');
248 1
            $teachers = Teacher::orderBy('name')->pluck('name', 'id');
249 1
            $organizers = Organizer::orderBy('name')->pluck('name', 'id');
250 1
            $venues = DB::table('event_venues')
251 1
                    ->select('id', 'name', 'address', 'city')->orderBy('name')->get();
252
253 1
            $eventFirstRepetition = DB::table('event_repetitions')
254 1
                    ->select('id', 'start_repeat', 'end_repeat')
255 1
                    ->where('event_id', '=', $event->id)
256 1
                    ->first();
257
258 1
            $dateTime = [];
259 1
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
260 1
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
261 1
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
262 1
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
263 1
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
264 1
            $dateTime['multipleDates'] = $event->multiple_dates;
265
266
            // GET Multiple teachers
267 1
            $teachersDatas = $event->teachers;
268 1
            $teachersSelected = [];
269 1
            foreach ($teachersDatas as $teacherDatas) {
270
                array_push($teachersSelected, $teacherDatas->id);
271
            }
272 1
            $multiple_teachers = implode(',', $teachersSelected);
273
274
            // GET Multiple Organizers
275 1
            $organizersDatas = $event->organizers;
276 1
            $organizersSelected = [];
277 1
            foreach ($organizersDatas as $organizerDatas) {
278
                array_push($organizersSelected, $organizerDatas->id);
279
            }
280 1
            $multiple_organizers = implode(',', $organizersSelected);
281
282 1
            return view('laravel-events-calendar::events.edit', compact('event'))
283 1
                        ->with('eventCategories', $eventCategories)
284 1
                        ->with('users', $users)
285 1
                        ->with('teachers', $teachers)
286 1
                        ->with('multiple_teachers', $multiple_teachers)
287 1
                        ->with('organizers', $organizers)
288 1
                        ->with('multiple_organizers', $multiple_organizers)
289 1
                        ->with('venues', $venues)
290 1
                        ->with('dateTime', $dateTime)
291 1
                        ->with('authorUserId', $authorUserId);
292
        } else {
293
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
294
        }
295
    }
296
297
    /***************************************************************************/
298
299
    /**
300
     * Update the specified resource in storage.
301
     *
302
     * @param  \Illuminate\Http\Request  $request
303
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
304
     * @return \Illuminate\Http\Response
305
     */
306 2
    public function update(Request $request, Event $event)
307
    {
308
        // Validate form datas
309 2
        $validator = $this->eventsValidator($request);
310 2
        if ($validator->fails()) {
311 1
            return back()->withErrors($validator)->withInput();
312
        }
313
314 1
        $this->saveOnDb($request, $event);
315
316 1
        return redirect()->route('events.index')
317 1
                        ->with('success', __('laravel-events-calendar::messages.event_updated_successfully'));
318
    }
319
320
    /***************************************************************************/
321
322
    /**
323
     * Remove the specified resource from storage.
324
     *
325
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
326
     * @return \Illuminate\Http\Response
327
     */
328 1
    public function destroy(Event $event)
329
    {
330 1
        DB::table('event_repetitions')
331 1
                ->where('event_id', $event->id)
332 1
                ->delete();
333
334 1
        $event->delete();
335
336 1
        return redirect()->route('events.index')
337 1
                        ->with('success', __('laravel-events-calendar::messages.event_deleted_successfully'));
338
    }
339
340
    /***************************************************************************/
341
342
    /**
343
     * To save event repetitions for create and update methods.
344
     *
345
     * @param  \Illuminate\Http\Request  $request
346
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
347
     * @return void
348
     */
349 20
    public function saveEventRepetitions($request, $event)
350
    {
351 20
        Event::deletePreviousRepetitions($event->id);
352
353
        // Saving repetitions - If it's a single event will be stored with just one repetition
354 20
        $timeStart = date('H:i:s', strtotime($request->get('time_start')));
355 20
        $timeEnd = date('H:i:s', strtotime($request->get('time_end')));
356 20
        switch ($request->get('repeat_type')) {
357 20
                case '1':  // noRepeat
358 13
                    $eventRepetition = new EventRepetition();
359 13
                    $eventRepetition->event_id = $event->id;
360
361 13
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
362 13
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
363
364 13
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
365 13
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
366 13
                    $eventRepetition->save();
367
368 13
                    break;
369
370 7
                case '2':   // repeatWeekly
371
372
                    // Convert the start date in a format that can be used for strtotime
373 2
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
374
375
                    // Calculate repeat until day
376 2
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
377 2
                        $this->saveWeeklyRepeatDates($event, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
378
379 2
                    break;
380
381 5
                case '3':  //repeatMonthly
382
                    // Same of repeatWeekly
383 5
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
384 5
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
385
386
                    // Get the array with month repeat details
387 5
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
388
389 5
                        $this->saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
390
391 5
                    break;
392
393
                case '4':  //repeatMultipleDays
394
                    // Same of repeatWeekly
395
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
396
397
                    // Get the array with single day repeat details
398
                        $singleDaysRepeatDatas = explode(',', $request->get('multiple_dates'));
399
400
                        $this->saveMultipleRepeatDates($event, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd);
401
402
                    break;
403
            }
404 20
    }
405
406
    /***************************************************************************/
407
408
    /**
409
     * 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
410
     * $dayOfTheWeek: 1|2|3|4|5|6|7 (MONDAY-SUNDAY)
411
     * https://stackoverflow.com/questions/2045736/getting-all-dates-for-mondays-and-tuesdays-for-the-next-year.
412
     *
413
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
414
     * @param  string $date
415
     * @param  int $dayOfTheWeek
416
     * @return void
417
     */
418 3
    public function isWeekDay($date, $dayOfTheWeek)
419
    {
420
        // Fix the bug that was avoiding to save Sunday. Date 'w' identify sunday as 0 and not 7.
421 3
        if ($dayOfTheWeek == 7) {
422 1
            $dayOfTheWeek = 0;
423
        }
424
425 3
        return date('w', strtotime($date)) == $dayOfTheWeek;
426
    }
427
428
    /***************************************************************************/
429
430
    /**
431
     * Save all the weekly repetitions in the event_repetitions table.
432
     * $dateStart and $dateEnd are in the format Y-m-d
433
     * $timeStart and $timeEnd are in the format H:i:s.
434
     * $weekDays - $request->get('repeat_weekly_on_day').
435
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
436
     * @param  string  $weekDays
437
     * @param  string  $startDate
438
     * @param  string  $repeatUntilDate
439
     * @param  string  $timeStart
440
     * @param  string  $timeEnd
441
     * @return void
442
     */
443 2
    public function saveWeeklyRepeatDates($event, $weekDays, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
444
    {
445 2
        $beginPeriod = new DateTime($startDate);
446 2
        $endPeriod = new DateTime($repeatUntilDate);
447 2
        $interval = DateInterval::createFromDateString('1 day');
448 2
        $period = new DatePeriod($beginPeriod, $interval, $endPeriod);
449
450 2
        foreach ($period as $day) {  // Iterate for each day of the period
451 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...
452 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...
453 2
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
454
                }
455
            }
456
        }
457 2
    }
458
459
    /***************************************************************************/
460
461
    /**
462
     * Save all the weekly repetitions inthe event_repetitions table
463
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
464
     *
465
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
466
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
467
     *                      0|28 the 28th day of the month
468
     *                      1|2|2 the 2nd Tuesday of the month
469
     *                      2|17 the 18th to last day of the month
470
     *                      3|1|3 the 2nd to last Wednesday of the month
471
     * @param  string  $startDate (Y-m-d)
472
     * @param  string  $repeatUntilDate (Y-m-d)
473
     * @param  string  $timeStart (H:i:s)
474
     * @param  string  $timeEnd (H:i:s)
475
     * @return void
476
     */
477 5
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
478
    {
479 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...
480 5
        $end = strtotime($repeatUntilDate);
481
482 5
        $numberOfTheWeekArray = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
483 5
        $weekdayArray = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
484
485 5
        switch ($monthRepeatDatas[0]) {
486 5
            case '0':  // Same day number - eg. "the 28th day of the month"
487 2
                while ($month < $end) {
488 2
                    $day = date('Y-m-d', $month);
489 2
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
490 2
                    $month = strtotime('+1 month', $month);
491
                }
492 2
                break;
493 3
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
494 1
                $numberOfTheWeek = $numberOfTheWeekArray[$monthRepeatDatas[1] - 1]; //eg. first | second | third | fourth | fifth
495 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
496
497 1
                while ($month < $end) {
498 1
                    $monthString = date('Y-m', $month);  //eg. 2015-12
499
500
                    // The day to pick
501
                        //dd($numberOfTheWeek." ".$weekday." ".$monthString);
502 1
                    $day = date('Y-m-d', strtotime($numberOfTheWeek.' '.$weekday.' '.$monthString));  // get the first weekday of a month eg. strtotime("first wednesday 2015-12")
503 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
504 1
                    $month = strtotime('+1 month', $month);
505
                }
506 1
                break;
507 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)
508 1
                while ($month < $end) {
509 1
                    $monthString = date('Y-m', $month);  //eg. 2015-12
510 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")
511 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
512 1
                    $month = strtotime('+1 month', $month);
513
                }
514 1
                break;
515 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)
516 1
                $numberOfTheWeekFromTheEnd = $monthRepeatDatas[1]; //eg. 0(last) | 1 | 2 | 3 | 4
517 1
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
518 1
                while ($month < $end) {
519 1
                    $monthString = date('Y-m', $month);  //eg. 2015-12
520 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")
521
                    //dd(date("Y-m-d", strtotime("last ".$weekday." of ".$monthString)));
522
                    switch ($numberOfTheWeekFromTheEnd) {
523 1
                        case '0':
524
                            $day = date('Y-m-d', $timestamp);
525
                            break;
526 1
                        case '1':
527 1
                            $day = date('Y-m-d', strtotime('-1 week', $timestamp));
528 1
                            break;
529
                        default:
530
                            $day = date('Y-m-d', strtotime('-'.$numberOfTheWeekFromTheEnd.' weeks', $timestamp));
531
                            break;
532
                    }
533
534 1
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
535 1
                    $month = strtotime('+1 month', $month);
536
                }
537 1
                break;
538
        }
539 5
    }
540
541
    /***************************************************************************/
542
543
    /**
544
     * Save all the weekly repetitions inthe event_repetitions table
545
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
546
     *
547
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
548
     * @param  array   $singleDaysRepeatDatas - explode of $request->get('multiple_dates')
549
     * @param  string  $startDate (Y-m-d)
550
     * @param  string  $timeStart (H:i:s)
551
     * @param  string  $timeEnd (H:i:s)
552
     * @return void
553
     */
554
    public function saveMultipleRepeatDates($event, $singleDaysRepeatDatas, $startDate, $timeStart, $timeEnd)
555
    {
556
        $dateTime = strtotime($startDate);
557
        $day = date('Y-m-d', $dateTime);
558
        $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
559
560
        foreach ($singleDaysRepeatDatas as $key => $singleDayRepeatDatas) {
561
            $dateTime = strtotime($singleDayRepeatDatas);
562
            $day = date('Y-m-d', $dateTime);
563
564
            $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
565
        }
566
    }
567
568
    /***************************************************************************/
569
570
    /**
571
     * Save event repetition in the DB.
572
     * $dateStart and $dateEnd are in the format Y-m-d
573
     * $timeStart and $timeEnd are in the format H:i:s.
574
     * @param  int $eventId
575
     * @param  string $dateStart
576
     * @param  string $dateEnd
577
     * @param  string $timeStart
578
     * @param  string $timeEnd
579
     * @return void
580
     */
581 7
    public function saveEventRepetitionOnDB($eventId, $dateStart, $dateEnd, $timeStart, $timeEnd)
582
    {
583 7
        $eventRepetition = new EventRepetition();
584 7
        $eventRepetition->event_id = $eventId;
585
586 7
        $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
587 7
        $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
588 7
        $eventRepetition->save();
589 7
    }
590
591
    /***************************************************************************/
592
593
    /**
594
     * Send the Misuse mail.
595
     *
596
     * @param  \Illuminate\Http\Request  $request
597
     * @return \Illuminate\Http\Response
598
     */
599
    public function reportMisuse(Request $request)
600
    {
601
        $report = [];
602
603
        $report['senderEmail'] = '[email protected]';
604
        $report['senderName'] = 'Anonymus User';
605
        $report['subject'] = 'Report misuse form';
606
        //$report['adminEmail'] = env('ADMIN_MAIL');
607
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
608
609
        $report['message'] = $request->message;
610
        $report['event_title'] = $request->event_title;
611
        $report['event_id'] = $request->event_id;
612
        $report['event_slug'] = $request->slug;
613
614
        switch ($request->reason) {
615
            case '1':
616
                $report['reason'] = 'Not about Contact Improvisation';
617
                break;
618
            case '2':
619
                $report['reason'] = 'Contains wrong informations';
620
                break;
621
            case '3':
622
                $report['reason'] = 'It is not translated in english';
623
                break;
624
            case '4':
625
                $report['reason'] = 'Other (specify in the message)';
626
                break;
627
        }
628
629
        //Mail::to($request->user())->send(new ReportMisuse($report));
630
        Mail::to(env('ADMIN_MAIL'))->send(new ReportMisuse($report));
631
632
        return redirect()->route('events.misuse-thankyou');
633
    }
634
635
    /***************************************************************************/
636
637
    /**
638
     * Send the mail to the Organizer (from the event modal in the event show view).
639
     *
640
     * @param  \Illuminate\Http\Request  $request
641
     * @return \Illuminate\Http\Response
642
     */
643
    public function mailToOrganizer(Request $request)
644
    {
645
        $message = [];
646
        $message['senderEmail'] = $request->user_email;
647
        $message['senderName'] = $request->user_name;
648
        $message['subject'] = 'Request from the Global CI Calendar';
649
        //$message['emailTo'] = $organizersEmails;
650
651
        $message['message'] = $request->message;
652
        $message['event_title'] = $request->event_title;
653
        $message['event_id'] = $request->event_id;
654
        $message['event_slug'] = $request->slug;
655
656
        /*
657
        $eventOrganizers = Event::find($request->event_id)->organizers;
658
        foreach ($eventOrganizers as $eventOrganizer) {
659
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
660
        }*/
661
662
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
663
664
        return redirect()->route('events.organizer-sent');
665
    }
666
667
    /***************************************************************************/
668
669
    /**
670
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
671
     *
672
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
673
     * @return \Illuminate\Http\Response
674
     */
675 1
    public function mailToOrganizerSent()
676
    {
677 1
        return view('laravel-events-calendar::emails.contact.organizer-sent');
678
    }
679
680
    /***************************************************************************/
681
682
    /**
683
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
684
     * @return \Illuminate\Http\Response
685
     */
686 1
    public function reportMisuseThankyou()
687
    {
688 1
        return view('laravel-events-calendar::emails.report-thankyou');
689
    }
690
691
    /***************************************************************************/
692
693
    /**
694
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
695
     *
696
     * @param  \Illuminate\Http\Request  $request
697
     * @param  \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
698
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event  $event
699
     */
700 20
    public function setEventRepeatFields($request, $event)
701
    {
702
        // Set Repeat Until
703 20
        $event->repeat_type = $request->get('repeat_type');
704 20
        if ($request->get('repeat_until')) {
705 7
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
706 7
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
707
        }
708
709
        // Weekely - Set multiple week days
710 20
        if ($request->get('repeat_weekly_on_day')) {
711 2
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
712
            //dd($repeat_weekly_on_day);
713 2
            $i = 0;
714 2
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
715 2
            $event->repeat_weekly_on = '';
716 2
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
717 2
                $event->repeat_weekly_on .= $weeek_day;
718 2
                if ($i != $len - 1) {  // not last
719 2
                    $event->repeat_weekly_on .= ',';
720
                }
721 2
                $i++;
722
            }
723
        }
724
725
        // Monthly
726
727
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
728
729 20
        return $event;
730
    }
731
732
    /***************************************************************************/
733
734
    /**
735
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
736
     * - Used by the AJAX in the event repeat view -
737
     * - The HTML contain a <select></select> with four <options></options>.
738
     *
739
     * @param  \Illuminate\Http\Request  $request  - Just the day
740
     * @return string
741
     */
742 1
    public function calculateMonthlySelectOptions(Request $request)
743
    {
744 1
        $monthlySelectOptions = [];
745 1
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
746 1
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
747 1
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
748
749
        // Same day number - eg. "the 28th day of the month"
750 1
        $dateArray = explode('/', $request->day);
751 1
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
752 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

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

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

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

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

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

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

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