Passed
Push — master ( 04da28...e05cb1 )
by Davide
49:29 queued 11:18
created

Event   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 288
Duplicated Lines 0 %

Test Coverage

Coverage 97.27%

Importance

Changes 12
Bugs 2 Features 1
Metric Value
wmc 20
eloc 127
c 12
b 2
f 1
dl 0
loc 288
ccs 107
cts 110
cp 0.9727
rs 10

8 Methods

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

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