Completed
Push — master ( 8beb36...d49ec7 )
by Alexander
11:49
created

Target::getTime()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
crap 2
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 Yii;
11
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
use yii\helpers\ArrayHelper;
14
use yii\helpers\VarDumper;
15
use yii\web\Request;
16
17
/**
18
 * Target is the base class for all log target classes.
19
 *
20
 * A log target object will filter the messages logged by [[Logger]] according
21
 * to its [[levels]] and [[categories]] properties. It may also export the filtered
22
 * messages to specific destination defined by the target, such as emails, files.
23
 *
24
 * Level filter and category filter are combinatorial, i.e., only messages
25
 * satisfying both filter conditions will be handled. Additionally, you
26
 * may specify [[except]] to exclude messages of certain categories.
27
 *
28
 * @property int $levels The message levels that this target is interested in. This is a bitmap of level
29
 * values. Defaults to 0, meaning  all available levels. Note that the type of this property differs in getter
30
 * and setter. See [[getLevels()]] and [[setLevels()]] for details.
31
 * @property bool $enabled Whether to enable this log target. Defaults to true.
32
 *
33
 * For more details and usage information on Target, see the [guide article on logging & targets](guide:runtime-logging).
34
 *
35
 * @author Qiang Xue <[email protected]>
36
 * @since 2.0
37
 */
38
abstract class Target extends Component
39
{
40
    /**
41
     * @var array list of message categories that this target is interested in. Defaults to empty, meaning all categories.
42
     * You can use an asterisk at the end of a category so that the category may be used to
43
     * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
44
     * categories starting with 'yii\db\', such as 'yii\db\Connection'.
45
     */
46
    public $categories = [];
47
    /**
48
     * @var array list of message categories that this target is NOT interested in. Defaults to empty, meaning no uninteresting messages.
49
     * If this property is not empty, then any category listed here will be excluded from [[categories]].
50
     * You can use an asterisk at the end of a category so that the category can be used to
51
     * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
52
     * categories starting with 'yii\db\', such as 'yii\db\Connection'.
53
     * @see categories
54
     */
55
    public $except = [];
56
    /**
57
     * @var array list of the PHP predefined variables that should be logged in a message.
58
     * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be logged.
59
     *
60
     * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']`.
61
     *
62
     * Since version 2.0.9 additional syntax can be used:
63
     * Each element could be specified as one of the following:
64
     *
65
     * - `var` - `var` will be logged.
66
     * - `var.key` - only `var[key]` key will be logged.
67
     * - `!var.key` - `var[key]` key will be excluded.
68
     *
69
     * @see \yii\helpers\ArrayHelper::filter()
70
     */
71
    public $logVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER'];
72
    /**
73
     * @var callable a PHP callable that returns a string to be prefixed to every exported message.
74
     *
75
     * If not set, [[getMessagePrefix()]] will be used, which prefixes the message with context information
76
     * such as user IP, user ID and session ID.
77
     *
78
     * The signature of the callable should be `function ($message)`.
79
     */
80
    public $prefix;
81
    /**
82
     * @var int how many messages should be accumulated before they are exported.
83
     * Defaults to 1000. Note that messages will always be exported when the application terminates.
84
     * Set this property to be 0 if you don't want to export messages until the application terminates.
85
     */
86
    public $exportInterval = 1000;
87
    /**
88
     * @var array the messages that are retrieved from the logger so far by this log target.
89
     * Please refer to [[Logger::messages]] for the details about the message structure.
90
     */
91
    public $messages = [];
92
93
    /**
94
     * @var bool whether to log time with microseconds.
95
     * Defaults to false.
96
     * @since 2.0.13
97
     */
98
    public $microtime = false;
99
100
    private $_levels = 0;
101
    private $_enabled = true;
102
103
    /**
104
     * Exports log [[messages]] to a specific destination.
105
     * Child classes must implement this method.
106
     */
107
    abstract public function export();
108
109
    /**
110
     * Processes the given log messages.
111
     * This method will filter the given messages with [[levels]] and [[categories]].
112
     * And if requested, it will also export the filtering result to specific medium (e.g. email).
113
     * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
114
     * of each message.
115
     * @param bool $final whether this method is called at the end of the current application
116
     */
117 337
    public function collect($messages, $final)
118
    {
119 337
        $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
120 337
        $count = count($this->messages);
121 337
        if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
122 25
            if (($context = $this->getContextMessage()) !== '') {
123 6
                $this->messages[] = [$context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME];
124
            }
125
            // set exportInterval to 0 to avoid triggering export again while exporting
126 25
            $oldExportInterval = $this->exportInterval;
127 25
            $this->exportInterval = 0;
128 25
            $this->export();
129 25
            $this->exportInterval = $oldExportInterval;
130
131 25
            $this->messages = [];
132
        }
133 337
    }
