Passed
Push — master ( 0f5c8a...e02280 )
by Davide
38:43
created

Event::getActiveEventsMapGeoJSON()   A

Complexity

Conditions 5
Paths 1

Size

Total Lines 56
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 5.0008

Importance

Changes 11
Bugs 4 Features 0
Metric Value
eloc 33
c 11
b 4
f 0
dl 0
loc 56
ccs 30
cts 31
cp 0.9677
rs 9.0808
cc 5
nc 1
nop 0
crap 5.0008

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace DavideCasiraghi\LaravelEventsCalendar\Models;
4
5
use Carbon\Carbon;
6
use DavideCasiraghi\LaravelEventsCalendar\Facades\LaravelEventsCalendar;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Support\Facades\Cache;
9
10
class Event extends Model
11
{
12
    /***************************************************************************/
13
    /**
14
     * The table associated with the model.
15
     *
16
     * @var string
17
     */
18
    protected $table = 'events';
19
20
    /***************************************************************************/
21
22
    protected $fillable = [
23
        'title',
24
        'description',
25
        'organized_by',
26
        'category_id',
27
        'venue_id',
28
        'image',
29
        'facebook_event_link',
30
        'website_event_link',
31
        'status',
32
        'repeat_type',
33
        'repeat_until',
34
        'repeat_weekly_on',
35
        'repeat_monthly_on',
36
        'on_monthly_kind',
37
        'multiple_dates',
38
    ];
39
40
    /***************************************************************************/
41
42
    /**
43
     * Get the user that owns the event. eg. $event->user.
44
     */
45
    public function user()
46
    {
47
        return $this->belongsTo('\Illuminate\Foundation\Auth\User', 'created_by');
48
    }
49
50
    /***************************************************************************/
51
52
    /**
53
     * Get the teachers for the event.
54
     */
55 31
    public function teachers()
56
    {
57 31
        return $this->belongsToMany('DavideCasiraghi\LaravelEventsCalendar\Models\Teacher', 'event_has_teachers', 'event_id', 'teacher_id');
58
    }
59
60
    /***************************************************************************/
61
62
    /**
63
     * Get the organizers for the event.
64
     */
65 31
    public function organizers()
66
    {
67 31
        return $this->belongsToMany('DavideCasiraghi\LaravelEventsCalendar\Models\Organizer', 'event_has_organizers', 'event_id', 'organizer_id');
68
    }
69
70
    /***************************************************************************/
71
72
    /**
73
     * Get the organizers for the event.
74
     */
75 1
    public function eventRepetitions()
76
    {
77 1
        return $this->hasMany('DavideCasiraghi\LaravelEventsCalendar\Models\EventRepetition', 'event_id');
78
    }
79
80
    /***************************************************************************/
81
82
    /**
83
     * Return an array with active events datas.
84
     *
85
     * @return array
86
     */
87 2
    public static function getActiveEvents()
88
    {
89 2
        $seconds = 86400; // One day (this cache tag get invalidates also on event save)
90
91
        $ret = Cache::remember('active_events', $seconds, function () {
92 2
            date_default_timezone_set('Europe/Rome');
93 2
            $searchStartDate = date('Y-m-d', time());
94 2
            $lastestEventsRepetitionsQuery = EventRepetition::getLastestEventsRepetitionsQuery($searchStartDate, null);
95
96
            return self::
97 2
                    select('title', 'countries.name AS country_name', 'countries.id AS country_id', 'countries.continent_id AS continent_id', 'event_venues.city AS city', 'events.repeat_until', 'events.category_id', 'events.created_by', 'events.repeat_type')
98 2
                    ->join('event_venues', 'event_venues.id', '=', 'events.venue_id')
99 2
                    ->join('countries', 'countries.id', '=', 'event_venues.country_id')
100
                    ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
101 2
                        $join->on('events.id', '=', 'event_repetitions.event_id');
102 2
                    })
103 2
                    ->get();
104
105
            /* EVERY TIME THIS QUERY CHANGE REMEMBER TO FLUSH THE CACHE
106
            (php artisan cache:clear) */
107 2
        });
108
109 2
        return $ret;
110
    }
111
112
    /***************************************************************************/
113
114
    /**
115
     * Return the active events based on the search keys provided.
116
     *
117
     * @param array $filters
118
     * @param int $itemPerPage
119
     * @return \DavideCasiraghi\LaravelEventsCalendar\Models\Event
120
     */
121
    //$keywords, $category, $city, $country, $continent, $teacher, $venue, $startDate, $endDate,
122 2
    public static function getEvents(array $filters, $itemPerPage)
