Completed
Push — master ( 8700fd...9d854c )
by Carsten
11:41
created

Target::getEnabled()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
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
    private $_levels = 0;
94
    private $_enabled = true;
95
96
    /**
97
     * Exports log [[messages]] to a specific destination.
98
     * Child classes must implement this method.
99
     */
100
    abstract public function export();
101
102
    /**
103
     * Processes the given log messages.
104
     * This method will filter the given messages with [[levels]] and [[categories]].
105
     * And if requested, it will also export the filtering result to specific medium (e.g. email).
106
     * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
107
     * of each message.
108
     * @param bool $final whether this method is called at the end of the current application
109
     */
110 335
    public function collect($messages, $final)
111
    {
112 335
        $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except));
113 335
        $count = count($this->messages);
114 335
        if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
115 25
            if (($context = $this->getContextMessage()) !== '') {
116 6
                $this->messages[] = [$context, Logger::LEVEL_INFO, 'application', YII_BEGIN_TIME];
117
            }
118
            // set exportInterval to 0 to avoid triggering export again while exporting
119 25
            $oldExportInterval = $this->exportInterval;
120 25
            $this->exportInterval = 0;
121 25
            $this->export();
122 25
            $this->exportInterval = $oldExportInterval;
123
124 25
            $this->messages = [];
125
        }
126 335
    }
127
128
    /**
129
     * Generates the context information to be logged.
130
     * The default implementation will dump user information, system variables, etc.
131
     * @return string the context information. If an empty string, it means no context information.
132
     */
133 26
    protected function getContextMessage()
134
    {
135 26
        $context = ArrayHelper::filter($GLOBALS, $this->logVars);
136 26
        $result = [];
137 26
        foreach ($context as $key => $value) {
138 7
            $result[] = "\${$key} = " . VarDumper::dumpAsString($value);
139
        }
140
141 26
        return implode("\n\n", $result);
142
    }
143
144
    /**
145
     * @return int the message levels that this target is interested in. This is a bitmap of
146
     * level values. Defaults to 0, meaning  all available levels.
147
     */
148 337
    public function getLevels()
149
    {
150 337
        return $this->_levels;
151
    }
152
153
    /**
154
     * Sets the message levels that this target is interested in.
155
     *
156
     * The parameter can be either an array of interested level names or an integer representing
157
     * the bitmap of the interested level values. Valid level names include: 'error',
158
     * 'warning', 'info', 'trace' and 'profile'; valid level values include:
159
     * [[Logger::LEVEL_ERROR]], [[Logger::LEVEL_WARNING]], [[Logger::LEVEL_INFO]],
160
     * [[Logger::LEVEL_TRACE]] and [[Logger::LEVEL_PROFILE]].
161
     *
162
     * For example,
163
     *
164
     * ```php
165
     * ['error', 'warning']
166
     * // which is equivalent to:
167
     * Logger::LEVEL_ERROR | Logger::LEVEL_WARNING
168
     * ```
169
     *
170
     * @param array|int $levels message levels that this target is interested in.
171
     * @throws InvalidConfigException if $levels value is not correct.
172
     */
173 24
    public function setLevels($levels)
174
    {
175 24
        static $levelMap = [
176
            'error' => Logger::LEVEL_ERROR,
177
            'warning' => Logger::LEVEL_WARNING,
178
            'info' => Logger::LEVEL_INFO,
179
            'trace' => Logger::LEVEL_TRACE,
180
            'profile' => Logger::LEVEL_PROFILE,
181
        ];
182 24
        if (is_array($levels)) {
183 11
            $this->_levels = 0;
184 11
            foreach ($levels as $level) {
185 11
                if (isset($levelMap[$level])) {
186 11
                    $this->_levels |= $levelMap[$level];
187
                } else {
188 11
                    throw new InvalidConfigException("Unrecognized level: $level");
189
                }
190
            }
191
        } else {
192 13
            $bitmapValues = array_reduce($levelMap, function ($carry, $item) {
193 13
                return $carry | $item;
194 13
            });
195 13
            if (!($bitmapValues & $levels) && $levels !== 0) {
196 1
                throw new InvalidConfigException("Incorrect $levels value");
197
            }
198 13
            $this->_levels = $levels;
199
        }
200 24
    }
201
202
    /**
203
     * Filters the given messages according to their categories and levels.
204
     * @param array $messages messages to be filtered.
205
     * The message structure follows that in [[Logger::messages]].
206
     * @param int $levels the message levels to filter by. This is a bitmap of
207
     * level values. Value 0 means allowing all levels.
208
     * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
209
     * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
210
     * @return array the filtered messages.
211
     */
