LogQuery   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 19
dl 0
loc 40
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A createLogEntity() 0 11 3
A getEntityType() 0 8 3
1
<?php
2
namespace common\models\query;
3
4
use yii\db\ActiveQuery;
5
use yii\db\ActiveRecord;
6
use common\models\Log;
7
use common\models\User;
8
use yii\helpers\Json;
9
10
class LogQuery extends ActiveQuery
11
{
12
    protected $actionEventMap = [
13
        ActiveRecord::EVENT_BEFORE_INSERT => Log::ACTION_CREATE,
14
        ActiveRecord::EVENT_BEFORE_UPDATE => Log::ACTION_UPDATE,
15
        ActiveRecord::EVENT_BEFORE_DELETE => Log::ACTION_DELETE,
16
    ];
17
18
    protected $entityTypeMap = [
19
        User::class => Log::ENTITY_USER,
20
    ];
21
22
    /**
23
     * @param ActiveRecord $entity
24
     * @param int $action
25
     * @param bool $safeOldData
26
     * @param bool $saveNewData
27
     * @return Log
28
     */
29
    public function createLogEntity(ActiveRecord $entity, $action, $safeOldData = true, $saveNewData = true)
30
    {
31
        $log = new Log();
32
        $log->setAttributes([
33
            'action' => $action,
34
            'item_type' => $this->getEntityType($entity),
35
            'item_id' => $entity->getPrimaryKey(),
36
            'old_data' => $safeOldData ? Json::encode($entity->toArray()) : '',
37
            'new_data' => $saveNewData ? Json::encode($entity->getOldAttributes()) : '',
38
        ]);
39
        return $log;
40
    }
41
42
    protected function getEntityType(ActiveRecord $entity)
43
    {
44
        foreach ($this->entityTypeMap as $entityClass => $entityTypeId) {
45
            if ($entity instanceof $entityClass) {
46
                return $entityTypeId;
47
            }
48
        }
49
        return Log::ENTITY_UNKNOWN;
50
    }
51
}
52