1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: Lai Vu |
5
|
|
|
* Date: 10/25/2016 |
6
|
|
|
* Time: 9:18 AM |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace LaiVu\ActivityLog\Handlers; |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
use Carbon\Carbon; |
13
|
|
|
use Illuminate\Database\Eloquent\Model; |
14
|
|
|
use LaiVu\ActivityLog\Exceptions\InvalidConfiguration; |
15
|
|
|
use LaiVu\ActivityLog\Models\Activity; |
16
|
|
|
|
17
|
|
|
class EloquentHandler implements ActivityLogHandlerInterface |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param \Illuminate\Database\Eloquent\Model $performOn |
22
|
|
|
* @param \Illuminate\Database\Eloquent\Model $causerBy |
23
|
|
|
* @param array $properties |
24
|
|
|
* @param $logName |
25
|
|
|
* @param string $description |
26
|
|
|
* @return mixed |
27
|
|
|
*/ |
28
|
|
|
function log($performOn, $causerBy, $properties = [], $logName, $description) |
|
|
|
|
29
|
|
|
{ |
30
|
|
|
$activityModelClassName = $this->determineActivityModel(); |
31
|
|
|
$activity = new $activityModelClassName(); |
32
|
|
|
|
33
|
|
|
if ($performOn) { |
34
|
|
|
$activity->subject()->associate($performOn); |
35
|
|
|
} |
36
|
|
|
if ($causerBy) { |
37
|
|
|
$activity->causer()->associate($causerBy); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$activity->properties = $properties; |
41
|
|
|
|
42
|
|
|
$activity->description = $description; |
43
|
|
|
|
44
|
|
|
$activity->log_name = $logName; |
45
|
|
|
|
46
|
|
|
$activity->save(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param $maxAgeInDays |
51
|
|
|
* @return bool |
52
|
|
|
* @throws \Exception |
53
|
|
|
*/ |
54
|
|
|
function cleanLog($maxAgeInDays) |
|
|
|
|
55
|
|
|
{ |
56
|
|
|
$cutOffDate = Carbon::now()->subDays($maxAgeInDays)->format('Y-m-d H:i:s'); |
57
|
|
|
Activity::where('created_at', '<=', $cutOffDate)->delete(); |
58
|
|
|
return true; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return Model |
63
|
|
|
* @throws InvalidConfiguration |
64
|
|
|
*/ |
65
|
|
|
public function determineActivityModel() |
66
|
|
|
{ |
67
|
|
|
$activityModel = config('activitylog.activity_model', Activity::class); |
68
|
|
|
if (!is_a($activityModel, Activity::class, true)) { |
69
|
|
|
throw InvalidConfiguration::modelIsNotValid($activityModel); |
70
|
|
|
} |
71
|
|
|
return $activityModel; |
72
|
|
|
} |
73
|
|
|
} |
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.