134
135
    /**
136
     * Generates the context information to be logged.
137
     * The default implementation will dump user information, system variables, etc.
138
     * @return string the context information. If an empty string, it means no context information.
139
     */
140 26
    protected function getContextMessage()
141
    {
142 26
        $context = ArrayHelper::filter($GLOBALS, $this->logVars);
143 26
        $result = [];
144 26
        foreach ($context as $key => $value) {
145 7
            $result[] = "\${$key} = " . VarDumper::dumpAsString($value);
146
        }
147
148 26
        return implode("\n\n", $result);
149
    }
150
151
    /**
152
     * @return int the message levels that this target is interested in. This is a bitmap of
153
     * level values. Defaults to 0, meaning  all available levels.
154
     */
155 339
    public function getLevels()
156
    {
157 339
        return $this->_levels;
158
    }
159
160
    /**
161
     * Sets the message levels that this target is interested in.
162
     *
163
     * The parameter can be either an array of interested level names or an integer representing
164
     * the bitmap of the interested level values. Valid level names include: 'error',
165
     * 'warning', 'info', 'trace' and 'profile'; valid level values include:
166
     * [[Logger::LEVEL_ERROR]], [[Logger::LEVEL_WARNING]], [[Logger::LEVEL_INFO]],
167
     * [[Logger::LEVEL_TRACE]] and [[Logger::LEVEL_PROFILE]].
168
     *
169
     * For example,
170
     *
171
     * ```php
172
     * ['error', 'warning']
173
     * // which is equivalent to:
174
     * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING
175
     * ```
176
     *
177
     * @param array|int $levels message levels that this target is interested in.
178
     * @throws InvalidConfigException if $levels value is not correct.
179
     */
180 24
    public function setLevels($levels)
181
    {
182 24
        static $levelMap = [
183
            'error' => Logger::LEVEL_ERROR,
184
            'warning' => Logger::LEVEL_WARNING,
185
            'info' => Logger::LEVEL_INFO,
186
            'trace' => Logger::LEVEL_TRACE,
187
            'profile' => Logger::LEVEL_PROFILE,
188
        ];
189 24
        if (is_array($levels)) {
190 11
            $this->_levels = 0;
191 11
            foreach ($levels as $level) {
192 11
                if (isset($levelMap[$level])) {
193 11
                    $this->_levels |= $levelMap[$level];
194
                } else {
195 11
                    throw new InvalidConfigException("Unrecognized level: $level");
196
                }
197
            }
198
        } else {
199 13
            $bitmapValues = array_reduce($levelMap, function ($carry, $item) {
200 13
                return $carry | $item;
201 13
            });
202 13
            if (!($bitmapValues & $levels) && $levels !== 0) {
203 1
                throw new InvalidConfigException("Incorrect $levels value");
204
            }
205 13
            $this->_levels = $levels;
206
        }
207 24
    }
208
209
    /**
210
     * Filters the given messages according to their categories and levels.
211
     * @param array $messages messages to be filtered.
212
     * The message structure follows that in [[Logger::messages]].
213
     * @param int $levels the message levels to filter by. This is a bitmap of
214
     * level values. Value 0 means allowing all levels.
215
     * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
216
     * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
217
     * @return array the filtered messages.
218
     */
219 337
    public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
220
    {
221 337
        foreach ($messages as $i => $message) {
222 337
            if ($levels && !($levels & $message[1])) {
223 316
                unset($messages[$i]);
224 316
                continue;
225
            }
226
227 260
            $matched = empty($categories);
228 260
            foreach ($categories as $category) {
229 245
                if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
230 217
                    $matched = true;
231 245
                    break;
232
                }
233
            }
234
235 260
            if ($matched) {
236 232
                foreach ($except as $category) {
237 1
                    $prefix = rtrim($category, '*');
238 1
                    if (($message[2] === $category || $prefix !== $category) && strpos($message[2], $prefix) === 0) {
239 1
                        $matched = false;
240 1
                        break;
241
                    }
242
                }
243
            }
244
245 260
            if (!$matched) {
246 260
                unset($messages[$i]);
247
            }
248
        }
