AuditableTraitObserver   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 60
ccs 0
cts 19
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A creating() 0 13 3
A getAuthenticatedUserId() 0 4 2
A updating() 0 8 2
A saved() 0 9 3
1
<?php
2
3
namespace Yajra\Auditable;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
class AuditableTraitObserver
8
{
9
    /**
10
     * Model's creating event hook.
11
     *
12
     * @param Model $model
13
     */
14
    public function creating(Model $model)
15
    {
16
        $createdBy = $model->getCreatedByColumn();
17
        $updatedBy = $model->getUpdatedByColumn();
18
19
        if (! $model->$createdBy) {
20
            $model->$createdBy = $this->getAuthenticatedUserId();
21
        }
22
23
        if (! $model->$updatedBy) {
24
            $model->$updatedBy = $this->getAuthenticatedUserId();
25
        }
26
    }
27
28
    /**
29
     * Get authenticated user id depending on model's auth guard.
30
     *
31
     * @return int
32
     */
33
    protected function getAuthenticatedUserId()
34
    {
35
        return auth()->check() ? auth()->id() : null;
36
    }
37
38
    /**
39
     * Model's updating event hook.
40
     *
41
     * @param Model $model
42
     */
43
    public function updating(Model $model)
44
    {
45
        $updatedBy = $model->getUpdatedByColumn();
46
47
        if (! $model->isDirty($updatedBy)) {
48
            $model->$updatedBy = $this->getAuthenticatedUserId();
49
        }
50
    }
51
52
    /**
53
     * Set updatedBy column on save if value is not the same.
54
     *
55
     * @param \Illuminate\Database\Eloquent\Model $model
56
     */
57
    public function saved(Model $model)
58
    {
59
        $updatedBy = $model->getUpdatedByColumn();
60
61
        if ($this->getAuthenticatedUserId() && $model->$updatedBy <> $this->getAuthenticatedUserId()) {
62
            $model->$updatedBy = $this->getAuthenticatedUserId();
63
            $model->save();
64
        }
65
    }
66
}
67