Passed
Pull Request — main (#69)
by Tan
03:00
created

VisitorLogsService   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 14
Bugs 4 Features 0
Metric Value
eloc 18
c 14
b 4
f 0
dl 0
loc 44
rs 10
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A trackPostView() 0 34 5
1
<?php
2
3
namespace CSlant\Blog\Api\Services;
4
5
use Carbon\Carbon;
6
use CSlant\Blog\Api\Enums\StatusEnum;
7
use CSlant\Blog\Api\Models\VisitorLog;
8
use CSlant\Blog\Core\Models\Post;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Database\Eloquent\ModelNotFoundException;
11
12
class VisitorLogsService
13
{
14
    /**
15
     * @param  int  $postId
16
     * @param  null|string  $ipAddress
17
     * @param  null|string  $userAgent
18
     *
19
     * @return Post
20
     * @throws ModelNotFoundException
21
     */
22
    public function trackPostView(
23
        int $postId,
24
        ?string $ipAddress,
25
        ?string $userAgent = null
26
    ): Post {
27
        $now = Carbon::now();
28
29
        /** @var Post $post */
30
        $post = Post::query()->lockForUpdate()->findOrFail($postId);
31
32
        if ($post->status !== StatusEnum::PUBLISHED->value) {
33
            return $post;
34
        }
35
36
        $visitorLog = VisitorLog::query()->firstOrNew([
37
            'viewable_id' => $post->getKey(),
38
            'viewable_type' => Post::class,
39
            'ip_address' => $ipAddress ?: '',
40
        ]);
41
42
        $shouldCountView = !$visitorLog->exists || $now->isAfter($visitorLog->expired_at ?? $now->copy()->subMinute());
43
44
        if ($shouldCountView) {
45
            $visitorLog->fill([
46
                'user_agent' => $userAgent,
47
                'expired_at' => $now->copy()->addMinutes((int) config('blog-core.view_throttle_minutes')),
48
            ]);
49
            $visitorLog->save();
50
51
            Post::where('id', $postId)->increment('views');
52
            $post->refresh();
53
        }
54
55
        return $post;
56
    }
57
}
58