Completed
Push — psr-3-target ( 2554ab )
by Alexander
37:44
created

PsrTarget::setLevels()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 12
nc 5
nop 1
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 yii\log;
9
10
use Psr\Log\LoggerAwareInterface;
11
use Psr\Log\LoggerAwareTrait;
12
use Psr\Log\LoggerInterface;
13
use Psr\Log\NullLogger;
14
use yii\base\InvalidConfigException;
15
16
/**
17
 * PsrTarget is a log target which uses PSR-2 compatible logger
18
 *
19
 * @author Alexander Makarov <[email protected]>
20
 * @since 2.0.12
21
 */
22
class PsrTarget extends Target implements LoggerAwareInterface
23
{
24
    use LoggerAwareTrait;
25
26
    public $exportInterval = 1;
27
28
    public $levelsMap = [
29
        Logger::LEVEL_ERROR => 'error',
30
        Logger::LEVEL_WARNING => 'warning',
31
        Logger::LEVEL_INFO => 'info',
32
        Logger::LEVEL_TRACE => 'debug',
33
    ];
34
35
    /**
36
     * @return LoggerInterface
37
     */
38
    public function getLogger()
39
    {
40
        if (!$this->logger) {
41
            $this->logger = new NullLogger();
42
        }
43
        return $this->logger;
44
    }
45
46
    /**
47
     * @inheritdoc
48
     */
49
    public function export()
50
    {
51
        foreach ($this->messages as $message) {
52
            $this->logger->log($this->levelsMap[$message[1]],
53
                $message[0],
54
            [
55
                'category' => $message[2],
56
                'memory' => $message[5],
57
                'trace' => $message[4],
58
            ]);
59
        }
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function setLevels($levels)
66
    {
67
        if (is_array($levels)) {
68
            foreach ($levels as $level) {
69
                if (!isset($this->levelsMap[$level])) {
70
                    throw new InvalidConfigException('PsrTarget supports only error, warning, info and trace levels.');
71
                }
72
            }
73
        } else {
74
            $bitmapValues = array_reduce(array_flip($this->levelsMap),
75
                function ($carry, $item) {
76
                    return $carry | $item;
77
                });
78
            if (!($bitmapValues & $levels) && $levels !== 0) {
79
                throw new InvalidConfigException("Incorrect $levels value. PsrTarget supports only error, warning, info and trace levels.");
80
            }
81
        }
82
83
        parent::setLevels($levels);
84
    }
85
}