LogTarget::export()   B
last analyzed

Complexity

Conditions 8
Paths 10

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
nc 10
nop 0
dl 0
loc 27
ccs 17
cts 17
cp 1
crap 8
rs 8.4444
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link      http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license   http://www.yiiframework.com/license/
6
 */
7
8
namespace bedezign\yii2\audit;
9
10
use Yii;
11
use yii\log\Target;
12
13
/**
14
 * LogTarget
15
 * @package bedezign\yii2\audit
16
 */
17
class LogTarget extends Target
18
{
19
    /**
20
     * @var Audit
21
     */
22
    public $module;
23
24
    /**
25
     * @var bool Set to true to allow Audit to export the logs during the handling of the request according to $exportInterval.
26
     * By default this is disabled, as it will cause extra DB load and possibly slow down the response time.
27
     * If you however expect to do an obscene amount of logging you can enable this.
28 75
     */
29
    public $exportAtIntervals = false;
30 75
31 75
    /**
32 75
     * @param Audit $module
33
     * @param array $config
34
     */
35
    public function __construct($module, $config = [])
36
    {
37 57
        parent::__construct($config);
38
        $this->module = $module;
39 57
    }
40
41 57
    /**
42
     *
43 57
     */
44 57
    public function export()
45 57
    {
46
        if (!\Yii::$app)
47 57
            // Things like this can happen in tests etc, but it is too late for us to do anything about that.
48
            return;
49 57
50 57
        $module = $this->module;
51 57
        if (!$module->entry || empty($module->panels))
52 57
            return;
53 57
54
        $entry = $module->entry;
55 57
56 57
        $records = [];
57 57
        foreach ($module->panels as $id => $panel) {
58
            $records[$id] = $panel->save();
59 9
        }
60 9
        $records = array_filter($records);
61
62 57
        if (!empty($records)) {
63 57
            if ($module->batchSave)
64 57
                $entry->addBatchData($records, false);
65
            else {
66
                foreach ($records as $type => $record)
67
                    $entry->addData($type, $record, false);
68
            }
69
        }
70 57
    }
71
72 57
    /**
73 57
     * @param array $messages
74 57
     * @param bool  $final
75 57
     */
76 57
    public function collect($messages, $final)
77
    {
78
        if ($this->exportAtIntervals) {
79
            parent::collect($messages, $final);
80
        }
81
        else {
82
            $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
83
            if ($final) {
84
                $this->export();
85
                $this->messages = [];
86
            }
87
        }
88
    }
89
}
90