I have the following custom TimestampBehavior:
namespace api\components;
use yii\behaviors\TimestampBehavior;
use \yii\db\Expression;
class GameTimestampBehavior extends TimestampBehavior
{
protected function getValue($event){
return new Expression('(UNIX_TIMESTAMP()-1468249200)*24-6626966400');
}
}
which is used in my model:
class User extends ActiveRecord implements IdentityInterface
{
public static function tableName()
{
return 'user';
}
public function behaviors()
{
return [
[
'class' => \api\components\GameTimestampBehavior::className()
],
];
}
public function rules()
{
return [
(...)
[['status', 'created_at', 'updated_at', 'lastLogin', 'level', 'cash'], 'integer'],
];
}
(...)
}
This very simple action works as expected, updating the update_at field:
public function actionTest(){
$user= \api\models\User::find()
->where(['id'=>1])
->one();
$user->cash++;
if($user->save()===false){
throw new \yii\web\ServerErrorHttpException(
json_encode($user->getErrors()));
}
}
However, if I try to update the register a second time like this:
public function actionTest(){
$user= \api\models\User::find()
->where(['id'=>1])
->one();
$user->cash++;
if($user->save()===false){
throw new \yii\web\ServerErrorHttpException(
json_encode($user->getErrors()));
}
$user->cash++;
if($user->save()===false){
throw new \yii\web\ServerErrorHttpException(
json_encode($user->getErrors()));
}
}
I get this exception:
Exception ‘yii\web\ServerErrorHttpException’ with message ‘{“updated_at”:[“Updated At must be an integer.”]}’
I’ve edited class NumberValidator function validateAttribute, adding an error_log(“value:”.$value); to find out why GameTimestampBehavior was not returning an integer.
This is php_error.log output:
value:10
value:-6371889432
value:56
value:10
value:(UNIX_TIMESTAMP()-1468249200)*24-6626966400
value:57
The first 3 lines refer to the first update and the other 3 to the second one.
The first update is ok, but the second one is returning GameTimestampBehavior expression without evaluating it.
I have no clue why the behavior is not working. Can anyone help me to solve this issue?