bupy7 / yii2-activerecord-history

This extension adds storage history of changes to the ActiveRecord model.
26 stars 17 forks source link

Error when running inserts from console #2

Closed maxxer closed 8 years ago

maxxer commented 8 years ago

When running AR creation from console commands the behavior returns error

Exception: Calling unknown method: yii\console\Application::getSession() (/home/maxxer/vendor/yiisoft/yii2/base/Component.php:285)
#0 /home/maxxer/vendor/yiisoft/yii2/web/User.php(657): yii\base\Component->__call('getSession', Array)
#1 /home/maxxer/vendor/yiisoft/yii2/web/User.php(188): yii\web\User->renewAuthStatus()
#2 /home/maxxer/vendor/yiisoft/yii2/web/User.php(350): yii\web\User->getIdentity()
#3 /home/maxxer/vendor/yiisoft/yii2/base/Component.php(130): yii\web\User->getId()
#4 /home/maxxer/vendor/bupy7/yii2-activerecord-history/behaviors/History.php(194): yii\base\Component->__get('id')
#5 /home/maxxer/vendor/bupy7/yii2-activerecord-history/behaviors/History.php(105): bupy7\activerecord\history\behaviors\History->getCreatedBy()
#6 [internal function]: bupy7\activerecord\history\behaviors\History->saveHistory(Object(yii\db\AfterSaveEvent))
maxxer commented 8 years ago

Possible fix:

11:50 $ diff -Naur vendor/bupy7/yii2-activerecord-history/behaviors/History_orig.php vendor/bupy7/yii2-activerecord-history/behaviors/History.php --- vendor/bupy7/yii2-activerecord-history/behaviors/History_orig.php 2016-10-05 11:49:56.683069585 +0200
+++ vendor/bupy7/yii2-activerecord-history/behaviors/History.php    2016-10-05 11:04:15.699624100 +0200
@@ -100,6 +100,8 @@
      */
     public function saveHistory(Event $event)
     {   
+        if(is_a(Yii::$app,'yii\console\Application'))
+            return;
         $rowId = $this->getRowId();
         $tableName = $this->getTableName();
         $createdBy = $this->getCreatedBy();
bupy7 commented 8 years ago

@maxxer No. Need ID of an user. This is a mandatory requirement. You need authenticated an user in console or don't use history.

maxxer commented 8 years ago

The same happens with Blameable Behavior they say, but they allow to set the value to be used, in case Yii::$app->user is not available.

maxxer commented 8 years ago

I should create a fake console user component implementing \yii\web\User that must return something to the ->id getter?

bupy7 commented 8 years ago

Make a service user and run below code before some action:

$identity = \app\models\User::findIdentity('<service_user_id>');
if ($identity === null) {
   throw new ForbiddenHttpException;
}
\Yii::$app->user->setIdentity($identity); 

Set custom user will be to future functional.

maxxer commented 8 years ago

ok thanks...