Passed
Pull Request — main (#69)
by
unknown
04:13 queued 44s
created

TrackPostView::handle()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 40
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 23
c 2
b 0
f 0
nc 7
nop 2
dl 0
loc 40
rs 9.2408
1
<?php
2
3
namespace CSlant\Blog\Api\Http\Middlewares;
4
5
use Carbon\Carbon;
6
use Closure;
7
use CSlant\Blog\Api\Models\PostView;
8
use CSlant\Blog\Core\Models\Post;
9
10
class TrackPostView
11
{
12
    public function handle($request, Closure $next)
13
    {
14
        $postId = $request->route('id');
15
        $ipAddress = $request->ip();
16
17
        $post = Post::find($postId);
18
        if (!$post) {
0 ignored issues
show
introduced by
$post is of type Illuminate\Database\Eloquent\Builder, thus it always evaluated to true.
Loading history...
19
            return $next($request);
20
        }
21
22
        $postView = PostView::where('post_id', $postId)
23
            ->where('ip_address', $ipAddress)
24
            ->first();
25
26
        $shouldIncrementView = false;
27
28
        if (!$postView) {
29
            // Access this post for the first time from this IP
30
            PostView::create([
31
                'post_id' => $postId,
32
                'ip_address' => $ipAddress,
33
                'time_check' => Carbon::now()->addHours(),
34
            ]);
35
            $shouldIncrementView = true;
36
        } else {
37
            // Check if field time_check is passed
38
            if (Carbon::now()->isAfter($postView->time_check)) {
0 ignored issues
show
Bug introduced by
The property time_check does not seem to exist on CSlant\Blog\Api\Models\PostView. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
39
                // Update the field time_check
40
                $postView->update([
41
                    'time_check' => Carbon::now()->addHours(),
42
                ]);
43
                $shouldIncrementView = true;
44
            }
45
        }
46
47
        if ($shouldIncrementView) {
48
            $post->increment('views');
49
        }
50
51
        return $next($request);
52
    }
53
}
54