249
250 337
        return $messages;
251
    }
252
253
    /**
254
     * Formats a log message for display as a string.
255
     * @param array $message the log message to be formatted.
256
     * The message structure follows that in [[Logger::messages]].
257
     * @return string the formatted message
258
     */
259 3
    public function formatMessage($message)
260
    {
261 3
        list($text, $level, $category, $timestamp) = $message;
262 3
        $level = Logger::getLevelName($level);
263 3
        if (!is_string($text)) {
264
            // exceptions may not be serializable if in the call stack somewhere is a Closure
265
            if ($text instanceof \Throwable || $text instanceof \Exception) {
266
                $text = (string) $text;
267
            } else {
268
                $text = VarDumper::export($text);
269
            }
270
        }
271 3
        $traces = [];
272 3
        if (isset($message[4])) {
273 2
            foreach ($message[4] as $trace) {
274
                $traces[] = "in {$trace['file']}:{$trace['line']}";
275
            }
276
        }
277
278 3
        $prefix = $this->getMessagePrefix($message);
279 3
        return $this->getTime($timestamp) . " {$prefix}[$level][$category] $text"
280 3
            . (empty($traces) ? '' : "\n    " . implode("\n    ", $traces));
281
    }
282
283
    /**
284
     * Returns a string to be prefixed to the given message.
285
     * If [[prefix]] is configured it will return the result of the callback.
286
     * The default implementation will return user IP, user ID and session ID as a prefix.
287
     * @param array $message the message being exported.
288
     * The message structure follows that in [[Logger::messages]].
289
     * @return string the prefix string
290
     */
291 9
    public function getMessagePrefix($message)
292
    {
293 9
        if ($this->prefix !== null) {
294
            return call_user_func($this->prefix, $message);
295
        }
296
297 9
        if (Yii::$app === null) {
298 1
            return '';
299
        }
300
301 8
        $request = Yii::$app->getRequest();
302 8
        $ip = $request instanceof Request ? $request->getUserIP() : '-';
303
304
        /* @var $user \yii\web\User */
305 8
        $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
306 8
        if ($user && ($identity = $user->getIdentity(false))) {
307
            $userID = $identity->getId();
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $identity (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
308
        } else {
309 8
            $userID = '-';
310
        }
311
312
        /* @var $session \yii\web\Session */
313 8
        $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
314 8
        $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
315
316 8
        return "[$ip][$userID][$sessionID]";
317
    }
318
319
    /**
320
     * Sets a value indicating whether this log target is enabled.
321
     * @param bool|callable $value a boolean value or a callable to obtain the value from.
322
     * The callable value is available since version 2.0.13.
323
     *
324
     * A callable may be used to determine whether the log target should be enabled in a dynamic way.
325
     * For example, to only enable a log if the current user is logged in you can configure the target
326
     * as follows:
327
     *
328
     * ```php
329
     * 'enabled' => function() {
330
     *     return !Yii::$app->user->isGuest;
331
     * }
332
     * ```
333
     */
334 2
    public function setEnabled($value)
335
    {
336 2
        $this->_enabled = $value;
0 ignored issues
show
Documentation Bug introduced by
It seems like $value can also be of type callable. However, the property $_enabled is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
337 2
    }
338
339
    /**
340
     * Check whether the log target is enabled.
341
     * @property Indicates whether this log target is enabled. Defaults to true.
342
     * @return bool A value indicating whether this log target is enabled.
343
     */
344 338
    public function getEnabled()
345
    {
346 338
        if (is_callable($this->_enabled)) {
347 1
            return call_user_func($this->_enabled, $this);
348
        }
349
350 338
        return $this->_enabled;
351
    }
352
353
    /**
354
     * Returns formatted ('Y-m-d H:i:s') timestamp for message.
355
     * If [[microtime]] is configured to true it will return format 'Y-m-d H:i:s.u'
356
     * @param float $timestamp
357
     * @return string
358
     * @since 2.0.13
359
     */
360 3
    protected function getTime($timestamp)
361
    {
362 3
        list ($timestamp, $usec) = explode('.', (string)$timestamp);
363
364 3
        return date('Y-m-d H:i:s', $timestamp) . ($this->microtime ? ('.' . $usec) : '');
365
    }
366
}
367