Completed
Push — master ( ba992d...dc755b )
by Davide
07:03
created

EventController::index()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 48
rs 8.8234
c 0
b 0
f 0
cc 5
nc 4
nop 1
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\User;
6
use DateTime;
7
use App\Event;
8
use Validator;
9
use DatePeriod;
10
use App\Country;
11
use App\Teacher;
12
use DateInterval;
13
use App\Organizer;
14
use App\EventVenue;
15
use App\EventCategory;
16
use App\EventRepetition;
17
use App\Mail\ReportMisuse;
18
use Illuminate\Support\Str;
19
use Illuminate\Http\Request;
20
use App\Mail\ContactOrganizer;
21
use Illuminate\Validation\Rule;
22
use Illuminate\Support\Facades\DB;
23
use Illuminate\Support\Facades\Auth;
24
use Illuminate\Support\Facades\Mail;
25
26
class EventController extends Controller
27
{
28
    /***************************************************************************/
29
    /* Restrict the access to this resource just to logged in users except show view */
30
    public function __construct()
31
    {
32
        $this->middleware('auth', ['except' => ['show', 'reportMisuse', 'reportMisuseThankyou', 'mailToOrganizer', 'mailToOrganizerSent', 'eventBySlug', 'eventBySlugAndRepetition', 'EventsListByCountry']]);
33
    }
34
35
    /***************************************************************************/
36
37
    /**
38
     * Display a listing of the resource.
39
     * @param  \Illuminate\Http\Request  $request
40
     * @return \Illuminate\Http\Response
41
     */
42
    public function index(Request $request)
43
    {
44
        // To show just the events created by the the user - If admin or super admin is set to null show all the events
45
        $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
46
47
        $eventCategories = EventCategory::orderBy('name')->pluck('name', 'id');
48
        $countries = Country::orderBy('name')->pluck('name', 'id');
49
        $venues = EventVenue::pluck('country_id', 'id');
50
51
        $searchKeywords = $request->input('keywords');
52
        $searchCategory = $request->input('category_id');
53
        $searchCountry = $request->input('country_id');
54
55
        if ($searchKeywords || $searchCategory || $searchCountry) {
56
            $events = Event::
57
                // Show only the events owned by the user, if the user is an admin or super admin show all the events
58
                when(isset($authorUserId), function ($query, $authorUserId) {
59
                    return $query->where('created_by', $authorUserId);
60
                })
61
                ->when($searchKeywords, function ($query, $searchKeywords) {
62
                    return $query->where('title', $searchKeywords)->orWhere('title', 'like', '%'.$searchKeywords.'%');
63
                })
64
                ->when($searchCategory, function ($query, $searchCategory) {
65
                    return $query->where('category_id', '=', $searchCategory);
66
                })
67
                ->when($searchCountry, function ($query, $searchCountry) {
68
                    return $query->join('event_venues', 'events.venue_id', '=', 'event_venues.id')->where('event_venues.country_id', '=', $searchCountry);
69
                })
70
                ->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
71
                ->paginate(20);
72
73
        //dd($events);
74
        } else {
75
            $events = Event::latest()
76
                ->when($authorUserId, function ($query, $authorUserId) {
77
                    return $query->where('created_by', $authorUserId);
78
                })->paginate(20);
79
        }
80
81
        return view('events.index', compact('events'))
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
82
            ->with('i', (request()->input('page', 1) - 1) * 20)
83
            ->with('eventCategories', $eventCategories)
84
            ->with('countries', $countries)
85
            ->with('venues', $venues)
86
            ->with('searchKeywords', $searchKeywords)
87
            ->with('searchCategory', $searchCategory)
88
            ->with('searchCountry', $searchCountry);
89
    }
90
91
    /***************************************************************************/
92
93
    /**
94
     * Show the form for creating a new resource.
95
     *
96
     * @return \Illuminate\Http\Response
97
     */
98
    public function create()
99
    {
100
        $authorUserId = $this->getLoggedAuthorId();
101
102
        $eventCategories = EventCategory::pluck('name', 'id');
103
        $users = User::pluck('name', 'id');
104
        $teachers = Teacher::pluck('name', 'id');
105
        $organizers = Organizer::pluck('name', 'id');
106
        //$venues = EventVenue::pluck('name', 'id');
107
        $venues = DB::table('event_venues')
108
                ->select('id', 'name', 'city')->get();
109
110
        $dateTime = [];
111
        $dateTime['repeatUntil'] = null;
112
113
        return view('events.create')
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
114
            ->with('eventCategories', $eventCategories)
115
            ->with('users', $users)
116
            ->with('teachers', $teachers)
117
            ->with('organizers', $organizers)
118
            ->with('venues', $venues)
119
            ->with('dateTime', $dateTime)
120
            ->with('authorUserId', $authorUserId);
121
    }
122
123
    /***************************************************************************/
124
125
    /**
126
     * Store a newly created resource in storage.
127
     *
128
     * @param  \Illuminate\Http\Request  $request
129
     * @return \Illuminate\Http\Response
130
     */
131 View Code Duplication
    public function store(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
132
    {
133
        // Validate form datas
134
        $validator = $this->eventsValidator($request);
135
        if ($validator->fails()) {
136
            return back()->withErrors($validator)->withInput();
137
        }
138
139
        $event = new Event();
140
        $this->saveOnDb($request, $event);
141
142
        return redirect()->route('events.index')
143
                        ->with('success', __('messages.event_added_successfully'));
144
    }
145
146
    /***************************************************************************/
147
148
    /**
149
     * Display the specified resource.
150
     *
151
     * @param  \App\Event  $event
152
     * @param  $firstRpDates
153
     * @return \Illuminate\Http\Response
154
     */
155
    public function show(Event $event, $firstRpDates)
156
    {
157
        $category = EventCategory::find($event->category_id);
158
        $teachers = $event->teachers()->get();
159
        $organizers = $event->organizers()->get();
160
161
        $venue = DB::table('event_venues')
162
                ->select('id', 'name', 'city', 'address', 'zip_code', 'country_id')
163
                ->where('id', $event->venue_id)
164
                ->first();
165
166
        $country = DB::table('countries')
167
                ->select('id', 'name', 'continent_id')
168
                ->where('id', $venue->country_id)
169
                ->first();
170
171
        $continent = DB::table('continents')
172
                ->select('id', 'name')
173
                ->where('id', $country->continent_id)
174
                ->first();
175
176
        // Repetition text to show
177
        switch ($event->repeat_type) {
178
                case '1': // noRepeat
179
                    $repetition_text = null;
180
                    break;
181
                case '2': // repeatWeekly
182
                    $repeatUntil = new DateTime($event->repeat_until);
183
184
                    // Get the name of the weekly day when the event repeat, if two days, return like "Thursday and Sunday"
185
                        $repetitonWeekdayNumbersArray = explode(',', $event->repeat_weekly_on);
186
                        $repetitonWeekdayNamesArray = [];
187
                        foreach ($repetitonWeekdayNumbersArray as $key => $repetitonWeekdayNumber) {
188
                            $repetitonWeekdayNamesArray[] = $this->decodeRepeatWeeklyOn($repetitonWeekdayNumber);
189
                        }
190
                        // create from an array a string with all the values divided by " and "
191
                        $nameOfTheRepetitionWeekDays = implode(' and ', $repetitonWeekdayNamesArray);
192
193
                    $repetition_text = 'The event happens every '.$nameOfTheRepetitionWeekDays.' until '.$repeatUntil->format('d/m/Y');
194
                    break;
195
                case '3': //repeatMonthly
196
                    $repeatUntil = new DateTime($event->repeat_until);
197
                    $repetitionFrequency = $this->decodeOnMonthlyKind($event->on_monthly_kind);
198
                    $repetition_text = 'The event happens '.$repetitionFrequency.' until '.$repeatUntil->format('d/m/Y');
199
                    break;
200
            }
201
202
        // True if the repetition start and end on the same day
203
        $sameDateStartEnd = ((date('Y-m-d', strtotime($firstRpDates->start_repeat))) == (date('Y-m-d', strtotime($firstRpDates->end_repeat)))) ? 1 : 0;
204
205
        return view('events.show', compact('event'))
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
206
                ->with('category', $category)
207
                ->with('teachers', $teachers)
208
                ->with('organizers', $organizers)
209
                ->with('venue', $venue)
210
                ->with('country', $country)
211
                ->with('continent', $continent)
212
                ->with('datesTimes', $firstRpDates)
213
                ->with('repetition_text', $repetition_text)
0 ignored issues
show
Bug introduced by
The variable $repetition_text does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
214
                ->with('sameDateStartEnd', $sameDateStartEnd);
215
    }
216
217
    /***************************************************************************/
218
219
    /**
220
     * Show the form for editing the specified resource.
221
     *
222
     * @param  \App\Event  $event
223
     * @return \Illuminate\Http\Response
224
     */
225
    public function edit(Event $event)
226
    {
227
        if (Auth::user()->id == $event->created_by || Auth::user()->isSuperAdmin() || Auth::user()->isAdmin()) {
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?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Bug introduced by
The method isSuperAdmin() does not seem to exist on object<Illuminate\Contracts\Auth\Authenticatable>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method isAdmin() does not seem to exist on object<Illuminate\Contracts\Auth\Authenticatable>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
228
            $authorUserId = $this->getLoggedAuthorId();
229
230
            $eventCategories = EventCategory::pluck('name', 'id');
231
            $users = User::pluck('name', 'id');
232
            $teachers = Teacher::pluck('name', 'id');
233
            $organizers = Organizer::pluck('name', 'id');
234
            $venues = DB::table('event_venues')
235
                    ->select('id', 'name', 'address', 'city')->get();
236
237
            $eventFirstRepetition = DB::table('event_repetitions')
238
                    ->select('id', 'start_repeat', 'end_repeat')
239
                    ->where('event_id', '=', $event->id)
240
                    ->first();
241
242
            $dateTime = [];
243
            $dateTime['dateStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->start_repeat)) : '';
244
            $dateTime['dateEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('d/m/Y', strtotime($eventFirstRepetition->end_repeat)) : '';
245
            $dateTime['timeStart'] = (isset($eventFirstRepetition->start_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->start_repeat)) : '';
246
            $dateTime['timeEnd'] = (isset($eventFirstRepetition->end_repeat)) ? date('g:i A', strtotime($eventFirstRepetition->end_repeat)) : '';
247
            $dateTime['repeatUntil'] = date('d/m/Y', strtotime($event->repeat_until));
248
249
            // GET Multiple teachers
250
            $teachersDatas = $event->teachers;
251
            $teachersSelected = [];
252
            foreach ($teachersDatas as $teacherDatas) {
253
                array_push($teachersSelected, $teacherDatas->id);
254
            }
255
            $multiple_teachers = implode(',', $teachersSelected);
256
257
            // GET Multiple Organizers
258
            $organizersDatas = $event->organizers;
259
            $organizersSelected = [];
260
            foreach ($organizersDatas as $organizerDatas) {
261
                array_push($organizersSelected, $organizerDatas->id);
262
            }
263
            $multiple_organizers = implode(',', $organizersSelected);
264
265
            return view('events.edit', compact('event'))
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
266
                        ->with('eventCategories', $eventCategories)
267
                        ->with('users', $users)
268
                        ->with('teachers', $teachers)
269
                        ->with('multiple_teachers', $multiple_teachers)
270
                        ->with('organizers', $organizers)
271
                        ->with('multiple_organizers', $multiple_organizers)
272
                        ->with('venues', $venues)
273
                        ->with('dateTime', $dateTime)
274
                        ->with('authorUserId', $authorUserId);
275
        } else {
276
            return redirect()->route('home')->with('message', __('auth.not_allowed_to_access'));
277
        }
278
    }
279
280
    /***************************************************************************/
281
282
    /**
283
     * Update the specified resource in storage.
284
     *
285
     * @param  \Illuminate\Http\Request  $request
286
     * @param  \App\Event  $event
287
     * @return \Illuminate\Http\Response
288
     */
289
    public function update(Request $request, Event $event)
290
    {
291
        // Validate form datas
292
        $validator = $this->eventsValidator($request);
293
        if ($validator->fails()) {
294
            return back()->withErrors($validator)->withInput();
295
        }
296
297
        $this->saveOnDb($request, $event);
298
299
        return redirect()->route('events.index')
300
                        ->with('success', __('messages.event_updated_successfully'));
301
    }
302
303
    /***************************************************************************/
304
305
    /**
306
     * Remove the specified resource from storage.
307
     *
308
     * @param  \App\Event  $event
309
     * @return \Illuminate\Http\Response
310
     */
311
    public function destroy(Event $event)
312
    {
313
        $eventFirstRepetition = DB::table('event_repetitions')
0 ignored issues
show
Unused Code introduced by
$eventFirstRepetition is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
314
                //->where('active', 0)->delete();
315
                ->where('event_id', $event->id)
316
                ->delete();
317
318
        $event->delete();
319
320
        return redirect()->route('events.index')
321
                        ->with('success', __('messages.event_deleted_successfully'));
322
    }
323
324
    /***************************************************************************/
325
326
    /**
327
     * To save event repetitions for create and update methods.
328
     *
329
     * @param  \Illuminate\Http\Request  $request
330
     * @param  \App\Event  $event
331
     * @return void
332
     */
333
    public function saveEventRepetitions($request, $event)
334
    {
335
        Event::deletePreviousRepetitions($event->id);
336
337
        // Saving repetitions - If it's a single event will be stored with just one repetition
338
        $timeStart = date('H:i:s', strtotime($request->get('time_start')));
339
        $timeEnd = date('H:i:s', strtotime($request->get('time_end')));
340
        switch ($request->get('repeat_type')) {
341
                case '1':  // noRepeat
342
                    $eventRepetition = new EventRepetition();
343
                    $eventRepetition->event_id = $event->id;
344
345
                    $dateStart = implode('-', array_reverse(explode('/', $request->get('startDate'))));
346
                    $dateEnd = implode('-', array_reverse(explode('/', $request->get('endDate'))));
347
348
                    $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
349
                    $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
350
                    $eventRepetition->save();
351
352
                    break;
353
354 View Code Duplication
                case '2':   // repeatWeekly
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
355
356
                    // Convert the start date in a format that can be used for strtotime
357
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
358
359
                    // Calculate repeat until day
360
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
361
                        $this->saveWeeklyRepeatDates($event, $request->get('repeat_weekly_on_day'), $startDate, $repeatUntilDate, $timeStart, $timeEnd);
362
363
                    break;
364
365 View Code Duplication
                case '3':  //repeatMonthly
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
366
                    // Same of repeatWeekly
367
                        $startDate = implode('-', array_reverse(explode('/', $request->get('startDate'))));
368
                        $repeatUntilDate = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
369
370
                    // Get the array with month repeat details
371
                        $monthRepeatDatas = explode('|', $request->get('on_monthly_kind'));
372
373
                        $this->saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd);
374
375
                    break;
376
            }
377
    }
378
379
    /***************************************************************************/
380
381
    /**
382
     * 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
383
     * $dayOfTheWeek: 1|2|3|4|5|6|7 (MONDAY-SUNDAY)
384
     * https://stackoverflow.com/questions/2045736/getting-all-dates-for-mondays-and-tuesdays-for-the-next-year.
385
     *
386
     * @param  \App\Event  $event
0 ignored issues
show
Bug introduced by
There is no parameter named $event. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
387
     * @param  string $date
388
     * @param  int $dayOfTheWeek
389
     * @return void
390
     */
391
    public function isWeekDay($date, $dayOfTheWeek)
392
    {
393
        // Fix the bug that was avoiding to save Sunday. Date 'w' identify sunday as 0 and not 7.
394
        if ($dayOfTheWeek == 7) {
395
            $dayOfTheWeek = 0;
396
        }
397
398
        return date('w', strtotime($date)) == $dayOfTheWeek;
399
    }
400
401
    /***************************************************************************/
402
403
    /**
404
     * Save all the weekly repetitions in the event_repetitions table.
405
     * $dateStart and $dateEnd are in the format Y-m-d
406
     * $timeStart and $timeEnd are in the format H:i:s.
407
     * $weekDays - $request->get('repeat_weekly_on_day').
408
     * @param  \App\Event  $event
409
     * @param  string  $weekDays
410
     * @param  string  $startDate
411
     * @param  string  $repeatUntilDate
412
     * @param  string  $timeStart
413
     * @param  string  $timeEnd
414
     * @return void
415
     */
416
    public function saveWeeklyRepeatDates($event, $weekDays, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
417
    {
418
        $beginPeriod = new DateTime($startDate);
419
        $endPeriod = new DateTime($repeatUntilDate);
420
        $interval = DateInterval::createFromDateString('1 day');
421
        $period = new DatePeriod($beginPeriod, $interval, $endPeriod);
422
423
        foreach ($period as $day) {  // Iterate for each day of the period
424
            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...
425
                if ($this->isWeekDay($day->format('Y-m-d'), $weekDayNumber)) {
426
                    $this->saveEventRepetitionOnDB($event->id, $day->format('Y-m-d'), $day->format('Y-m-d'), $timeStart, $timeEnd);
427
                }
428
            }
429
        }
430
    }
431
432
    /***************************************************************************/
433
434
    /**
435
     * Save all the weekly repetitions inthe event_repetitions table
436
     * useful: http://thisinterestsme.com/php-get-first-monday-of-month/.
437
     *
438
     * @param  \App\Event  $event
439
     * @param  array   $monthRepeatDatas - explode of $request->get('on_monthly_kind')
440
     *                      0|28 the 28th day of the month
441
     *                      1|2|2 the 2nd Tuesday of the month
442
     *                      2|17 the 18th to last day of the month
443
     *                      3|1|3 the 2nd to last Wednesday of the month
444
     * @param  string  $startDate (Y-m-d)
445
     * @param  string  $repeatUntilDate (Y-m-d)
446
     * @param  string  $timeStart (H:i:s)
447
     * @param  string  $timeEnd (H:i:s)
448
     * @return void
449
     */
450
    public function saveMonthlyRepeatDates($event, $monthRepeatDatas, $startDate, $repeatUntilDate, $timeStart, $timeEnd)
451
    {
452
        $start = $month = strtotime($startDate);
0 ignored issues
show
Unused Code introduced by
$start is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
453
        $end = strtotime($repeatUntilDate);
454
455
        $numberOfTheWeekArray = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'];
456
        $weekdayArray = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
457
458
        switch ($monthRepeatDatas[0]) {
459
            case '0':  // Same day number - eg. "the 28th day of the month"
460
                while ($month < $end) {
461
                    $day = date('Y-m-d', $month);
462
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
463
                    $month = strtotime('+1 month', $month);
464
                }
465
                break;
466
            case '1':  // Same weekday/week of the month - eg. the "1st Monday"
467
                $numberOfTheWeek = $numberOfTheWeekArray[$monthRepeatDatas[1] - 1]; //eg. first | second | third | fourth | fifth
468
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
469
470
                while ($month < $end) {
471
                    $monthString = date('Y-m', $month);  //eg. 2015-12
472
473
                    // The day to pick
474
                        //dd($numberOfTheWeek." ".$weekday." ".$monthString);
475
                    $day = date('Y-m-d', strtotime($numberOfTheWeek.' '.$weekday.' '.$monthString));  // get the first weekday of a month eg. strtotime("first wednesday 2015-12")
476
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
477
                    $month = strtotime('+1 month', $month);
478
                }
479
                break;
480
            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)
481
                while ($month < $end) {
482
                    $monthString = date('Y-m', $month);  //eg. 2015-12
483
                    $day = date('Y-m-d', strtotime('last day of '.$monthString));  // get the last day of a month eg. strtotime("last day of 2015-12")
484
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
485
                    $month = strtotime('+1 month', $month);
486
                }
487
                break;
488
            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)
489
                $numberOfTheWeekFromTheEnd = $monthRepeatDatas[1]; //eg. 0(last) | 1 | 2 | 3 | 4
490
                $weekday = $weekdayArray[$monthRepeatDatas[2] - 1]; // eg. monday | tuesday | wednesday
491
                while ($month < $end) {
492
                    $monthString = date('Y-m', $month);  //eg. 2015-12
493
                    $timestamp = strtotime(date('Y-m-d', strtotime('last '.$weekday.' of '.$monthString))); // get the last weekday of a month eg. strtotime("last wednesday 2015-12")
494
                    //dd(date("Y-m-d", strtotime("last ".$weekday." of ".$monthString)));
495
                    switch ($numberOfTheWeekFromTheEnd) {
496
                        case '0':
497
                            $day = date('Y-m-d', $timestamp);
498
                            break;
499
                        case '1':
500
                            $day = date('Y-m-d', strtotime('-1 week', $timestamp));
501
                            break;
502
                        default:
503
                            $day = date('Y-m-d', strtotime('-'.$numberOfTheWeekFromTheEnd.' weeks', $timestamp));
504
                            break;
505
                    }
506
507
                    $this->saveEventRepetitionOnDB($event->id, $day, $day, $timeStart, $timeEnd);
508
                    $month = strtotime('+1 month', $month);
509
                }
510
                break;
511
        }
512
    }
513
514
    /***************************************************************************/
515
516
    /**
517
     * Save event repetition in the DB.
518
     * $dateStart and $dateEnd are in the format Y-m-d
519
     * $timeStart and $timeEnd are in the format H:i:s.
520
     * @param  int $eventId
521
     * @param  string $dateStart
522
     * @param  string $dateEnd
523
     * @param  string $timeStart
524
     * @param  string $timeEnd
525
     * @return void
526
     */
527
    public function saveEventRepetitionOnDB($eventId, $dateStart, $dateEnd, $timeStart, $timeEnd)
528
    {
529
        $eventRepetition = new EventRepetition();
530
        $eventRepetition->event_id = $eventId;
531
532
        $eventRepetition->start_repeat = $dateStart.' '.$timeStart;
533
        $eventRepetition->end_repeat = $dateEnd.' '.$timeEnd;
534
        $eventRepetition->save();
535
    }
536
537
    /***************************************************************************/
538
539
    /**
540
     * Send the Misuse mail.
541
     *
542
     * @param  \Illuminate\Http\Request  $request
543
     * @return \Illuminate\Http\Response
544
     */
545
    public function reportMisuse(Request $request)
546
    {
547
        $report = [];
548
549
        $report['senderEmail'] = '[email protected]';
550
        $report['senderName'] = 'Anonymus User';
551
        $report['subject'] = 'Report misuse form';
552
        $report['adminEmail'] = env('ADMIN_MAIL');
553
        $report['creatorEmail'] = $this->getCreatorEmail($request->created_by);
554
555
        $report['message'] = $request->message;
556
        $report['event_title'] = $request->event_title;
557
        $report['event_id'] = $request->event_id;
558
559
        switch ($request->reason) {
560
            case '1':
561
                $report['reason'] = 'Not about Contact Improvisation';
562
                break;
563
            case '2':
564
                $report['reason'] = 'Contains wrong informations';
565
                break;
566
            case '3':
567
                $report['reason'] = 'It is not translated in english';
568
                break;
569
            case '4':
570
                $report['reason'] = 'Other (specify in the message)';
571
                break;
572
        }
573
574
        //Mail::to($request->user())->send(new ReportMisuse($report));
575
        Mail::to('[email protected]')->send(new ReportMisuse($report));
576
577
        return redirect()->route('events.misuse-thankyou');
578
    }
579
580
    /***************************************************************************/
581
582
    /**
583
     * Send the mail to the Organizer (from the event modal in the event show view).
584
     *
585
     * @param  \Illuminate\Http\Request  $request
586
     * @return \Illuminate\Http\Response
587
     */
588
    public function mailToOrganizer(Request $request)
589
    {
590
        $message = [];
591
        $message['senderEmail'] = $request->user_email;
592
        $message['senderName'] = $request->user_name;
593
        $message['subject'] = 'Request from the Global CI Calendar';
594
        //$message['emailTo'] = $organizersEmails;
595
596
        $message['message'] = $request->message;
597
        $message['event_title'] = $request->event_title;
598
        $message['event_id'] = $request->event_id;
599
600
        /*
601
        $eventOrganizers = Event::find($request->event_id)->organizers;
602
        foreach ($eventOrganizers as $eventOrganizer) {
603
            Mail::to($eventOrganizer->email)->send(new ContactOrganizer($message));
604
        }*/
605
        Mail::to($request->contact_email)->send(new ContactOrganizer($message));
606
607
        return redirect()->route('events.organizer-sent');
608
    }
609
610
    /***************************************************************************/
611
612
    /**
613
     * Display the thank you view after the mail to the organizer is sent (called by /mailToOrganizer/sent route).
614
     *
615
     * @param  \App\Event  $event
0 ignored issues
show
Bug introduced by
There is no parameter named $event. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
616
     * @return \Illuminate\Http\Response
617
     */
618
    public function mailToOrganizerSent()
619
    {
620
        return view('emails.contact.organizer-sent');
621
    }
622
623
    /***************************************************************************/
624
625
    /**
626
     * Display the thank you view after the misuse report mail is sent (called by /misuse/thankyou route).
627
     * @return \Illuminate\Http\Response
628
     */
629
    public function reportMisuseThankyou()
630
    {
631
        return view('emails.report-thankyou');
632
    }
633
634
    /***************************************************************************/
635
636
    /**
637
     * Set the Event attributes about repeating before store or update (repeat until field and multiple days).
638
     *
639
     * @param  \Illuminate\Http\Request  $request
640
     * @param  \App\Event  $event
641
     * @return \App\Event  $event
642
     */
643
    public function setEventRepeatFields($request, $event)
644
    {
645
646
        // Set Repeat Until
647
        $event->repeat_type = $request->get('repeat_type');
648
        if ($request->get('repeat_until')) {
649
            $dateRepeatUntil = implode('-', array_reverse(explode('/', $request->get('repeat_until'))));
650
            $event->repeat_until = $dateRepeatUntil.' 00:00:00';
651
        }
652
653
        // Weekely - Set multiple week days
654
        if ($request->get('repeat_weekly_on_day')) {
655
            $repeat_weekly_on_day = $request->get('repeat_weekly_on_day');
656
            //dd($repeat_weekly_on_day);
657
            $i = 0;
658
            $len = count($repeat_weekly_on_day); // to put "," to all items except the last
659
            $event->repeat_weekly_on = '';
660
            foreach ($repeat_weekly_on_day as $key => $weeek_day) {
661
                $event->repeat_weekly_on .= $weeek_day;
662
                if ($i != $len - 1) {  // not last
663
                    $event->repeat_weekly_on .= ',';
664
                }
665
                $i++;
666
            }
667
        }
668
669
        // Monthly
670
671
        /* $event->repeat_type = $request->get('repeat_monthly_on');*/
672
673
        return $event;
674
    }
675
676
    /***************************************************************************/
677
678
    /**
679
     * Return the HTML of the monthly select dropdown - inspired by - https://www.theindychannel.com/calendar
680
     * - Used by the AJAX in the event repeat view -
681
     * - The HTML contain a <select></select> with four <options></options>.
682
     *
683
     * @param  \Illuminate\Http\Request  $request  - Just the day
684
     * @return string
685
     */
686
    public function calculateMonthlySelectOptions(Request $request)
687
    {
688
        $monthlySelectOptions = [];
689
        $date = implode('-', array_reverse(explode('/', $request->day)));  // Our YYYY-MM-DD date string
690
        $unixTimestamp = strtotime($date);  // Convert the date string into a unix timestamp.
691
        $dayOfWeekString = date('l', $unixTimestamp); // Monday | Tuesday | Wednesday | ..
692
693
        // Same day number - eg. "the 28th day of the month"
694
        $dateArray = explode('/', $request->day);
695
        $dayNumber = ltrim($dateArray[0], '0'); // remove the 0 in front of a day number eg. 02/10/2018
696
        $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
697
698
        array_push($monthlySelectOptions, [
699
                'value' => '0|'.$dayNumber,
700
                'text' => 'the '.$dayNumber.$ordinalIndicator.' day of the month',
701
            ]);
702
703
        // Same weekday/week of the month - eg. the "1st Monday" 1|1|1 (first week, monday)
704
            $dayOfWeekValue = date('N', $unixTimestamp); // 1 (for Monday) through 7 (for Sunday)
705
            $weekOfTheMonth = $this->weekdayNumberOfMonth($date, $dayOfWeekValue); // 1 | 2 | 3 | 4 | 5
706
            $ordinalIndicator = $this->getOrdinalIndicator($weekOfTheMonth); //st, nd, rd, th
707
708
            array_push($monthlySelectOptions, [
709
                'value' => '1|'.$weekOfTheMonth.'|'.$dayOfWeekValue,
710
                'text' => 'the '.$weekOfTheMonth.$ordinalIndicator.' '.$dayOfWeekString.' of the month',
711
            ]);
712
713
        // 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)
714
            $dayOfMonthFromTheEnd = $this->dayOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
715
            $ordinalIndicator = $this->getOrdinalIndicator($dayOfMonthFromTheEnd);
716
717
        if ($dayOfMonthFromTheEnd == 1) {
718
            $dayText = 'last';
719
            $dayValue = 0;
720
        } else {
721
            $dayText = $dayOfMonthFromTheEnd.$ordinalIndicator.' to last';
722
            $dayValue = $dayOfMonthFromTheEnd - 1;
723
        }
724
725
        array_push($monthlySelectOptions, [
726
            'value' => '2|'.$dayValue,
727
            'text' => 'the '.$dayText.' day of the month',
728
        ]);
729
730
        // 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)
731
732
        // Get the date parameters
733
                $weekOfMonthFromTheEnd = $this->weekOfMonthFromTheEnd($unixTimestamp); // 1 | 2 | 3 | 4 | 5
734
                $ordinalIndicator = $this->getOrdinalIndicator($weekOfMonthFromTheEnd);
735
736
        if ($weekOfMonthFromTheEnd == 1) {
737
            $weekText = 'last ';
738
            $weekValue = 0;
739
        } else {
740
            $weekText = $weekOfMonthFromTheEnd.$ordinalIndicator.' to last ';
741
            $weekValue = $weekOfMonthFromTheEnd - 1;
742
        }
743
744
        array_push($monthlySelectOptions, [
745
                'value' => '3|'.$weekValue.'|'.$dayOfWeekValue,
746
                'text' => 'the '.$weekText.$dayOfWeekString.' of the month',
747
            ]);
748
749
        // GENERATE the HTML to return
750
        $onMonthlyKindSelect = "<select name='on_monthly_kind' id='on_monthly_kind' class='selectpicker' title='Select repeat monthly kind'>";
751
        foreach ($monthlySelectOptions as $key => $monthlySelectOption) {
752
            $onMonthlyKindSelect .= "<option value='".$monthlySelectOption['value']."'>".$monthlySelectOption['text'].'</option>';
753
        }
754
        $onMonthlyKindSelect .= '</select>';
755
756
        return $onMonthlyKindSelect;
757
    }
758
759
    /***************************************************************************/
760
761
    /**
762
     * GET number of the specified weekday in this month (1 for the first).
763
     * $dateTimestamp - unix timestramp of the date specified
764
     * $dayOfWeekValue -  1 (for Monday) through 7 (for Sunday)
765
     * Return the number of the week in the month of the weekday specified.
766
     * @param  string $dateTimestamp
767
     * @param  string $dayOfWeekValue
768
     * @return int
769
     */
770
    public function weekdayNumberOfMonth($dateTimestamp, $dayOfWeekValue)
771
    {
772
        $cut = substr($dateTimestamp, 0, 8);
773
        $daylen = 86400;
774
        $timestamp = strtotime($dateTimestamp);
775
        $first = strtotime($cut.'01');
776
        $elapsed = (($timestamp - $first) / $daylen) + 1;
777
        $i = 1;
778
        $weeks = 0;
779
        for ($i == 1; $i <= $elapsed; $i++) {
780
            $dayfind = $cut.(strlen($i) < 2 ? '0'.$i : $i);
781
            $daytimestamp = strtotime($dayfind);
782
            $day = strtolower(date('N', $daytimestamp));
783
            if ($day == strtolower($dayOfWeekValue)) {
784
                $weeks++;
785
            }
786
        }
787
        if ($weeks == 0) {
788
            $weeks++;
789
        }
790
791
        return $weeks;
792
    }
793
794
    /***************************************************************************/
795
796
    /**
797
     * GET number of week from the end of the month - https://stackoverflow.com/questions/5853380/php-get-number-of-week-for-month
798
     * Week of the month = Week of the year - Week of the year of first day of month + 1.
799
     * Return the number of the week in the month of the day specified
800
     * $when - unix timestramp of the date specified.
801
     *
802
     * @param  string $when
803
     * @return int
804
     */
805
    public function weekOfMonthFromTheEnd($when = null)
806
    {
807
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
808
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
809
        $dayDifference = $lastDayOfMonth - $numberOfDayOfTheMonth;
810
811
        switch (true) {
812
            case $dayDifference < 7:
813
                $weekFromTheEnd = 1;
814
                break;
815
816
            case $dayDifference < 14:
817
                $weekFromTheEnd = 2;
818
                break;
819
820
            case $dayDifference < 21:
821
                $weekFromTheEnd = 3;
822
                break;
823
824
            case $dayDifference < 28:
825
                $weekFromTheEnd = 4;
826
                break;
827
828
            default:
829
                $weekFromTheEnd = 5;
830
                break;
831
        }
832
833
        return $weekFromTheEnd;
834
    }
835
836
    /***************************************************************************/
837
838
    /**
839
     * GET number of day from the end of the month.
840
     * $when - unix timestramp of the date specified
841
     * Return the number of day of the month from end.
842
     *
843
     * @param  string $when
844
     * @return int
845
     */
846
    public function dayOfMonthFromTheEnd($when = null)
847
    {
848
        $numberOfDayOfTheMonth = strftime('%e', $when); // Day of the month 1-31
849
        $lastDayOfMonth = strftime('%e', strtotime(date('Y-m-t', $when))); // the last day of the month of the specified date
850
        $dayDifference = $lastDayOfMonth - $numberOfDayOfTheMonth;
851
852
        return $dayDifference;
853
    }
854
855
    /***************************************************************************/
856
857
    /**
858
     * GET the ordinal indicator - for the day of the month.
859
     * Return the ordinal indicator (st, nd, rd, th).
860
     * @param  int $number
861
     * @return string
862
     */
863
    public function getOrdinalIndicator($number)
864
    {
865
        switch ($number) {
866
            case  1:
867
                $ret = 'st';
868
                break;
869
            case  2:
870
                $ret = 'nd';
871
                break;
872
            case  3:
873
                $ret = 'rd';
874
                break;
875
            default:
876
                $ret = 'th';
877
                break;
878
        }
879
880
        return $ret;
881
    }
882
883
    /***************************************************************************/
884
885
    /**
886
     * Decode the event repeat_weekly_on field - used in event.show.
887
     * Return a string like "Monday".
888
     *
889
     * @param  string $repeatWeeklyOn
890
     * @return string
891
     */
892
    public function decodeRepeatWeeklyOn($repeatWeeklyOn)
893
    {
894
        $weekdayArray = ['', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
895
        $ret = $weekdayArray[$repeatWeeklyOn];
896
897
        return $ret;
898
    }
899
900
    /***************************************************************************/
901
902
    /**
903
     * Decode the event on_monthly_kind field - used in event.show.
904
     * Return a string like "the 4th to last Thursday of the month".
905
     *
906
     * @param  string $onMonthlyKindCode
907
     * @return string
908
     */
909
    public function decodeOnMonthlyKind($onMonthlyKindCode)
910
    {
911
        $onMonthlyKindCodeArray = explode('|', $onMonthlyKindCode);
912
        $weekDays = ['', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
913
914
        //dd($onMonthlyKindCodeArray);
915
        switch ($onMonthlyKindCodeArray[0]) {
916 View Code Duplication
            case '0':  // 0|7 eg. the 7th day of the month
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
917
                $dayNumber = $onMonthlyKindCodeArray[1];
918
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
919
920
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
921
                $format = 'the %s day of the month';
922
                $ret = sprintf($format, $dayNumberOrdinal);
923
                break;
924 View Code Duplication
            case '1':  // 1|2|4 eg. the 2nd Thursday of the month
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
925
                $dayNumber = $onMonthlyKindCodeArray[1];
926
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
927
928
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
929
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
930
                $format = 'the %s %s of the month';
931
                $ret = sprintf($format, $dayNumberOrdinal, $weekDay);
932
                break;
933 View Code Duplication
            case '2': // 2|20 eg. the 21th to last day of the month
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
934
                $dayNumber = $onMonthlyKindCodeArray[1] + 1;
935
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
936
937
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
938
                $format = 'the %s to last day of the month';
939
                $ret = sprintf($format, $dayNumberOrdinal);
940
                break;
941 View Code Duplication
            case '3': // 3|3|4 eg. the 4th to last Thursday of the month
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
942
                $dayNumber = $onMonthlyKindCodeArray[1] + 1;
943
                $ordinalIndicator = $this->getOrdinalIndicator($dayNumber);
944
945
                $dayNumberOrdinal = $dayNumber.$ordinalIndicator;
946
                $weekDay = $weekDays[$onMonthlyKindCodeArray[2]]; // Monday, Tuesday, Wednesday
947
                $format = 'the %s to last %s of the month';
948
                $ret = sprintf($format, $dayNumberOrdinal, $weekDay);
949
                break;
950
        }
951
952
        return $ret;
0 ignored issues
show
Bug introduced by
The variable $ret does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
953
    }
954
955
    // **********************************************************************
956
957
    /**
958
     * Save/Update the record on DB.
959
     *
960
     * @param  \Illuminate\Http\Request $request
961
     * @param  \App\Event $event
962
     * @return string $ret - the ordinal indicator (st, nd, rd, th)
963
     */
964
    public function saveOnDb($request, $event)
965
    {
966
        $countries = Country::getCountries();
967
        $teachers = Teacher::pluck('name', 'id');
968
969
        $venue = DB::table('event_venues')
970
                ->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')
971
                ->where('event_venues.id', '=', $request->get('venue_id'))
972
                ->first();
973
974
        $event->title = $request->get('title');
975
        //$event->description = $request->get('description');
976
        $event->description = clean($request->get('description'));
977
        $event->created_by = \Auth::user()->id;
978
        if (! $event->slug) {
979
            $event->slug = Str::slug($event->title, '-').'-'.rand(100000, 1000000);
980
        }
981
        $event->category_id = $request->get('category_id');
982
        $event->venue_id = $request->get('venue_id');
983
        $event->image = $request->get('image');
984
        $event->contact_email = $request->get('contact_email');
985
        $event->website_event_link = $request->get('website_event_link');
986
        $event->facebook_event_link = $request->get('facebook_event_link');
987
        $event->status = $request->get('status');
988
        $event->on_monthly_kind = $request->get('on_monthly_kind');
989
990
        // Event teaser image upload
991
        //dd($request->file('image'));
992
        if ($request->file('image')) {
993
            $imageFile = $request->file('image');
994
            $imageName = time().'.'.'jpg';  //$imageName = $teaserImageFile->hashName();
995
            $imageSubdir = 'events_teaser';
996
            $imageWidth = '968';
997
            $thumbWidth = '310';
998
999
            $this->uploadImageOnServer($imageFile, $imageName, $imageSubdir, $imageWidth, $thumbWidth);
1000
            $event->image = $imageName;
1001
        } else {
1002
            $event->image = $request->get('image');
1003
        }
1004
1005
        // Support columns for homepage search (we need this to show events in HP with less use of resources)
1006
        $event->sc_country_id = $venue->country_id;
1007
        $event->sc_country_name = $countries[$venue->country_id];
1008
        $event->sc_city_name = $venue->city;
1009
        $event->sc_venue_name = $venue->venue_name;
1010
        $event->sc_teachers_id = json_encode(explode(',', $request->get('multiple_teachers')));
1011
        $event->sc_continent_id = $venue->continent_id;
1012
1013
        // Multiple teachers - populate support column field
1014
        if ($request->get('multiple_teachers')) {
1015
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
1016
            $i = 0;
1017
            $len = count($multiple_teachers); // to put "," to all items except the last
1018
            $event->sc_teachers_names = '';
1019
            foreach ($multiple_teachers as $key => $teacher_id) {
1020
                $event->sc_teachers_names .= $teachers[$teacher_id];
1021
1022
                if ($i != $len - 1) {  // not last
1023
                    $event->sc_teachers_names .= ', ';
1024
                }
1025
                $i++;
1026
            }
1027
        } else {
1028
            $event->sc_teachers_names = '';
1029
        }
1030
1031
        // Set the Event attributes about repeating (repeat until field and multiple days)
1032
        $event = $this->setEventRepeatFields($request, $event);
1033
1034
        // Save event and repetitions
1035
        $event->save();
1036
        $this->saveEventRepetitions($request, $event);
1037
1038
        // Update multi relationships with teachers and organizers tables.
1039
        if ($request->get('multiple_teachers')) {
1040
            $multiple_teachers = explode(',', $request->get('multiple_teachers'));
1041
            $event->teachers()->sync($multiple_teachers);
1042
        } else {
1043
            $event->teachers()->sync([]);
1044
        }
1045
        if ($request->get('multiple_organizers')) {
1046
            $multiple_organizers = explode(',', $request->get('multiple_organizers'));
1047
            $event->organizers()->sync($multiple_organizers);
1048
        } else {
1049
            $event->organizers()->sync([]);
1050
        }
1051
    }
1052
1053
    /***********************************************************************/
1054
1055
    /**
1056
     * Get creator email.
1057
     *
1058
     * @param  int $created_by
1059
     * @return \App\User
1060
     */
1061
    public function getCreatorEmail($created_by)
1062
    {
1063
        $creatorEmail = DB::table('users')  // Used to send the Report misuse (not in english)
1064
                ->select('email')
1065
                ->where('id', $created_by)
1066
                ->first();
1067
1068
        $ret = $creatorEmail->email;
1069
1070
        return $ret;
1071
    }
1072
1073
    /***************************************************************************/
1074
1075
    /**
1076
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx).
1077
     *
1078
     * @param  string  $slug
1079
     * @return \Illuminate\Http\Response
1080
     */
1081
    public function eventBySlug($slug)
1082
    {
1083
        $event = Event::where('slug', $slug)->first();
1084
1085
        $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
1086
1087
        //dd($event);
1088
        return $this->show($event, $firstRpDates);
1089
    }
1090
1091
    /***************************************************************************/
1092
1093
    /**
1094
     * Return the event by SLUG. (eg. http://websitename.com/event/xxxx/300).
1095
     * @param  string $slug
1096
     * @param  int $repetitionId
1097
     * @return \Illuminate\Http\Response
1098
     */
1099
    public function eventBySlugAndRepetition($slug, $repetitionId)
1100
    {
1101
        $event = Event::where('slug', $slug)->first();
1102
        $firstRpDates = Event::getFirstEventRpDatesByRepetitionId($repetitionId);
1103
1104
        /*$firstRpDates = DB::table('event_repetitions')
1105
                            ->select('start_repeat','end_repeat')
1106
                            ->where('id',$repetitionId)
1107
                            ->first();*/
1108
1109
        // If not found get the first repetion of the event in the future.
1110
        if (! $firstRpDates) {
1111
            $firstRpDates = Event::getFirstEventRpDatesByEventId($event->id);
1112
        }
1113
1114
        return $this->show($event, $firstRpDates);
1115
    }
1116
1117
    /***************************************************************************/
1118
1119
    /**
1120
     * Return the Event validator with all the defined constraint.
1121
     * @param  \Illuminate\Http\Request  $request
1122
     * @return \Illuminate\Http\Response
1123
     */
1124
    public function eventsValidator($request)
1125
    {
1126
        $rules = [
1127
            'title' => 'required',
1128
            'description' => 'required',
1129
            'category_id' => 'required',
1130
            'venue_id' => 'required',
1131
            'startDate' => 'required',
1132
            'endDate' => 'required',
1133
            'repeat_until' => Rule::requiredIf($request->repeat_type > 1),
1134
            'repeat_weekly_on_day' => Rule::requiredIf($request->repeat_type == 2),
1135
            'on_monthly_kind' => Rule::requiredIf($request->repeat_type == 3),
1136
            'contact_email' => 'nullable|email',
1137
            'facebook_event_link' => 'nullable|url',
1138
            'website_event_link' => 'nullable|url',
1139
            // 'image' => 'nullable|image|mimes:jpeg,jpg,png|max:3000', // BUG create problems to validate on edit. Fix this after the rollout
1140
        ];
1141
        if ($request->hasFile('image')) {
1142
            $rules['image'] = 'nullable|image|mimes:jpeg,jpg,png|max:5000';
1143
        }
1144
1145
        $messages = [
1146
            'repeat_weekly_on_day[].required' => 'Please specify which day of the week is repeting the event.',
1147
            'on_monthly_kind.required' => 'Please specify the kind of monthly repetion',
1148
            'endDate.same' => 'If the event is repetitive the start date and end date must match',
1149
            'facebook_event_link.url' => 'The facebook link is invalid. It should start with https://',
1150
            'website_event_link.url' => 'The website link is invalid. It should start with https://',
1151
            'image.max' => 'The maximum image size is 5MB. If you need to resize it you can use: www.simpleimageresizer.com',
1152
        ];
1153
1154
        $validator = Validator::make($request->all(), $rules, $messages);
1155
1156
        // End date and start date must match if the event is repetitive
1157
        $validator->sometimes('endDate', 'same:startDate', function ($input) {
1158
            return $input->repeat_type > 1;
1159
        });
1160
1161
        return $validator;
1162
    }
1163
}
1164