212 335
    public static function filterMessages($messages, $levels = 0, $categories = [], $except = [])
213
    {
214 335
        foreach ($messages as $i => $message) {
215 335
            if ($levels && !($levels & $message[1])) {
216 314
                unset($messages[$i]);
217 314
                continue;
218
            }
219
220 260
            $matched = empty($categories);
221 260
            foreach ($categories as $category) {
222 245
                if ($message[2] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2], rtrim($category, '*')) === 0) {
223 217
                    $matched = true;
224 245
                    break;
225
                }
226
            }
227
228 260
            if ($matched) {
229 232
                foreach ($except as $category) {
230 1
                    $prefix = rtrim($category, '*');
231 1
                    if (($message[2] === $category || $prefix !== $category) && strpos($message[2], $prefix) === 0) {
232 1
                        $matched = false;
233 1
                        break;
234
                    }
235
                }
236
            }
237
238 260
            if (!$matched) {
239 260
                unset($messages[$i]);
240
            }
241
        }
242
243 335
        return $messages;
244
    }
245
246
    /**
247
     * Formats a log message for display as a string.
248
     * @param array $message the log message to be formatted.
249
     * The message structure follows that in [[Logger::messages]].
250
     * @return string the formatted message
251
     */
252 2
    public function formatMessage($message)
253
    {
254 2
        list($text, $level, $category, $timestamp) = $message;
255 2
        $level = Logger::getLevelName($level);
256 2
        if (!is_string($text)) {
257
            // exceptions may not be serializable if in the call stack somewhere is a Closure
258
            if ($text instanceof \Throwable || $text instanceof \Exception) {
259
                $text = (string) $text;
260
            } else {
261
                $text = VarDumper::export($text);
262
            }
263
        }
264 2
        $traces = [];
265 2
        if (isset($message[4])) {
266 2
            foreach ($message[4] as $trace) {
267
                $traces[] = "in {$trace['file']}:{$trace['line']}";
268
            }
269
        }
270
271 2
        $prefix = $this->getMessagePrefix($message);
272 2
        return date('Y-m-d H:i:s', $timestamp) . " {$prefix}[$level][$category] $text"
273 2
            . (empty($traces) ? '' : "\n    " . implode("\n    ", $traces));
274
    }
275
276
    /**
277
     * Returns a string to be prefixed to the given message.
278
     * If [[prefix]] is configured it will return the result of the callback.
279
     * The default implementation will return user IP, user ID and session ID as a prefix.
280
     * @param array $message the message being exported.
281
     * The message structure follows that in [[Logger::messages]].
282
     * @return string the prefix string
283
     */
284 8
    public function getMessagePrefix($message)
285
    {
286 8
        if ($this->prefix !== null) {
287
            return call_user_func($this->prefix, $message);
288
        }
289
290 8
        if (Yii::$app === null) {
291
            return '';
292
        }
293
294 8
        $request = Yii::$app->getRequest();
295 8
        $ip = $request instanceof Request ? $request->getUserIP() : '-';
296
297
        /* @var $user \yii\web\User */
298 8
        $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
299 8
        if ($user && ($identity = $user->getIdentity(false))) {
300
            $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...
301
        } else {
302 8
            $userID = '-';
303
        }
304
305
        /* @var $session \yii\web\Session */
306 8
        $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
307 8
        $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
308
309 8
        return "[$ip][$userID][$sessionID]";
310
    }
311
312
    /**
313
     * Sets a value indicating whether this log target is enabled.
314
     * @param bool|callable $value a boolean value or a callable to obtain the value from.
315
     * The callable value is available since version 2.0.13.
316
     *
317
     * A callable may be used to determine whether the log target should be enabled in a dynamic way.
318
     * For example, to only enable a log if the current user is logged in you can configure the target
319
     * as follows:
320
     *
321
     * ```php
322
     * 'enabled' => function() {
323
     *     return !Yii::$app->user->isGuest;
324
     * }
325
     * ```
326
     */
327 1
    public function setEnabled($value)
328
    {
329 1
        $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...
330 1
    }
331
332
    /**
333
     * Check whether the log target is enabled.
334
     * @property Indicates whether this log target is enabled. Defaults to true.
335
     * @return bool A value indicating whether this log target is enabled.
336
     */
337 336
    public function getEnabled()
338
    {
339 336
        if (is_callable($this->_enabled)) {
340 1
            return call_user_func($this->_enabled, $this);
341
        }
342
343 336
        return $this->_enabled;
344
    }
345
}
346