Completed
Push — 2.1 ( 83fa82...a136f4 )
by
unknown
12:35
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 Psr\Log\LogLevel;
11
use Yii;
12
use yii\base\Component;
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
 * For more details and usage information on Target, see the [guide article on logging & targets](guide:runtime-logging).
29
 *
30
 * @property bool $enabled Whether to enable this log target. Defaults to true.
31
 * 
32
 * @author Qiang Xue <[email protected]>
33
 * @since 2.0
34
 */
35
abstract class Target extends Component
36
{
37
    /**
38
     * @var array list of message categories that this target is interested in. Defaults to empty, meaning all categories.
39
     * You can use an asterisk at the end of a category so that the category may be used to
40
     * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
41
     * categories starting with 'yii\db\', such as `yii\db\Connection`.
42
     */
43
    public $categories = [];
44
    /**
45
     * @var array list of message categories that this target is NOT interested in. Defaults to empty, meaning no uninteresting messages.
46
     * If this property is not empty, then any category listed here will be excluded from [[categories]].
47
     * You can use an asterisk at the end of a category so that the category can be used to
48
     * match those categories sharing the same common prefix. For example, 'yii\db\*' will match
49
     * categories starting with 'yii\db\', such as `yii\db\Connection`.
50
     * @see categories
51
     */
52
    public $except = [];
53
    /**
54
     * @var array the message levels that this target is interested in.
55
     *
56
     * The parameter should be an array of interested level names. See [[LogLevel]] constants for valid level names.
57
     *
58
     * For example:
59
     *
60
     * ```php
61
     * ['error', 'warning'],
62
     * // or
63
     * [LogLevel::ERROR, LogLevel::WARNING]
64
     * ```
65
     *
66
     * Defaults is empty array, meaning all available levels.
67
     */
68
    public $levels = [];
69
    /**
70
     * @var array list of the PHP predefined variables that should be logged in a message.
71
     * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be logged.
72
     *
73
     * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER']`.
74
     *
75
     * Since version 2.0.9 additional syntax can be used:
76
     * Each element could be specified as one of the following:
77
     *
78
     * - `var` - `var` will be logged.
79
     * - `var.key` - only `var[key]` key will be logged.
80
     * - `!var.key` - `var[key]` key will be excluded.
81
     *
82
     * @see \yii\helpers\ArrayHelper::filter()
83
     */
84
    public $logVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION', '_SERVER'];
85
    /**
86
     * @var callable a PHP callable that returns a string to be prefixed to every exported message.
87
     *
88
     * If not set, [[getMessagePrefix()]] will be used, which prefixes the message with context information
89
     * such as user IP, user ID and session ID.
90
     *
91
     * The signature of the callable should be `function ($message)`.
92
     */
93
    public $prefix;
94
    /**
95
     * @var int how many messages should be accumulated before they are exported.
96
     * Defaults to 1000. Note that messages will always be exported when the application terminates.
97
     * Set this property to be 0 if you don't want to export messages until the application terminates.
98
     */
99
    public $exportInterval = 1000;
100
    /**
101
     * @var array the messages that are retrieved from the logger so far by this log target.
102
     * Please refer to [[Logger::messages]] for the details about the message structure.
103
     */
104
    public $messages = [];
105
106
    /**
107
     * @var bool
108
     */
109
    private $_enabled = true;
110
111
112
    /**
113
     * Exports log [[messages]] to a specific destination.
114
     * Child classes must implement this method.
115
     */
116
    abstract public function export();
117
118
    /**
119
     * Processes the given log messages.
120
     * This method will filter the given messages with [[levels]] and [[categories]].
121
     * And if requested, it will also export the filtering result to specific medium (e.g. email).
122
     * @param array $messages log messages to be processed. See [[Logger::messages]] for the structure
123
     * of each message.
124
     * @param bool $final whether this method is called at the end of the current application
125
     */
126 334
    public function collect($messages, $final)
127
    {
128 334
        $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->levels, $this->categories, $this->except));
129 334
        $count = count($this->messages);
130 334
        if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) {
131 25
            if (($context = $this->getContextMessage()) !== '') {
132 6
                $this->messages[] = [LogLevel::INFO, $context, ['category' => 'application', 'time' => YII_BEGIN_TIME]];
133
            }
134
            // set exportInterval to 0 to avoid triggering export again while exporting
135 25
            $oldExportInterval = $this->exportInterval;
136 25
            $this->exportInterval = 0;
137 25
            $this->export();
138 25
            $this->exportInterval = $oldExportInterval;
139
140 25
            $this->messages = [];
141
        }
142 334
    }
143
144
    /**
145
     * Generates the context information to be logged.
146
     * The default implementation will dump user information, system variables, etc.
147
     * @return string the context information. If an empty string, it means no context information.
148
     */
149 26
    protected function getContextMessage()
150
    {
151 26
        $context = ArrayHelper::filter($GLOBALS, $this->logVars);
152 26
        $result = [];
153 26
        foreach ($context as $key => $value) {
154 7
            $result[] = "\${$key} = " . VarDumper::dumpAsString($value);
155
        }
156
157 26
        return implode("\n\n", $result);
158
    }
