EventRepository::getById()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace App\Repositories;
5
6
use App\Models\Event;
7
use App\Models\EventRepetition;
8
use Carbon\Carbon;
9
use Illuminate\Support\Collection;
10
use Illuminate\Support\Facades\Auth;
11
12
class EventRepository implements EventRepositoryInterface
13
{
14
    /**
15
     * Get all Events.
16
     *
17
     * @param int|null $recordsPerPage
18
     * @param array|null $searchParameters
19
     *
20
     * @return \App\Models\Event[]|\Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Collection
21
     */
22 1
    public function getAll(int $recordsPerPage = null, array $searchParameters = null)
23
    {
24 1
        // Upcoming events are shown first
25
        $query = Event::select('events.*', 'event_repetitions.start_repeat', 'event_repetitions.end_repeat')
26 1
            ->with(['category', 'teachers', 'venue', 'venue.country'])
27
            ->leftJoin('event_repetitions', 'events.id', '=', 'event_repetitions.event_id')
28
            ->orderBy('event_repetitions.start_repeat');
29
30
        if (!is_null($searchParameters)) {
31
            if (!empty($searchParameters['title'])) {
32
                $query->where(
33
                    'title',
34
                    'like',
35
                    '%' . $searchParameters['title'] . '%'
36
                );
37
            }
38
            if (!empty($searchParameters['eventCategoryId'])) {
39
                $query->where('event_category_id', $searchParameters['eventCategoryId']);
40
            }
41
            if (!empty($searchParameters['startDate'])) {
42
                $startDate = Carbon::createFromFormat(
43
                    'd/m/Y',
44
                    $searchParameters['startDate']
45
                );
46
                $query->where('start_repeat', '>=', $startDate);
47
            }
48
            if (!empty($searchParameters['endDate'])) {
49
                $endDate = Carbon::createFromFormat(
50
                    'd/m/Y',
51
                    $searchParameters['endDate']
52
                );
53
                $query->where('end_repeat', '<=', $endDate);
54
            }
55
            if (!is_null($searchParameters['is_published'])) {
56 1
                $query->where('is_published', $searchParameters['is_published']);
57 1
            }
58
        }
59
60
        if ($recordsPerPage) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $recordsPerPage of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
61
            $results = $query->paginate($recordsPerPage)->withQueryString();
62 1
        } else {
63
            $results = $query->get();
64
        }
65
66
        return $results;
67
    }
68
69
    /**
70
     * Get Event by id
71 2
     *
72
     * @param int $eventId
73 2
     * @return Event
74
     */
75
    public function getById(int $eventId): Event
76
    {
77
        return Event::findOrFail($eventId);
78
    }
79
80
    /**
81
     * Get Event by slug
82
     *
83
     * @param  string  $eventSlug
84 4
     * @return Event
85
     */
86 4
    public function getBySlug(string $eventSlug): Event
87 4
    {
88
        return Event::where('slug', $eventSlug)->first();
89
    }
90 4
91
    /**
92 4
     * Return the list of the expiring repetitive events (the 7th day from now).
93
     * Consider just Weekly(2) and Monthly(3) events.
94 4
     * It returns just the events expiring the 7th day from now, not the 6th day or less.
95
     *
96 4
     * @return Collection
97
     */
98 4
    public function getRepetitiveExpiringInOneWeek(): Collection
99
    {
100
        $query = Event::orderBy('title', 'desc');
101
        $query->where('repeat_until', '<=', Carbon::today()->addWeek());
102
        $query->where('repeat_until', '>', Carbon::now()->addWeek()->subDay());
103
        $query->whereIn('repeat_type', [2, 3]); // Weekly(2), Monthly(3)
104
105
        return $query->get();
106
    }
107
108
    /**
109 1
     * Store Event
110
     *
111 1
     * @param array $data
112 1
     *
113
     * @return Event
114 1
     * @throws \Spatie\ModelStatus\Exceptions\InvalidStatus
115
     */
116 1
    public function store(array $data): Event
