Passed
Push — master ( 06f5a7...6013ae )
by Loban
02:50
created

Manager::getUserIdentity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
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 6
    public function __construct(
30
        StorageInterface $storage,
31
        array            $config = []
32
    )
33
    {
34 6
        parent::__construct($config);
35 6
        $this->storage = $storage;
36
    }
37
38 27
    protected function getUserIdentity(): ?IdentityInterface
39
    {
40
        /** @var \yii\web\User $user */
41 27
        $user = Yii::$app->get($this->user, false);
42 27
        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 26
        return null;
46
    }
47
48 27
    public function isEnabled(): bool
49
    {
50 27
        return true;
51
    }
52
53 27
    public function log(MessageData $message): bool
54
    {
55 27
        if ($identity = $this->getUserIdentity()) {
56 1
            $message->userId = $identity->getId();
57 1
            $message->userName = $identity->{$this->userNameAttribute};
58
        }
59
60
        try {
61 27
            $this->storage->save($message);
62 26
            return true;
63 1
        } catch (Throwable $e) {
64 1
            $this->throwException($e);
65 1
            return false;
66
        }
67
    }
68
69 6
    public function delete(DeleteCommand $command): bool
70
    {
71
        try {
72 6
            $this->storage->delete($command);
73 5
            return true;
74 2
        } catch (Throwable $e) {
75 2
            $this->throwException($e);
76 1
            return false;
77
        }
78
    }
79
80 2
    private function throwException(Throwable $e): void
81
    {
82 2
        if ($this->debug) {
83 2
            throw $e;
84
        }
85 1
        Yii::error($e->getMessage(), static::class);
86
    }
87
}