Passed
Pull Request — main (#69)
by Tan
03:50 queued 59s
created

VisitorLogsService   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 7
Bugs 1 Features 0
Metric Value
eloc 17
c 7
b 1
f 0
dl 0
loc 37
rs 10
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A trackPostView() 0 27 4
1
<?php
2
3
namespace CSlant\Blog\Api\Services;
4
5
use Carbon\Carbon;
6
use CSlant\Blog\Api\Models\VisitorLog;
7
use CSlant\Blog\Core\Models\Post;
8
9
class VisitorLogsService
10
{
11
    /**
12
     * Track a view for a post by ID.
13
     *
14
     * @param int $postId The post ID
15
     * @param null|string $ipAddress The viewer's IP address
16
     * @param null|string $userAgent The viewer's user agent
17
     * @return Post The updated post
18
     */
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
    }
47
}
48