123
    {
124 2
        if (! array_key_exists('startDate', $filters) || ! $filters['startDate']) {
125 2
            $filters['startDate'] = Carbon::now()->format('Y-m-d');
126
        }
127
128
        // Sub-Query Joins - https://laravel.com/docs/5.7/queries
129 2
        $lastestEventsRepetitionsQuery = EventRepetition::getLastestEventsRepetitionsQuery($filters['startDate'], $filters['endDate']);
130
131
        // Retrieve the events that correspond to the selected filters
132 2
        if ($filters['keywords'] || $filters['category'] || $filters['city'] || $filters['country'] || $filters['region'] || $filters['continent'] || $filters['teacher'] || $filters['venue'] || $filters['endDate']) {
133
134
        //$start = microtime(true);
135
            //DB::enableQueryLog();
136
            $ret = self::
137 1
                    select('events.title', 'events.category_id', 'events.slug', 'event_venues.name as venue_name', 'event_venues.city as city_name', 'countries.name as country_name', 'events.sc_teachers_names', 'event_repetitions.start_repeat', 'event_repetitions.end_repeat')
138
                    ->when($filters['keywords'], function ($query, $keywords) {
139 1
                        return $query->where('title', 'like', '%'.$keywords.'%');
140 1
                    })
141
                    ->when($filters['category'], function ($query, $category) {
142 1
                        return $query->where('category_id', '=', $category);
143 1
                    })
144
                    ->when($filters['teacher'], function ($query, $teacher) {
145
                        return $query->whereRaw('json_contains(sc_teachers_id, \'["'.$teacher.'"]\')');
146 1
                    })
147
                    ->when($filters['country'], function ($query, $country) {
148 1
                        return $query->where('event_venues.country_id', '=', $country);
149 1
                    })
150
                    ->when($filters['region'], function ($query, $region) {
151 1
                        return $query->where('event_venues.region_id', '=', $region);
152 1
                    })
153
                    ->when($filters['continent'], function ($query, $continent) {
154 1
                        return $query->where('event_venues.continent_id', '=', $continent);  //sc_continent_id
155 1
                    })
156
                    ->when($filters['city'], function ($query, $city) {
157 1
                        return $query->where('event_venues.city', 'like', '%'.$city.'%');
158 1
                    })
159
                    ->when($filters['venue'], function ($query, $venue) {
160 1
                        return $query->where('event_venues.name', 'like', '%'.$venue.'%');
161 1
                    })
162
                    ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
163 1
                        $join->on('events.id', '=', 'event_repetitions.event_id');
164 1
                    })
165
166 1
                    ->leftJoin('event_venues', 'events.venue_id', '=', 'event_venues.id')
167 1
                    ->leftJoin('continents', 'event_venues.continent_id', '=', 'continents.id')
168 1
                    ->leftJoin('countries', 'event_venues.country_id', '=', 'countries.id')
169 1
                    ->leftJoin('regions', 'event_venues.region_id', '=', 'regions.id')
170
171 1
                    ->orderBy('event_repetitions.start_repeat', 'asc')
172 1
                    ->paginate($itemPerPage);
173
        //dd(DB::getQueryLog());
174
175
        //$time = microtime(true) - $start;
176
        //dd($time);
177
        }
178
        // If no filter selected retrieve all the events
179
        else {
180
            $ret = self::
181 1
                        select('events.title', 'events.category_id', 'events.slug', 'event_venues.name as venue_name', 'event_venues.city as city_name', 'countries.name as country_name', 'events.sc_teachers_names', 'event_repetitions.start_repeat', 'event_repetitions.end_repeat')
182
                        ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
183 1
                            $join->on('events.id', '=', 'event_repetitions.event_id');
184 1
                        })
185 1
                        ->leftJoin('event_venues', 'events.venue_id', '=', 'event_venues.id')
186 1
                        ->leftJoin('continents', 'event_venues.continent_id', '=', 'continents.id')
187 1
                        ->leftJoin('countries', 'event_venues.country_id', '=', 'countries.id')
188 1
                        ->leftJoin('regions', 'event_venues.region_id', '=', 'regions.id')
189
190 1
                        ->orderBy('event_repetitions.start_repeat', 'asc')
191 1
                        ->paginate($itemPerPage);
192
193
            // It works, but I don't use it now to develop
194
                /*$cacheExpireMinutes = 15;
195
                $events = Cache::remember('all_events', $cacheExpireTime, function () {
196
                    return DB::table('events')->latest()->paginate(20);
197
                });*/
198
        }
199
200 2
        return $ret;
201
    }
202
203
    /***************************************************************************/
204
205
    /**
206
     * Return a cached JSON with active events map markers.
207
     *
208
     * @return array
209
     */
210 1
    public static function getActiveEventsMapGeoJSON()
