Conditions | 5 |
Paths | 5 |
Total Lines | 34 |
Code Lines | 17 |
Lines | 0 |
Ratio | 0 % |
Changes | 11 | ||
Bugs | 4 | Features | 0 |
1 | <?php |
||
21 | public function trackPostView( |
||
22 | int $postId, |
||
23 | ?string $ipAddress, |
||
24 | ?string $userAgent = null |
||
25 | ): Post { |
||
26 | $now = Carbon::now(); |
||
27 | |||
28 | /** @var Post $post */ |
||
29 | $post = Post::query()->lockForUpdate()->findOrFail($postId); |
||
30 | |||
31 | if ($post->status !== StatusEnum::PUBLISHED->value) { |
||
32 | return $post; |
||
33 | } |
||
34 | |||
35 | $visitorLog = VisitorLog::query()->firstOrNew([ |
||
36 | 'viewable_id' => $post->getKey(), |
||
37 | 'viewable_type' => Post::class, |
||
38 | 'ip_address' => $ipAddress ?: '', |
||
39 | ]); |
||
40 | |||
41 | $shouldCountView = !$visitorLog->exists || $now->isAfter($visitorLog->expired_at ?? $now->copy()->subMinute()); |
||
42 | |||
43 | if ($shouldCountView) { |
||
44 | $visitorLog->fill([ |
||
45 | 'user_agent' => $userAgent, |
||
46 | 'expired_at' => $now->copy()->addMinutes((int) config('blog-core.view_throttle_minutes')), |
||
47 | ]); |
||
48 | $visitorLog->save(); |
||
49 | |||
50 | Post::where('id', $postId)->increment('views'); |
||
51 | $post->refresh(); |
||
52 | } |
||
53 | |||
54 | return $post; |
||
55 | } |
||
57 |