Passed
Push — master ( ed3719...9cc54a )
by Loban
02:45
created

Manager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 7
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * @link https://github.com/lav45/yii2-activity-logger
4
 * @copyright Copyright (c) 2017 LAV45
5
 * @author Aleksey Loban <[email protected]>
6
 * @license http://opensource.org/licenses/BSD-3-Clause
7
 */
8
9
namespace lav45\activityLogger;
10
11
use lav45\activityLogger\storage\DeleteCommand;
12
use lav45\activityLogger\storage\MessageData;
13
use lav45\activityLogger\storage\StorageInterface;
14
use Throwable;
15
use Yii;
16
use yii\base\BaseObject;
17
use yii\web\IdentityInterface;
18
19
class Manager extends BaseObject implements ManagerInterface
20
{
21
    public string $user = 'user';
22
23
    public string $userNameAttribute = 'username';
24
25
    public bool $debug = YII_DEBUG;
26
27
    private StorageInterface $storage;
28
29 4
    public function __construct(
30
        StorageInterface $storage,
31
        array            $config = []
32
    )
33
    {
34 4
        parent::__construct($config);
35 4
        $this->storage = $storage;
36
    }
37
38 26
    protected function getUserIdentity(): ?IdentityInterface
39
    {
40
        /** @var \yii\web\User $user */
41 26
        $user = Yii::$app->get($this->user, false);
42 26
        if ($user) {
0 ignored issues
show
introduced by
$user is of type yii\web\User, thus it always evaluated to true.
Loading history...
43 1
            return $user->getIdentity();
44
        }
45 25
        return null;
46
    }
47
48 25
    public function isEnabled(): bool
49
    {
50 25
        return true;
51
    }
52
53 26
    public function log(MessageData $message): bool
54
    {
55 26
        if ($identity = $this->getUserIdentity()) {
56 1
            $message->userId = $identity->getId();
57 1
            $message->userName = $identity->{$this->userNameAttribute};
58
        }
59
60
        try {
61 26
            $this->storage->save($message);
62 26
            return true;
63
        } catch (Throwable $e) {
64
            $this->throwException($e);
65
            return false;
66
        }
67
    }
68
69 4
    public function delete(DeleteCommand $command): bool
70
    {
71
        try {
72 4
            $this->storage->delete($command);
73 4
            return true;
74
        } catch (Throwable $e) {
75
            $this->throwException($e);
76
            return false;
77
        }
78
    }
79
80
    private function throwException(Throwable $e): void
81
    {
82
        if ($this->debug) {
83
            throw $e;
84
        }
85
        Yii::error($e->getMessage(), static::class);
86
    }
87
}