| Conditions | 4 |
| Paths | 4 |
| Total Lines | 27 |
| Code Lines | 16 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 7 | ||
| Bugs | 1 | Features | 0 |
| 1 | <?php |
||
| 19 | public function trackPostView(int $postId, ?string $ipAddress, ?string $userAgent = null): Post |
||
| 20 | { |
||
| 21 | $expirationMinutes = (int) config('blog-core.expiration_view_time'); |
||
| 22 | $ipAddress = $ipAddress ?: ''; |
||
| 23 | $now = Carbon::now(); |
||
| 24 | |||
| 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($expirationMinutes), |
||
| 39 | ]); |
||
| 40 | $visitorLog->save(); |
||
| 41 | |||
| 42 | Post::where('id', $postId)->increment('views'); |
||
| 43 | } |
||
| 44 | |||
| 45 | return $post->refresh(); |
||
| 46 | } |
||
| 48 |