|
1
|
|
|
<?php |
|
2
|
|
|
namespace NwLaravel\ActivityLog\Handlers; |
|
3
|
|
|
|
|
4
|
|
|
use Illuminate\Http\Request; |
|
5
|
|
|
use Illuminate\Contracts\Auth\Authenticatable; |
|
6
|
|
|
use NwLaravel\ActivityLog\ActivityLog; |
|
7
|
|
|
use Carbon\Carbon; |
|
8
|
|
|
|
|
9
|
|
|
class DefaultHandler implements HandlerInterface |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var ActivityLog |
|
13
|
|
|
*/ |
|
14
|
|
|
protected $model; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Construct |
|
18
|
|
|
* |
|
19
|
|
|
* @param ActivityLog $model |
|
20
|
|
|
*/ |
|
21
|
2 |
|
public function __construct(ActivityLog $model) |
|
22
|
|
|
{ |
|
23
|
2 |
|
$this->model = $model; |
|
24
|
2 |
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Log activity |
|
28
|
|
|
* |
|
29
|
|
|
* @param string $action |
|
30
|
|
|
* @param string $description |
|
31
|
|
|
* @param \Eloquent $content |
|
32
|
|
|
* @param Authenticatable $user |
|
33
|
|
|
* @param Request $request |
|
34
|
|
|
* |
|
35
|
|
|
* @return bool |
|
36
|
|
|
*/ |
|
37
|
1 |
|
public function log($action, $description, $content = null, Authenticatable $user = null, Request $request = null) |
|
38
|
|
|
{ |
|
39
|
1 |
|
$user_id = null; |
|
40
|
1 |
|
$user_type = null; |
|
41
|
1 |
|
$user_name = null; |
|
42
|
1 |
|
if ($user) { |
|
43
|
1 |
|
$user_id = $user->getAuthIdentifier(); |
|
44
|
1 |
|
$user_type = get_class($user); |
|
45
|
1 |
|
$user_name = $user->getAuthIdentifierName(); |
|
46
|
1 |
|
} |
|
47
|
|
|
|
|
48
|
1 |
|
$content_type = is_object($content) ? get_class($content) : null; |
|
49
|
1 |
|
$content_id = is_object($content) ? $content->id : null; |
|
50
|
1 |
|
$ip_address = $request->ip(); |
|
|
|
|
|
|
51
|
|
|
|
|
52
|
1 |
|
return (bool) $this->model->create([ |
|
|
|
|
|
|
53
|
1 |
|
'action' => $action, |
|
54
|
1 |
|
'user_id' => $user_id, |
|
55
|
1 |
|
'user_type' => $user_type, |
|
56
|
1 |
|
'user_name' => $user_name, |
|
57
|
1 |
|
'description' => $description, |
|
58
|
1 |
|
'ip_address' => $ip_address, |
|
59
|
1 |
|
'content_type' => $content_type, |
|
60
|
1 |
|
'content_id' => $content_id, |
|
61
|
1 |
|
]); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Clean old log records. |
|
66
|
|
|
* |
|
67
|
|
|
* @param int $maxAgeInMonths |
|
68
|
|
|
* |
|
69
|
|
|
* @return integer |
|
70
|
|
|
*/ |
|
71
|
1 |
|
public function cleanLog($maxAgeInMonths) |
|
72
|
|
|
{ |
|
73
|
1 |
|
$maxAgeInMonths = 4; |
|
74
|
1 |
|
$date = Carbon::now()->subMonths($maxAgeInMonths); |
|
75
|
|
|
|
|
76
|
1 |
|
return $this->model->where('created_at', '<=', $date->format('Y-m-d'))->delete(); |
|
|
|
|
|
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe: