Conditions | 4 |
Paths | 4 |
Total Lines | 27 |
Code Lines | 14 |
Lines | 0 |
Ratio | 0 % |
Changes | 9 | ||
Bugs | 2 | Features | 0 |
1 | <?php |
||
19 | public function trackPostView( |
||
20 | int $postId, |
||
21 | ?string $ipAddress, |
||
22 | ?string $userAgent = null |
||
23 | ): Model|VisitorLog { |
||
24 | $now = Carbon::now(); |
||
25 | $post = Post::query()->lockForUpdate()->findOrFail($postId); |
||
26 | |||
27 | $visitorLog = VisitorLog::query()->firstOrNew([ |
||
28 | 'viewable_id' => $post->getKey(), |
||
29 | 'viewable_type' => Post::class, |
||
30 | 'ip_address' => $ipAddress ?: '', |
||
31 | ]); |
||
32 | |||
33 | $shouldCountView = !$visitorLog->exists || $now->isAfter($visitorLog->expired_at); |
||
34 | |||
35 | if ($shouldCountView) { |
||
36 | $visitorLog->fill([ |
||
37 | 'user_agent' => $userAgent, |
||
38 | 'expired_at' => $now->copy()->addMinutes((int) config('blog-core.view_throttle_minutes')), |
||
39 | ]); |
||
40 | $visitorLog->save(); |
||
41 | |||
42 | Post::where('id', $postId)->increment('views'); |
||
43 | } |
||
44 | |||
45 | return $visitorLog; |
||
46 | } |
||
48 |