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