Message::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 1
1
<?php
2
/**
3
 * Yii 2 log message object
4
 *
5
 * @see       https://github.com/sergeymakinen/yii2-log-message
6
 * @copyright Copyright (c) 2017-2018 Sergey Makinen (https://makinen.ru)
7
 * @license   https://github.com/sergeymakinen/yii2-log-message/blob/master/LICENSE MIT License
8
 */
9
10
namespace sergeymakinen\yii\logmessage;
11
12
use yii\base\BaseObject;
13
use yii\base\InvalidConfigException;
14
use yii\console\Request as ConsoleRequest;
15
use yii\helpers\VarDumper;
16
use yii\log\Logger;
17
use yii\log\Target;
18
use yii\web\Request as WebRequest;
19
20
/**
21
 * This class wraps a log message and exposes its properties as well as the current request/user details.
22
 * @property string $category message category.
23
 * @property string|null $commandLine command line.
24
 * @property bool $isConsoleRequest whether the current request is a console request.
25
 * @property string $level message level as a string.
26
 * @property string $prefix messsage prefix string.
27
 * @property string|null $sessionId session ID.
28
 * @property string|null $stackTrace stack trace as a string.
29
 * @property string $text message text.
30
 * @property float $timestamp message creation timestamp.
31
 * @property string|null $url absolute URL.
32
 * @property int|string|null $userId user identity ID.
33
 * @property string|null $userIp user IP address.
34
 */
