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', 60); |
|
|
|
|
22
|
|
|
$ipAddress = $ipAddress ?? ''; |
23
|
|
|
|
24
|
|
|
$post = Post::findOrFail($postId); |
25
|
|
|
$entityType = get_class($post); |
26
|
|
|
$entityId = $post->getKey(); |
27
|
|
|
$now = Carbon::now(); |
28
|
|
|
|
29
|
|
|
/** @var null|VisitorLog $existingView */ |
30
|
|
|
$existingView = VisitorLog::query() |
31
|
|
|
->where('viewable_id', '=', $entityId) |
32
|
|
|
->where('viewable_type', '=', $entityType) |
33
|
|
|
->where('ip_address', '=', $ipAddress) |
34
|
|
|
->first(); |
35
|
|
|
|
36
|
|
|
$expiredAt = $now->copy()->addMinutes($expirationMinutes); |
37
|
|
|
|
38
|
|
|
$visitorData = [ |
39
|
|
|
'user_agent' => $userAgent, |
40
|
|
|
'expired_at' => $expiredAt, |
41
|
|
|
]; |
42
|
|
|
|
43
|
|
|
if (!$existingView instanceof VisitorLog) { |
44
|
|
|
VisitorLog::create([ |
45
|
|
|
'viewable_id' => $entityId, |
46
|
|
|
'viewable_type' => $entityType, |
47
|
|
|
'ip_address' => $ipAddress, |
48
|
|
|
] + $visitorData); |
49
|
|
|
|
50
|
|
|
$post->increment('views'); |
51
|
|
|
} elseif ($now->isAfter($existingView->expired_at)) { |
52
|
|
|
$existingView->update($visitorData); |
53
|
|
|
$post->increment('views'); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $post->refresh(); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.