211
    {
212 1
        $cacheExpireMinutes = 1440; // Set the duration time of the cache (1 day - 1440 minutes) - this cache tag get invalidates also on event save
213
214
        $eventsMapGeoJSONArrayCached = Cache::remember('active_events_map_markers', $cacheExpireMinutes, function () {
215 1
            $eventsData = self::getActiveEventsMapMarkersDataFromDb();
216 1
            $eventsMapGeoJSONArray = [];
217 1
            foreach ($eventsData as $key => $eventData) {
218
                //dd($eventData);
219
220
                // Generates event link
221 1
                $nextEventRepetitionId = EventRepetition::getFirstEventRpIdByEventId($eventData->id);
222 1
                $eventLinkformat = 'event/%s/%s';   //event/{{$event->slug}}/{{$event->rp_id}}
223 1
                $eventLink = sprintf($eventLinkformat, $eventData->event_slug, $nextEventRepetitionId);
224
225
                // Get Next event occurrence date
226 1
                $nextDateOccurence = EventRepetition::getFirstEventRpDatesByEventId($eventData->id);
227 1
                if (! empty($nextDateOccurence)) {
228 1
                    $nextDate = Carbon::parse($nextDateOccurence->start_repeat)->isoFormat('D MMM YYYY');
229
                } else {
230
                    $nextDate = '';
231
                }
232
233 1
                $address = (! empty($eventData->address)) ? ', '.$eventData->address : '';
234 1
                $city = (! empty($eventData->city)) ? $eventData->city : '';
235
236
                // Add one element to the Geo array
237 1
                $eventsMapGeoJSONArray[] = [
238 1
                    'type' => 'Feature',
239 1
                    'id' => $eventData->id,
240
                    'properties' => [
241 1
                        'Title' => $eventData->title,
242 1
                        'Category' => EventCategory::getCategoryName($eventData->category_id),
243 1
                        'VenueName' => EventVenue::getVenueName($eventData->venue_id),
244 1
                        'City' => $city,
245 1
                        'Address' => $address,
246 1
                        'Link' => $eventLink,
247 1
                        'NextDate' => $nextDate,
248 1
                        'IconColor' => LaravelEventsCalendar::getMapMarkerIconColor($eventData->category_id),
0 ignored issues
show
Bug introduced by
The method getMapMarkerIconColor() 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

248
                        'IconColor' => LaravelEventsCalendar::/** @scrutinizer ignore-call */ getMapMarkerIconColor($eventData->category_id),
Loading history...
249
                    ],
250
                    'geometry' => [
251 1
                        'type' => 'Point',
252 1
                        'coordinates' => [$eventData->lng, $eventData->lat],
253
                    ],
254
                ];
255
            }
256
257
            /* EVERY TIME THIS CHANGE REMEMBER TO FLUSH THE CACHE
258
            (php artisan cache:clear) */
259
260 1
            return $eventsMapGeoJSONArray;
261 1
        });
262
263 1
        $ret = json_encode($eventsMapGeoJSONArrayCached);
264
265 1
        return $ret;
266
    }
267
268
    /***************************************************************************/
269
270
    /**
271
     * Return an array with active events map markers.
272
     *
273
     * @return array
274
     */
275 3
    public static function getActiveEventsMapMarkersDataFromDb()
276
    {
277 3
        $seconds = 86400; // One day (this cache tag get invalidates also on event save)
278
        
279
        $ret = Cache::remember('active_events_map_markers_data', $seconds, function () {
280 3
            date_default_timezone_set('Europe/Rome');
281 3
            $searchStartDate = Carbon::now()->format('Y-m-d');
282 3
            $lastestEventsRepetitionsQuery = EventRepetition::getLastestEventsRepetitionsQuery($searchStartDate, null);
283
            
284
            return self::
285 3
                    select('events.id AS id',
286 3
                    'events.title AS title',
287 3
                    'events.slug AS event_slug',
288 3
                    'event_venues.id AS venue_id',
289 3
                    'event_venues.city AS city',
290 3
                    'event_venues.address AS address',
291 3
                    'event_venues.lat AS lat',
292 3
                    'event_venues.lng AS lng',
293 3
                    'events.repeat_until',
294 3
                    'events.category_id',
295 3
                    'events.created_by',
296 3
                    'events.repeat_type'
297
                    )
298 3
            ->join('event_venues', 'event_venues.id', '=', 'events.venue_id')
299 3
            ->join('countries', 'countries.id', '=', 'event_venues.country_id')
300
            ->joinSub($lastestEventsRepetitionsQuery, 'event_repetitions', function ($join) {
301 3
                $join->on('events.id', '=', 'event_repetitions.event_id');
302 3
            })
303 3
            ->get();
304
305
            /* EVERY TIME THIS QUERY CHANGE REMEMBER TO FLUSH THE CACHE
306
            (php artisan cache:clear) */
307 3
        });
308
309 3
        return $ret;
310
    }
311
}
312