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