117
    {
118 1
        $event = new Event();
119 1
        $event = self::assignDataAttributes($event, $data);
0 ignored issues
show
Bug Best Practice introduced by
The method App\Repositories\EventRe...:assignDataAttributes() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

119
        /** @scrutinizer ignore-call */ 
120
        $event = self::assignDataAttributes($event, $data);
Loading history...
120 1
121
        // Creator - Logged user id or 1 for factories
122
        $event->user_id = !is_null(Auth::id()) ? Auth::id() : 1;
0 ignored issues
show
Bug introduced by
The property user_id does not exist on App\Models\Event. Did you mean user?
Loading history...
123 1
        // Default 'published'
124
        $event->is_published = 1;
125
126
        $event->save();
127
128
        self::syncManyToMany($event, $data);
0 ignored issues
show
Bug Best Practice introduced by
The method App\Repositories\EventRepository::syncManyToMany() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

128
        self::/** @scrutinizer ignore-call */ 
129
              syncManyToMany($event, $data);
Loading history...
129
130
        return $event->fresh();
131
    }
132 1
133
    /**
134 1
     * Update Event
135 1
     *
136
     * @param array $data
137
     * @param int $id
138
     *
139
     * @return Event
140
     */
141
    public function update(array $data, int $id): Event
142
    {
143
        $event = $this->getById($id);
144
        $event = self::assignDataAttributes($event, $data);
0 ignored issues
show
Bug Best Practice introduced by
The method App\Repositories\EventRe...:assignDataAttributes() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

144
        /** @scrutinizer ignore-call */ 
145
        $event = self::assignDataAttributes($event, $data);
Loading history...
145 5
146
        $event->update();
147 5
148 5
        self::syncManyToMany($event, $data);
0 ignored issues
show
Bug Best Practice introduced by
The method App\Repositories\EventRepository::syncManyToMany() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

148
        self::/** @scrutinizer ignore-call */ 
149
              syncManyToMany($event, $data);
Loading history...
149
150 5
        return $event;
151 5
    }
152 5
153 5
    /**
154 5
     * Delete Event
155 5
     *
156
     * @param int $id
157 5
     * @return void
158 5
     */
159 3
    public function delete(int $id): void
160 3
    {
161 2
        Event::destroy($id);
162 1
    }
163 1
164
    /**
165 1
     * Assign the attributes of the data array to the object
166 1
     *
167 1
     * @param \App\Models\Event $event
168 1
     * @param array $data
169 1
     *
170 1
     * @return \App\Models\Event
171
     */
172
    public function assignDataAttributes(Event $event, array $data): Event
173
    {
174
        $event->event_category_id = $data['event_category_id'];
0 ignored issues
show
Bug introduced by
The property event_category_id does not exist on App\Models\Event. Did you mean category?
Loading history...
175
        $event->venue_id = $data['venue_id'];
0 ignored issues
show
Bug introduced by
The property venue_id does not exist on App\Models\Event. Did you mean venue?
Loading history...
176
177 5
        $event->title = $data['title'];
178
        $event->description = $data['description'];
179
        $event->contact_email = $data['contact_email'];
180
        $event->website_event_link = $data['website_event_link'];
181
        $event->facebook_event_link = $data['facebook_event_link'];
182
        $event->repeat_type = $data['repeat_type'];
183
        $event->is_published = (isset($data['is_published'])) ? 1 : 0;
184
185
        switch ($data['repeat_type']) {
186
            case 1: // No Repeat
187
                $event->repeat_until = null;
188
                break;
189 5
            case 2: // Weekly
190
                if (array_key_exists('repeat_weekly_on', $data)) {
191 5
                    $event->repeat_weekly_on = implode(',', array_keys($data['repeat_weekly_on']));
192 5
                }
193 5
                $event->repeat_until = Carbon::createFromFormat('d/m/Y', $data['repeat_until']);
194
                break;
195
            case 3: // Monthly
196
                $event->on_monthly_kind = $data['on_monthly_kind'] ?? null;
197
                $event->repeat_until = Carbon::createFromFormat('d/m/Y', $data['repeat_until']);
198
                break;
199
            case 4: // Multiple days
200
                $event->multiple_dates = $data['multiple_dates'] ?? null;
201
                $event->repeat_until = null;
202
                break;
203
        }
204
205
        return $event;
206
    }
207
208
209
    /**
210
     * Sync the many-to-many relatioships
211
     *
212
     * @param \App\Models\Event $event
213
     * @param array $data
214
     *
215
     * @return void
216
     */
217
    public function syncManyToMany(Event $event, array $data): void
218
    {
219
        $event->teachers()->sync($data['teacher_ids'] ?? null);
220
        $event->organizers()->sync($data['organizer_ids'] ?? null);
221
    }
222
223
}
224