Skip to content

Commit 392f9f8

Browse files
fix: handle setting userID for console applications
1 parent c21d095 commit 392f9f8

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

behaviors/LoggingBehavior.php

+14-1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ class LoggingBehavior extends Behavior {
2727
'expire' => 'log_expire',
2828
];
2929

30+
/**
31+
* @var mixed : Value to use as userID during a console application. Be aware of relations/MySQL JOIN queries though - might want to use `null` for that reason.
32+
*/
33+
public $consoleUserID = 0; //default to 0 since we assume a normal user will never have ID 0 (at least never should)
34+
3035
/**
3136
* @var array : Exclude logging these events. Currently these are available: `insert`, `update`, `delete`
3237
*/
@@ -161,7 +166,15 @@ public function logChanges($event) {
161166
}
162167

163168
if ($event->name !== ActiveRecord::EVENT_AFTER_UPDATE || $this->logUpdateIfNoChanges || !empty($logAttributes[ $attrMap['data'] ])) {
164-
$logAttributes[ $attrMap['userID'] ] = (\Yii::$app->user->isGuest ? null : \Yii::$app->user->identity->id);
169+
if (\Yii::$app->request->isConsoleRequest) { //in a console app the user component normally will not exist
170+
if (!\Yii::$app->has('user') || \Yii::$app->user->isGuest) {
171+
$logAttributes[ $attrMap['userID'] ] = $this->consoleUserID;
172+
} else {
173+
$logAttributes[ $attrMap['userID'] ] = \Yii::$app->user->identity->id;
174+
}
175+
} else {
176+
$logAttributes[ $attrMap['userID'] ] = (\Yii::$app->user->isGuest ? null : \Yii::$app->user->identity->id);
177+
}
165178
$logAttributes[ $attrMap['model'] ] = $modelClass;
166179
$logAttributes[ $attrMap['modelID'] ] = $id;
167180
$logAttributes[ $attrMap['action'] ] = $action;

0 commit comments

Comments
 (0)