159
160
    /**
161
     * Filters the given messages according to their categories and levels.
162
     * @param array $messages messages to be filtered.
163
     * The message structure follows that in [[Logger::messages]].
164
     * @param array $levels the message levels to filter by. Empty value means allowing all levels.
165
     * @param array $categories the message categories to filter by. If empty, it means all categories are allowed.
166
     * @param array $except the message categories to exclude. If empty, it means all categories are allowed.
167
     * @return array the filtered messages.
168
     */
169 334
    public static function filterMessages($messages, $levels = [], $categories = [], $except = [])
170
    {
171 334
        foreach ($messages as $i => $message) {
172 334
            if (!empty($levels) && !in_array($message[0], $levels, true)) {
173 321
                unset($messages[$i]);
174 321
                continue;
175
            }
176
177 266
            $matched = empty($categories);
178 266
            foreach ($categories as $category) {
179 245
                if ($message[2]['category'] === $category || !empty($category) && substr_compare($category, '*', -1, 1) === 0 && strpos($message[2]['category'], rtrim($category, '*')) === 0) {
180 217
                    $matched = true;
181 245
                    break;
182
                }
183
            }
184
185 266
            if ($matched) {
186 239
                foreach ($except as $category) {
187 1
                    $prefix = rtrim($category, '*');
188 1
                    if (($message[2]['category'] === $category || $prefix !== $category) && strpos($message[2]['category'], $prefix) === 0) {
189 1
                        $matched = false;
190 1
                        break;
191
                    }
192
                }
193
            }
194
195 266
            if (!$matched) {
196 266
                unset($messages[$i]);
197
            }
198
        }
199
200 334
        return $messages;
201
    }
202
203
    /**
204
     * Formats a log message for display as a string.
205
     * @param array $message the log message to be formatted.
206
     * The message structure follows that in [[Logger::messages]].
207
     * @return string the formatted message
208
     */
209 2
    public function formatMessage($message)
210
    {
211 2
        [$level, $text, $context] = $message;
0 ignored issues
show
Bug introduced by
The variable $level seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Bug introduced by
The variable $text does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $context does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
212 2
        $category = $context['category'];
213 2
        $timestamp = $context['time'];
214 2
        $level = Logger::getLevelName($level);
0 ignored issues
show
Bug introduced by
The variable $level seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
215 2
        $traces = [];
216 2
        if (isset($context['trace'])) {
217 2
            foreach ($context['trace'] as $trace) {
218
                $traces[] = "in {$trace['file']}:{$trace['line']}";
219
            }
220
        }
221
222 2
        $prefix = $this->getMessagePrefix($message);
223 2
        return date('Y-m-d H:i:s', $timestamp) . " {$prefix}[$level][$category] $text"
224 2
            . (empty($traces) ? '' : "\n    " . implode("\n    ", $traces));
225
    }
226
227
    /**
228
     * Returns a string to be prefixed to the given message.
229
     * If [[prefix]] is configured it will return the result of the callback.
230
     * The default implementation will return user IP, user ID and session ID as a prefix.
231
     * @param array $message the message being exported.
232
     * The message structure follows that in [[Logger::messages]].
233
     * @return string the prefix string
234
     */
235 8
    public function getMessagePrefix($message)
236
    {
237 8
        if ($this->prefix !== null) {
238
            return call_user_func($this->prefix, $message);
239
        }
240
241 8
        if (Yii::$app === null) {
242
            return '';
243
        }
244
245 8
        $request = Yii::$app->getRequest();
246 8
        $ip = $request instanceof Request ? $request->getUserIP() : '-';
247
248
        /* @var $user \yii\web\User */
249 8
        $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
250 8
        if ($user && ($identity = $user->getIdentity(false))) {
251
            $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...
252
        } else {
253 8
            $userID = '-';
254
        }
255
256
        /* @var $session \yii\web\Session */
257 8
        $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
258 8
        $sessionID = $session && $session->getIsActive() ? $session->getId() : '-';
259
260 8
        return "[$ip][$userID][$sessionID]";
261
    }
262
263
    /**
264
     * Sets a value indicating whether this log target is enabled.
265
     * @param bool|callable $value a boolean value or a callable to obtain the value from.
266
     * The callable value is available since version 2.0.13.
267
     *
268
     * A callable may be used to determine whether the log target should be enabled in a dynamic way.
269
     * For example, to only enable a log if the current user is logged in you can configure the target
270
     * as follows:
271
     *
272
     * ```php
273
     * 'enabled' => function() {
274
     *     return !Yii::$app->user->isGuest;
275
     * }
276
     * ```
277
     */
278 1
    public function setEnabled($value)
279
    {
280 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...
281 1
    }
282
283
    /**
284
     * Check whether the log target is enabled.
285
     * @property Indicates whether this log target is enabled. Defaults to true.
286
     * @return bool A value indicating whether this log target is enabled.
287
     */
288 335
    public function getEnabled()
289
    {
290 335
        if (is_callable($this->_enabled)) {
291 1
            return call_user_func($this->_enabled, $this);
292
        }
293
294 335
        return $this->_enabled;
295
    }
296
}
297