35
class Message extends BaseObject
36
{
37
    /**
38
     * @var array raw message.
39
     */
40
    public $message;
41
42
    /**
43
     * @var Target message target.
44
     * Must be a [[Target]] instance or `null`.
45
     */
46
    public $target;
47
48
    /**
49
     * @var bool whether the current request is a console request.
50
     */
51
    private $_isConsoleRequest;
52
53
    /**
54
     * Constructor.
55
     * @param array $message message.
56
     * @param Target|null $target message target.
57
     * Must be a [[Target]] instance or `null`.
58
     * @param array $config name-value pairs that will be used to initialize the object properties.
59
     */
60 143
    public function __construct(array $message, $target = null, $config = [])
61
    {
62 143
        $this->message = $message;
63 143
        $this->target = $target;
64 143
        parent::__construct($config);
65 142
    }
66
67
    /**
68
     * @inheritDoc
69
     */
70 143
    public function init()
71
    {
72 143
        parent::init();
73 143
        if ($this->target !== null && !$this->target instanceof Target) {
74 1
            throw new InvalidConfigException('`' . get_class($this) . '::target` should be an instance of `' . Target::className() . '`.');
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
75
        }
76 142
    }
77
78
    /**
79
     * Returns the message category.
80
     * @return string message category.
81
     */
82 12
    public function getCategory()
83
    {
84 12
        return $this->message[2];
85
    }
86
87
    /**
88
     * Returns the command line.
89
     * @return string|null command line, `null` if not available.
90
     */
91 12
    public function getCommandLine()
92
    {
93 12
        if (\Yii::$app === null || !$this->getIsConsoleRequest()) {
94 8
            return null;
95
        }
96
97 4
        $params = [];
98 4
        if (isset($_SERVER['argv'])) {
99 4
            $params = $_SERVER['argv'];
100 4
        }
101 4
        return implode(' ', $params);
102
    }
103
104
    /**
105
     * Returns whether the current request is a console request.
106
     * @return bool whether the current request is a console request.
107
     * @throws InvalidConfigException if unable to determine.
108
     */
109 33
    public function getIsConsoleRequest()
110
    {
111 33
        if ($this->_isConsoleRequest === null && \Yii::$app !== null) {
112 32
            if (\Yii::$app->getRequest() instanceof ConsoleRequest) {
113 16
                $this->_isConsoleRequest = true;
114 32
            } elseif (\Yii::$app->getRequest() instanceof WebRequest) {
115 16
                $this->_isConsoleRequest = false;
116 16
            }
117 32
        }
118 33
        if ($this->_isConsoleRequest === null) {
119 1
            throw new InvalidConfigException('Unable to determine if the application is a console or web application.');
120
        }
121
122 32
        return $this->_isConsoleRequest;
123
    }
124
125
    /**
126
     * Returns the message level as a string.
127
     * @return string message level as a string.
128
     */
129 12
    public function getLevel()
130
    {
131 12
        return Logger::getLevelName($this->message[1]);
132
    }
133
134
    /**
135
     * Returns a string to be prefixed to the message.
136
     * @return string messsage prefix string.
137
     */
138 12
    public function getPrefix()
139
    {
140 12
        if ($this->target !== null) {
141 8
            return $this->target->getMessagePrefix($this->message);
142
        } else {
143 12
            return '';
144
        }
145
    }
146
147
    /**
148
     * Returns the session ID.
149
     * @return string|null session ID, `null` if not available.
150
     */
151 12
    public function getSessionId()
152
    {
153
        if (
154 12
            \Yii::$app !== null
155 12
            && \Yii::$app->has('session', true)
156 12
            && \Yii::$app->getSession() !== null
157 12
            && \Yii::$app->getSession()->getIsActive()
158 12
        ) {
159 4
            return \Yii::$app->getSession()->getId();
160
        } else {
161 8
            return null;
162
        }
163
    }
164
165
    /**
166
     * Returns the additional stack trace as a string.
167
     * @return string|null stack trace, `null` if not available.
168
     */
169 13
    public function getStackTrace()
170
    {
171 13
        if (!isset($this->message[4]) || empty($this->message[4])) {
172 12
            return null;
173
        }
174
175 1
        $traces = array_map(function ($trace) {
176 1
            return "in {$trace['file']}:{$trace['line']}";
177 1
        }, $this->message[4]);
178 1
        return implode("\n", $traces);
179
    }
180
181
    /**
182
     * Returns the message text.
183
     * @return string message text.
184
     */
185 12
    public function getText()
186
    {
187 12
        $text = $this->message[0];
188 12
        if (!is_string($text)) {
189 6
            if ($text instanceof \Throwable || $text instanceof \Exception) {
190 3
                $text = (string) $text;
191 3
            } else {
192 3
                $text = VarDumper::export($text);
193
            }
194 6
        }
195 12
        return $text;
196
    }
197
198
    /**
199
     * Returns the message creation timestamp.
200
     * @return float message creation timestamp.
201
     */
202 12
    public function getTimestamp()
203
    {
204 12
        return $this->message[3];
205
    }
206
207
    /**
208
     * Returns the current absolute URL.
209
     * @return null|string absolute URL, `null` if not available.
210
     */
211 12
    public function getUrl()
212
    {
213 12
        if (\Yii::$app === null || $this->getIsConsoleRequest()) {
214 8
            return null;
215
        }
216
217 4
        return \Yii::$app->getRequest()->getAbsoluteUrl();
218
    }
219
220
    /**
221
     * Returns the user identity ID.
222
     * @return int|string|null user identity ID, `null` if not available.
223
     */
224 12
    public function getUserId()
225
    {
226
        if (
227 12
            \Yii::$app !== null
228 12
            && \Yii::$app->has('user', true)
229 12
            && \Yii::$app->getUser() !== null
230 12
        ) {
231 4
            $user = \Yii::$app->getUser()->getIdentity(false);
232 4
            if ($user !== null) {
233 4
                return $user->getId();
234
            }
235
        }
236 8
        return null;
237
    }
238
239
    /**
240
     * Returns the user IP address.
241
     * @return string|null user IP address, `null` if not available.
242
     */
243 12
    public function getUserIp()
244
    {
245 12
        if (\Yii::$app === null || $this->getIsConsoleRequest()) {
246 8
            return null;
247
        }
248
249 4
        return \Yii::$app->getRequest()->getUserIP();
250
    }
251
}
252