AuditableTraitObserver::getAuthenticatedUserId()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
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