-
-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathActivityLogService.php
More file actions
251 lines (210 loc) · 6.35 KB
/
ActivityLogService.php
File metadata and controls
251 lines (210 loc) · 6.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php
namespace App\Services\Activity;
use App\Models\ActivityLog;
use App\Models\Server;
use App\Models\User;
use Closure;
use Filament\Facades\Filament;
use Illuminate\Contracts\Auth\Factory as AuthFactory;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Request;
use Throwable;
use Webmozart\Assert\Assert;
class ActivityLogService
{
protected ?ActivityLog $activity = null;
/** @var array<User> */
protected array $subjects = [];
public function __construct(
protected AuthFactory $manager,
protected ActivityLogTargetableService $targetable,
protected ConnectionInterface $connection
) {}
/**
* Sets the activity logger as having been caused by an anonymous
* user type.
*/
public function anonymous(): self
{
$this->getActivity()->actor_id = null;
$this->getActivity()->actor_type = null;
$this->getActivity()->setRelation('actor', null);
return $this;
}
/**
* Sets the action for this activity log.
*/
public function event(string $action): self
{
$this->getActivity()->event = $action;
return $this;
}
/**
* Set the description for this activity.
*/
public function description(?string $description): self
{
$this->getActivity()->description = $description;
return $this;
}
/**
* Sets the subject model instance.
*
* @template T extends \Illuminate\Database\Eloquent\Model|\Illuminate\Contracts\Auth\Authenticatable
*
* @param T|T[]|null $subjects
*/
public function subject(...$subjects): self
{
foreach ($subjects as $subject) {
if (is_null($subject)) {
continue;
}
foreach ($this->subjects as $entry) {
// If this subject is already tracked in our array of subjects just skip over
// it and move on to the next one in the list.
if ($entry->is($subject)) {
continue 2;
}
}
$this->subjects[] = $subject;
}
return $this;
}
/**
* Sets the actor model instance.
*/
public function actor(Model $actor): self
{
$this->getActivity()->actor()->associate($actor);
return $this;
}
/**
* Sets a custom property on the activity log instance.
*
* @param string|array<string, mixed> $key
* @param mixed $value
*/
public function property($key, $value = null): self
{
$properties = $this->getActivity()->properties;
$this->activity->properties = is_array($key)
? $properties->merge($key)
: $properties->put($key, $value);
return $this;
}
/**
* Attaches the instance request metadata to the activity log event.
*/
public function withRequestMetadata(): self
{
return $this->property([
'ip' => Request::getClientIp(),
'useragent' => Request::userAgent(),
]);
}
/**
* Logs an activity log entry with the set values and then returns the
* model instance to the caller. If there is an exception encountered while
* performing this action it will be logged to the disk but will not interrupt
* the code flow.
*/
public function log(?string $description = null): ActivityLog
{
$activity = $this->getActivity();
if (!is_null($description)) {
$activity->description = $description;
}
try {
return $this->save();
} catch (Throwable $exception) {
if (config('app.env') !== 'production') {
throw $exception;
}
logger()->error($exception);
}
return $activity;
}
/**
* Returns a cloned instance of the service allowing for the creation of a base
* activity log with the ability to change values on the fly without impact.
*/
public function clone(): self
{
return clone $this;
}
/**
* Executes the provided callback within the scope of a database transaction
* and will only save the activity log entry if everything else successfully
* settles.
*
* @throws Throwable
*/
public function transaction(Closure $callback): mixed
{
return $this->connection->transaction(function () use ($callback) {
$response = $callback($this);
$this->save();
return $response;
});
}
/**
* Resets the instance and clears out the log.
*/
public function reset(): void
{
$this->activity = null;
$this->subjects = [];
}
/**
* Returns the current activity log instance.
*/
protected function getActivity(): ActivityLog
{
if ($this->activity) {
return $this->activity;
}
$this->activity = new ActivityLog([
'ip' => Request::ip(),
'properties' => Collection::make([]),
'api_key_id' => $this->targetable->apiKeyId(),
]);
if ($subject = $this->targetable->subject()) {
$this->subject($subject);
} elseif ($tenant = Filament::getTenant()) {
if ($tenant instanceof Server) {
$this->subject($tenant);
}
}
if ($actor = $this->targetable->actor()) {
$this->actor($actor);
} elseif ($user = $this->manager->guard()->user()) {
$this->actor($user);
}
return $this->activity;
}
/**
* Saves the activity log instance and attaches all the subject models.
*
* @throws Throwable
*/
protected function save(): ActivityLog
{
Assert::notNull($this->activity);
$response = $this->connection->transaction(function () {
$this->activity->save();
foreach ($this->subjects as $subject) {
$this->activity->subjects()->forceCreate([
'subject_id' => $subject->getKey(),
'subject_type' => $subject->getMorphClass(),
]);
}
return $this->activity;
});
$this->activity = null;
$this->subjects = [];
return $response;
}
}