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