DbStorage   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 31
c 0
b 0
f 0
dl 0
loc 58
ccs 34
cts 34
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 3 1
A save() 0 15 1
A init() 0 3 1
A delete() 0 21 3
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\storage;
10
11
use yii\db\Query;
12
use yii\db\Connection;
13
use yii\di\Instance;
14
use yii\base\BaseObject;
15
16
class DbStorage extends BaseObject implements StorageInterface
17
{
18
    /** @var Connection|string|array */
19
    public $db = 'db';
20
21
    public string $tableName = '{{%activity_log}}';
22
23 29
    public function init(): void
24
    {
25 29
        $this->db = Instance::ensure($this->db, Connection::class);
26
    }
27
28 25
    public function save(MessageData $message): void
29
    {
30 25
        (new Query)
31 25
            ->createCommand($this->db)
32 25
            ->insert($this->tableName, [
33 25
                'entity_name' => $message->entityName,
34 25
                'entity_id' => $message->entityId,
35 25
                'created_at' => $message->createdAt,
36 25
                'user_id' => $message->userId,
37 25
                'user_name' => $message->userName,
38 25
                'action' => $message->action,
39 25
                'env' => $message->env,
40 25
                'data' => $this->encode($message->data),
41 25
            ])
42 25
            ->execute();
43
    }
44
45
    /**
46
     * @param array|string $data
47
     */
48 25
    private function encode($data): string
49
    {
50 25
        return json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
51
    }
52
53 4
    public function delete(DeleteCommand $command): void
54
    {
55 4
        $condition = array_filter([
56 4
            'entity_name' => $command->entityName,
57 4
            'entity_id' => $command->entityId,
58 4
            'user_id' => $command->userId,
59 4
            'action' => $command->action,
60 4
            'env' => $command->env,
61 4
        ]);
62
63 4
        if ($command->oldThan) {
64 1
            if (empty($condition)) {
65 1
                throw new \InvalidArgumentException("Condition can't be empty");
66
            }
67 1
            $condition = ['and', $condition, ['<=', 'created_at', $command->oldThan]];
68
        }
69
70 4
        (new Query)
71 4
            ->createCommand($this->db)
72 4
            ->delete($this->tableName, $condition)
73 4
            ->execute();
74
    }
75
}
76