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

VisitorLogsService   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 15
Bugs 4 Features 1
Metric Value
eloc 16
dl 0
loc 40
rs 10
c 15
b 4
f 1
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A trackPostView() 0 30 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
use Illuminate\Database\Eloquent\ModelNotFoundException;
9
10
class VisitorLogsService
11
{
12
    /**
13
     * @param  int  $postId
14
     * @param  null|string  $ipAddress
15
     * @param  null|string  $userAgent
16
     *
17
     * @return Post
18
     * @throws ModelNotFoundException
19
     */
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
    }
51
}
52