Ejemplo n.º 1
0
 /**
  * @param MeritTemplate $meritTemplate
  * @throws Exception
  */
 public function update(MeritTemplate $meritTemplate)
 {
     $meritLog = new MeritLog();
     $user = \Yii::$app->user->identity;
     $transaction = \Yii::$app->db->beginTransaction();
     try {
         /** @var Merit $userMerit */
         $userMerit = Merit::findOne(['user_id' => $user->getId(), 'type' => $meritTemplate->type]);
         // is sub 判断是否是减法
         $actionSub = $meritTemplate->action_type == MeritTemplate::ACTIVE_TYPE_SUB;
         if ($userMerit) {
             $merit = call_user_func($actionSub ? 'bcsub' : 'bcadd', $userMerit->merit, $meritTemplate->increment);
             $userMerit->setAttributes(['merit' => (int) $merit]);
         } else {
             $userMerit = new Merit();
             $userMerit->setAttributes(['merit' => ($actionSub ? '-' : '') . $meritTemplate->increment, 'user_id' => $user->getId(), 'username' => $user->username, 'type' => $meritTemplate->type]);
         }
         if (!$userMerit->save()) {
             Yii::error('Merit 操作失败' . json_encode(array_values($userMerit->getFirstErrors())), 'error');
             throw new Exception(array_values($userMerit->getFirstErrors())[0]);
         }
         $description = $meritTemplate->title . ': ' . MeritTemplate::getActionTypes()[$meritTemplate->action_type] . $meritTemplate->increment . MeritTemplate::getTypes()[$meritTemplate->type];
         $meritLog->setAttributes(['user_id' => $user->getId(), 'username' => $user->username, 'merit_template_id' => $meritTemplate->id, 'type' => $meritTemplate->type, 'description' => $description, 'action_type' => $meritTemplate->action_type, 'increment' => $meritTemplate->increment, 'created_at' => time()]);
         if (!$meritLog->save()) {
             throw new Exception(array_values($meritLog->getFirstErrors())[0]);
         }
         $transaction->commit();
     } catch (Exception $e) {
         $transaction->rollBack();
     }
 }