1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sfneal\Tracking\Jobs; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Illuminate\Database\Eloquent\Collection; |
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
use Sfneal\Queueables\Job; |
9
|
|
|
use Sfneal\Tracking\Models\TrackAction; |
10
|
|
|
use Sfneal\Tracking\Utils\ModelAdapter; |
11
|
|
|
|
12
|
|
|
class TrackActionJob extends Job |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Delete the job if its models no longer exist. |
16
|
|
|
* |
17
|
|
|
* @var bool |
18
|
|
|
*/ |
19
|
|
|
public $deleteWhenMissingModels = true; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var string Description of the action. |
23
|
|
|
*/ |
24
|
|
|
public $action; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var Collection|Model Model or models effected by the action |
28
|
|
|
*/ |
29
|
|
|
public $model; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var array array of changes made to the model |
33
|
|
|
*/ |
34
|
|
|
public $model_changes; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Track a user's action. |
38
|
|
|
* |
39
|
|
|
* @param string $action |
40
|
|
|
* @param Model|Collection $model |
41
|
|
|
*/ |
42
|
|
|
public function __construct(string $action, $model) |
43
|
|
|
{ |
44
|
|
|
$this->action = $action; |
45
|
|
|
$this->model = $model; |
46
|
|
|
|
47
|
|
|
try { |
48
|
|
|
$this->model_changes = $model->getChanges(); |
49
|
|
|
} catch (Exception $exception) { |
50
|
|
|
$this->model_changes = []; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$this->onQueue(config('tracking.queue')); |
54
|
|
|
$this->onConnection(config('tracking.driver')); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Execute the job. |
59
|
|
|
* |
60
|
|
|
* @return TrackAction|Model|null |
61
|
|
|
*/ |
62
|
|
|
public function handle(): ?TrackAction |
63
|
|
|
{ |
64
|
|
|
if ($this->model->exists) { |
65
|
|
|
return ModelAdapter::TrackAction()::query()->create([ |
66
|
|
|
'action' => $this->action, |
67
|
|
|
'model_changes' => $this->model_changes, |
68
|
|
|
'trackable_id' => $this->model->getKey(), |
69
|
|
|
'trackable_type' => get_class($this->model), |
70
|
|
|
]); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return null; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|