예제 #1
1
 public static function delete($id)
 {
     $response = new Response();
     $transactionManager = new TransactionManager();
     $transaction = $transactionManager->get();
     try {
         $products = Products::findByCategoryId($id);
         $products->setTransaction($transaction);
         $products->delete();
         $response->data = Categories::findFirst($id)->delete();
         $transaction->commit();
     } catch (Exception $e) {
         $transaction->rollback("Can't delete");
         $response->setException($e);
     } finally {
         return $response->toArray();
     }
 }
예제 #2
1
 /**
  * 存储完整意见--$comments
  */
 public static function insertComment($array, $examinee_id, $manager_id)
 {
     try {
         $manager = new TxManager();
         $transaction = $manager->get();
         $interview = Interview::findFirst(array('manager_id=?0 and examinee_id=?1', 'bind' => array(0 => $manager_id, 1 => $examinee_id)));
         $interview->setTransaction($transaction);
         $advantage = array('advantage1' => $array['advantage1'], 'advantage2' => $array['advantage2'], 'advantage3' => $array['advantage3'], 'advantage4' => $array['advantage4'], 'advantage5' => $array['advantage5']);
         $interview->advantage = json_encode($advantage, JSON_UNESCAPED_UNICODE);
         $disadvantage = array('disadvantage1' => $array['disadvantage1'], 'disadvantage2' => $array['disadvantage2'], 'disadvantage3' => $array['disadvantage3']);
         $interview->disadvantage = json_encode($disadvantage, JSON_UNESCAPED_UNICODE);
         $interview->remark = $array['remark'];
         $examinee = Examinee::findFirst($examinee_id);
         $examinee->setTransaction($transaction);
         $examinee->state = 5;
         if ($interview->save() == false || $examinee->save() == false) {
             $transaction->rollback("数据插入失败");
         }
         $transaction->commit();
         return true;
     } catch (TxFailed $e) {
         throw new Exception($e->getMessage());
     }
 }
예제 #3
0
 public static function create($user)
 {
     $manager = new TransactionManager();
     $transaction = $manager->get();
     $user->setTransaction($transaction);
     if (true !== $user->create()) {
         $transaction->rollback("create user failed");
         return false;
     }
     $userId = sprintf("%s='%s'", MyConst::FIELD_EMAIL, $user->email);
     $user = MaUser::findFirst($userId);
     if (empty($user)) {
         $transaction->rollback("cannot find user created");
         return false;
     }
     $myspace = new MaTeam();
     $myspace->setTransaction($transaction);
     $myspace->owner = $user->id;
     $myspace->name = 'MyMate';
     $myspace->mission = 'Record My Growths';
     $myspace->flag = MyConst::TEAM_FLAG_MYSPACE;
     if (true !== $myspace->create()) {
         $transaction->rollback("create myspace failed");
         return false;
     }
     $mymate = new MaTeam();
     $mymate->setTransaction($transaction);
     $mymate->owner = $user->id;
     $mymate->name = 'MyMate';
     $mymate->mission = 'Follow and Share Growths With My Closest Friends';
     $mymate->flag = MyConst::TEAM_FLAG_MYMATE;
     if (true !== $mymate->create()) {
         $transaction->rollback("create mymate failed");
         return false;
     }
     $mentora = new MaTeam();
     $mentora->setTransaction($transaction);
     $mentora->owner = $user->id;
     $mentora->name = 'Mentors';
     $mentora->flag = MyConst::TEAM_FLAG_MENTOR;
     if (true !== $mentora->create()) {
         $transaction->rollback("create mentora failed");
         return false;
     }
     $newbie = new MaTeam();
     $newbie->setTransaction($transaction);
     $newbie->owner = $user->id;
     $newbie->name = 'Students';
     $newbie->flag = MyConst::TEAM_FLAG_MENTOR;
     if (true !== $newbie->create()) {
         $transaction->rollback("create newbie failed");
         return false;
     }
     $transaction->commit();
     return true;
 }
예제 #4
0
 /**
  * 更新Examinee表中的other选项
  * @param json $json
  * @param Examinee:findFirst(id); $examinee
  * @throws Exception
  * @return boolean
  */
 public static function unpdateOther($json, $examinee)
 {
     try {
         $manager = new TxManager();
         $transaction = $manager->get();
         $examinee->setTransaction($transaction);
         $examinee->other = $json;
         if ($examinee->save() == false) {
             $transaction->rollback("插入数据库失败-" . print_r($array, true));
         }
         $transaction->commit();
         return true;
     } catch (TxFailed $e) {
         throw new Exception($e->getMessage());
     }
 }
예제 #5
0
 /**
  * Begin a transaction
  * @return void
  * @throws \Exception
  */
 public function begin()
 {
     if ($this->isInTransaction()) {
         throw new \Exception('You cannot start a new transaction once you are already in one (Originally started at: ' . self::$stackTrace . ')');
     } else {
         $e = new \Exception();
         self::$stackTrace = $e->getTraceAsString();
     }
     $transactionManager = new TransactionManager();
     $transactionManager->setDbService($this->getDbService());
     $this->setTransaction($transactionManager->get());
 }
예제 #6
0
 public function collectTransactions()
 {
     parent::collectTransactions();
 }
<?php

use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
try {
    $txManager = new TxManager();
    $transaction = $txManager->get();
    $robot = new Robots();
    $robot->setTransaction($transaction);
    $robot->name = 'WALL·E';
    $robot->created_at = date('Y-m-d');
    if ($robot->save() == false) {
        $transaction->rollback("Can't save robot");
    }
    $robotPart = new RobotParts();
    $robotPart->setTransaction($transaction);
    $robotPart->type = 'head';
    if ($robotPart->save() == false) {
        $transaction->rollback("Robot part cannot be saved");
    }
    $transaction->commit();
} catch (TxFailed $e) {
    echo 'Failed, reason: ', $e->getMessage();
}
예제 #8
0
 /**
  * @usage 完成基础得分计算后的被试状态转换
  * @param int $examinee_id
  * @throws Exception
  * @return boolean
  */
 public static function finishedBasic($examinee_id)
 {
     $examinee_info = Examinee::findFirst(array("id = :id:", 'bind' => array('id' => $examinee_id)));
     #如果examinee_id为空,这种处理也合适
     if (isset($examinee_info->id)) {
         try {
             $manager = new TxManager();
             $transaction = $manager->get();
             $examinee_info->setTransaction($transaction);
             $examinee_info->state = 2;
             if ($examinee_info->save() == false) {
                 $transaction->rollback(self::$error_state . '-数据库插入失败-' . print_r($examinee_info, true));
             }
             $transaction->commit();
             return true;
         } catch (TxFailed $e) {
             throw new Exception($e->getMessage());
         }
     } else {
         throw new Exception(self::$error_state . '-不存在该账号的用户-' . $examinee_id);
     }
 }
예제 #9
0
 /**
  * @param int $userId
  * @param string $newPassword
  * @param null $resetPasswordToken token to expire if call is from password reset
  * @return bool
  * @throws PasswordChangeException
  */
 public function updatePassword($userId, $newPassword, $resetPasswordToken = null)
 {
     $transactionManager = new TransactionManager();
     try {
         //use a transaction as we would be updating more than one table
         $transaction = $transactionManager->get();
         $this->setTransaction($transaction);
         $user = User::findFirst($userId);
         if ($user == false) {
             $transaction->rollback(ErrorMessages::PASSWORD_UPDATE_FAILED);
         }
         $previousPassword = $user->password;
         $user->password = Utils::encryptPassword($newPassword);
         if (!$user->save()) {
             $transaction->rollback(ErrorMessages::PASSWORD_UPDATE_FAILED);
         }
         $userPasswordChange = new UserPasswordChange();
         $userPasswordChange->setTransaction($transaction);
         $userPasswordChange->setDateChanged(date("Y-m-d H:i:s"));
         $userPasswordChange->setUserId($userId);
         $userPasswordChange->setPasswordHash($previousPassword);
         if (!$userPasswordChange->save()) {
             $transaction->rollback(ErrorMessages::PASSWORD_UPDATE_FAILED);
         }
         if (!empty($resetPasswordToken) && !(new UserPasswordReset())->expireToken($resetPasswordToken)) {
             $transaction->rollback(ErrorMessages::TOKEN_EXPIRY_FAILED);
         }
         $transaction->commit();
         return true;
     } catch (TransactionFailed $e) {
         throw new PasswordChangeException($e->getMessage());
     }
 }
예제 #10
0
<?php

use Phalcon\Mvc\Model\Transaction\Manager as TxManager, Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
try {
    //Create a transaction manager
    $manager = new TxManager();
    //Request a transaction
    $transaction = $manager->get();
    //Get the robots will be deleted
    foreach (Robots::find("type = 'mechanical'") as $robot) {
        $robot->setTransaction($transaction);
        if ($robot->delete() == false) {
            //Something goes wrong, we should to rollback the transaction
            foreach ($robot->getMessages() as $message) {
                $transaction->rollback($message->getMessage());
            }
        }
    }
    //Everything goes fine, let's commit the transaction
    $transaction->commit();
    echo "Robots were deleted successfully!";
} catch (TxFailed $e) {
    echo "Failed, reason: ", $e->getMessage();
}
예제 #11
0
 /**
  * Init engine.
  *
  * @param DI $di Dependency Injection.
  *
  * @return void
  */
 protected function _initEngine($di)
 {
     $di->setShared('transactions', function () {
         $manager = new TxManager();
         return $manager->setDbService("dbMaster");
     });
 }
예제 #12
0
 public static function insertMiddle($data)
 {
     try {
         $manager = new TxManager();
         $transaction = $manager->get();
         foreach ($data as $key => $value) {
             $middle = new MiddleLayer();
             $middle->setTransaction($transaction);
             foreach ($value as $skey => $svalue) {
                 $middle->{$skey} = $svalue;
             }
             if ($middle->save() == false) {
                 $transaction->rollback('数据更新失败-3');
             }
         }
         $transaction->commit();
         return true;
     } catch (TxFailed $e) {
         throw new Exception($e->getMessage());
     }
 }
예제 #13
0
 /**
  * Deletes an existing product
  */
 public function deleteAction($id)
 {
     if (!parent::isValidId($id)) {
         return parent::redirect('batch');
     }
     $manager = new TransactionManager();
     $transaction = $manager->get();
     try {
         $batch = Batch::findFirst($id);
         if ($batch) {
             $batch->setTransaction($transaction);
             # delete dependencies
             $pings = $batch->getPing();
             foreach ($pings as $ping) {
                 $ping->setTransaction($transaction);
                 $ping->delete();
             }
             $batch->delete();
             $this->flash->success('Batch deleted succesfully.');
             $transaction->commit();
         } else {
             $this->flash->notice('Batch not found, operation aborted.');
         }
     } catch (\Exception $ex) {
         $this->flash->error('Error deleting batch.');
         $transaction->rollback();
     }
     return $this->redirect('batch');
 }
예제 #14
0
 /**
  * Deletes an existing product
  */
 public function deleteAction($id)
 {
     if (!parent::isValidId($id)) {
         return parent::redirect('country');
     }
     $manager = new TransactionManager();
     $transaction = $manager->get();
     try {
         $proxy = Proxy::findFirst($id);
         if ($proxy) {
             $proxy->setTransaction($transaction);
             $pings = $proxy->getPing();
             foreach ($pings as $ping) {
                 $ping->setTransaction($transaction);
                 $ping->delete();
             }
             $proxy->delete();
             $this->flash->success('Proxy deleted succesfully.');
             $transaction->commit();
         } else {
             $this->flash->notice('Proxy not found, operation aborted.');
         }
     } catch (\Exception $ex) {
         $this->flash->error('Error deleting proxy.');
         $transaction->rollback();
     }
     return $this->redirect('proxy');
 }
예제 #15
0
 /**
  * public $NLL;
  * public $NLH;
  * public $B95;
  * public $B90;
  * public $B75;
  * public $B50;
  * public $B25;
  * public $B10;
  * public $B5;
  */
 private static function startMysqlSpmmdMemory()
 {
     $spmmd_first = SpmmdMemory::findFirst();
     if (isset($spmmd_first->NLL)) {
         return true;
     } else {
         try {
             $manager = new TxManager();
             $transaction = $manager->get();
             $spmmd_data = Spmmd::find();
             foreach ($spmmd_data as $spmmd_record) {
                 $spmmd_memory = new SpmmdMemory();
                 $spmmd_memory->setTransaction($transaction);
                 $spmmd_memory->NLL = $spmmd_record->NLL;
                 $spmmd_memory->NLH = $spmmd_record->NLH;
                 $spmmd_memory->B95 = $spmmd_record->B95;
                 $spmmd_memory->B90 = $spmmd_record->B90;
                 $spmmd_memory->B75 = $spmmd_record->B75;
                 $spmmd_memory->B50 = $spmmd_record->B50;
                 $spmmd_memory->B25 = $spmmd_record->B25;
                 $spmmd_memory->B10 = $spmmd_record->B10;
                 $spmmd_memory->B5 = $spmmd_record->B5;
                 if ($spmmd_memory->create() == false) {
                     unset($ksmd_data);
                     $transaction->rollback("SPMMD DATA INSERT INTO MEMORY TABLE ERROR!");
                 }
             }
             if (isset($spmmd_data)) {
                 unset($spmmd_data);
             }
             $transaction->commit();
             return true;
         } catch (TxFailed $e) {
             throw new Exception("Failed, reason: " . $e->getMessage());
         }
     }
 }
예제 #16
0
 public function ajaxReload($args)
 {
     $manager = new TransactionManager();
     $transaction = $manager->get();
     $id = $args->id;
     try {
         $result = PingHelper::reload($id);
         if ($result) {
             $payload['success'] = true;
             $payload['message'] = 'Ping reloaded succesfully.';
             $payload['payload'] = array('httpCode' => $result['httpCode'], 'duration' => $result['duration'], 'error' => $result['error']);
         } else {
             $payload['success'] = false;
             $payload['message'] = 'Ping not found.';
         }
         $payload['payload'] += array('id' => $id);
     } catch (\Exception $ex) {
         $transaction->rollback();
         $payload['success'] = false;
         $payload['message'] = 'Error reloading ping.';
         $payload['payload'] = array('id' => $id);
     }
     return $payload;
 }
예제 #17
0
 /**
  * 取消面询分配
  */
 public static function delallocExaminees($data, $interviewer_id)
 {
     try {
         $manager = new TxManager();
         $transaction = $manager->get();
         foreach ($data as $value) {
             $interview = Interview::findFirst(array('examinee_id = ?1 AND manager_id = ?2', 'bind' => array(1 => $value, 2 => $interviewer_id)));
             if (!isset($interview->examinee_id)) {
                 continue;
             }
             $interview->setTransaction($transaction);
             if ($interview->delete() == false) {
                 $transaction->rollback("数据删除失败");
             }
         }
         $transaction->commit();
         return true;
     } catch (TxFailed $e) {
         throw new Exception($e->getMessage());
     }
 }
예제 #18
0
 /**
  * Main processing script
  *
  * @throws Exception
  */
 public function processAction()
 {
     $this->view->disable();
     if ($this->request->isAjax()) {
         // Set transaction manager
         $transactionManager = new TransactionManager();
         $transaction = $transactionManager->get();
         $root = $this->root;
         $upload_dir_full = $this->upload_dir_full;
         $processed_dir = $this->processed_dir;
         // Create processed folder if it doesn't exist
         if (!file_exists($processed_dir)) {
             mkdir($processed_dir, 0777, true);
         }
         $qrs = $this->persistent->qrs;
         $errors = $this->persistent->errors;
         $created_prods_counter = $this->persistent->created_prods_counter;
         $created_prods_ids = $this->persistent->created_prods_ids;
         $id = $this->request->get('id');
         $item = self::filter($upload_dir_full, "{$id}")[$id];
         // A product must have a minimum of 3 photos
         if (count($item, true) - 1 < 4) {
             $this->errorExit($errors, $id, "У товара должно быть минимум три фотографии!");
         }
         // Check for file name (should not contain alphabetic characters)
         foreach ($item as $i => $f) {
             if (preg_match_all('/[A-Za-z]+\\d*\\./', "{$upload_dir_full}/{$f}")) {
                 $this->errorExit($errors, $id, "Неправильное название файла ({$f})");
             }
         }
         // QR code image
         $qrcode_img = $item[0];
         // Get scanned QR code
         if ($qrs[$id] != false) {
             $code = $qrs[$id];
         } else {
             $this->errorExit($errors, $id, "Не удалось отсканировать QR код ({$qrcode_img})");
         }
         // Check for product existence
         if (PProductMain::findFirst($code)) {
             $this->errorExit($errors, $id, "Товар с таким QR кодом уже внесен в базу ({$code})");
         }
         // -----------------------------------------------------------
         // QR code processing
         $qrcode_info = pathinfo($qrcode_img);
         $qrcode_name = "{$qrcode_info['filename']}qr{$code}";
         $qrcode_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
         $width = getimagesize("{$upload_dir_full}/{$qrcode_img}")[0];
         $height = getimagesize("{$upload_dir_full}/{$qrcode_img}")[1];
         $filesize = filesize("{$upload_dir_full}/{$qrcode_img}");
         // Create folders for a QR code
         mkdir($root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder, 0777, true);
         mkdir($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder, 0777, true);
         // Copy QR code image to the respective folder
         if (!copy("{$upload_dir_full}/{$qrcode_img}", $root . $this->config->upload->media_qrcodeimage_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения QR кода ({$qrcode_img})");
         }
         $qrimg = new SimpleImage("{$upload_dir_full}/{$qrcode_img}");
         // Resize QR code image for a thumbnail (100 px) and copy it to nail folder
         if (!$qrimg->fit_to_width(100)->save($root . $this->config->upload->media_qrcodeimage_nail_folder . "/" . $qrcode_folder . $qrcode_name . "." . $qrcode_info['extension'])) {
             $this->errorExit($errors, $id, "Ошибка при копировании изображения (nail) QR кода ({$qrcode_img})");
         }
         // Add QR code to the db
         $qrcode = new PProdQrcodeimage();
         $qrcode->setTransaction($transaction);
         $qrcode->product_id = $code;
         $qrcode->uri = $qrcode_name;
         $qrcode->ext = $qrcode_info['extension'];
         $qrcode->width = $width;
         $qrcode->height = $height;
         $qrcode->filesize = $filesize;
         $qrcode->folder = $qrcode_folder;
         $qrcode->thumbnail = "/thumb/qrcodeimage/nail/{$qrcode_folder}{$qrcode_name}.{$qrcode_info['extension']}";
         $qrcode->ordered = $qrcode->ordered();
         $qrcode->created = time();
         $qrcode->updated = time();
         if (!$qrcode->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при добавлении QR кода в базу данных ({$qrcode_img})");
         }
         // Remove QR code from the array
         array_shift($item);
         // -----------------------------------------------------------
         // Photos processing
         $photo_counter = 1;
         foreach ($item as $img) {
             // A product can have a maximum of 5 photos
             if ($photo_counter > 5) {
                 break;
             }
             // Change photo orientation if needed
             //                self::changeOrientation("$upload_dir_full/$img");
             $img_info = pathinfo($img);
             $rand = rand(1111, 9999);
             $width = getimagesize("{$upload_dir_full}/{$img}")[0];
             $height = getimagesize("{$upload_dir_full}/{$img}")[1];
             $filesize = filesize("{$upload_dir_full}/{$img}");
             $img_name = "IMG_{$rand}_{$height}";
             $img_folder = rand(111, 999) . "/" . rand(1111111, 99999999) . "/";
             // Create folders
             mkdir($root . $this->config->upload->media_productphoto_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder, 0777, true);
             mkdir($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder, 0777, true);
             // Resave an image to remove EXIF data
             if (self::removeExif("{$upload_dir_full}/{$img}") == false) {
                 $this->errorExit($errors, $id, "Ошибка при обработке фотографии ({$img})");
             }
             // Copy an image to the respective folder
             if (!copy("{$upload_dir_full}/{$img}", $root . $this->config->upload->media_productphoto_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии ({$img})");
             }
             // Resize an image for a thumbnail (500 px) and copy it to thumb folder
             $thumb_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$thumb_img->fit_to_width(500)->save($root . $this->config->upload->media_productphoto_thumb_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (thumb) ({$img})");
             }
             // Resize an image for a thumbnail (100 px) and copy it to nail folder
             $nail_img = new SimpleImage("{$upload_dir_full}/{$img}");
             if (!$nail_img->fit_to_width(100)->save($root . $this->config->upload->media_productphoto_nail_folder . "/" . $img_folder . $img_name . "." . $img_info['extension'])) {
                 $this->errorExit($errors, $id, "Ошибка при копировании фотографии (nail) ({$img})");
             }
             // Add image to the db
             $imgdb = new PProdPhoto();
             $imgdb->setTransaction($transaction);
             $imgdb->uri = $img_name;
             $imgdb->ext = $img_info['extension'];
             $imgdb->width = $width;
             $imgdb->height = $height;
             $imgdb->filesize = $filesize;
             $imgdb->folder = $img_folder;
             $imgdb->thumbnail = "/thumb/productphoto/nail/{$img_folder}{$img_name}.{$img_info['extension']}";
             $imgdb->product_id = $code;
             $imgdb->ordered = $photo_counter;
             $imgdb->created = time();
             $imgdb->updated = time();
             if (!$imgdb->create()) {
                 $transactionManager->collectTransactions();
                 // Clear transactions
                 $this->errorExit($errors, $id, "Ошибка при добавлении фотографий в базу данных ({$img})");
             }
             $photo_counter++;
         }
         // Create a new product
         $product = new PProductMain();
         $product->setTransaction($transaction);
         $product->id = $code;
         $product->created = time();
         $product->updated = time();
         $product->new = 1;
         $product->hasphoto = 1;
         $product->qrcodeimage_id = $qrcode->id;
         $product->status = 0;
         if (!$product->create()) {
             $transactionManager->collectTransactions();
             // Clear transactions
             $this->errorExit($errors, $id, "Ошибка при создании товара (QR - {$code})");
         }
         // Complete the transaction
         if (!$transaction->commit()) {
             $this->errorExit($errors, $id, "Ошибка транзакции (QR - {$code})");
         }
         // Set stats
         $this->ProdInfoService->setStat('product_created', 'photoUploader', 'ru', $code);
         // Move QR code image
         rename("{$upload_dir_full}/{$qrcode_img}", "{$processed_dir}/{$qrcode_name}.{$qrcode_info['extension']}");
         // Clear thumb for QR code img
         //            if (file_exists("$upload_dir_full/thumbs/$qrcode_img")) unlink("$upload_dir_full/thumbs/$qrcode_img");
         foreach ($item as $img) {
             // Move images
             rename("{$upload_dir_full}/{$img}", "{$processed_dir}/{$img}");
             // Clear thumbs
             //                if (file_exists("$upload_dir_full/thumbs/$img")) unlink("$upload_dir_full/thumbs/$img");
         }
         // Remove the id from QRs list
         $qrs = $this->persistent->qrs;
         unset($qrs[$id]);
         // Update counter and list of ids
         $created_prods_counter++;
         $created_prods_ids[] = $code;
         $this->persistent->qrs = $qrs;
         $this->persistent->created_prods_counter = $created_prods_counter;
         $this->persistent->created_prods_ids = $created_prods_ids;
         // Hooray!
         echo "success";
     }
 }
예제 #19
0
 /**
  * @param id
  */
 public static function delete($id)
 {
     try {
         $manager = new TransactionManager();
         $transaction = $manager->get();
         $model = self::getModel();
         $entity = $model::findFirst($id);
         $entity->setTransaction($transaction);
         if ($entity->delete() == false) {
             $transaction->rollback($entity->getMessages()[0]->message);
         }
         $transaction->commit();
         return $entity->getMessages();
     } catch (Phalcon\Mvc\Model\Transaction\Failed $e) {
         throw new CustomException($model->getMessages(), Constants::errorCode()['InternalServerError']);
     } catch (\Exception $e) {
         if (!empty($entity->getMessages())) {
             throw new CustomException($entity->getMessages(), Constants::errorCode()['InternalServerError']);
         } else {
             var_dump($e->getMessage());
             throw $e;
         }
     }
 }
예제 #20
0
 /**
  * Deletes an existing product
  */
 public function deleteAction($id)
 {
     if (!parent::isValidId($id)) {
         return parent::redirect('url');
     }
     $manager = new TransactionManager();
     $transaction = $manager->get();
     try {
         $url = Url::findFirst($id);
         if ($url) {
             $url->setTransaction($transaction);
             $batches = $url->getBatch();
             foreach ($batches as $batch) {
                 $batch->setTransaction($transaction);
                 $pings = $batch->getPing();
                 foreach ($pings as $ping) {
                     $ping->setTransaction($transaction);
                     $ping->delete();
                 }
                 $batch->delete();
             }
             $url->delete();
             $this->flash->success('Url deleted succesfully.');
             $transaction->commit();
         } else {
             $this->flash->notice('Url not found, operation aborted.');
         }
     } catch (\Exception $ex) {
         $this->flash->error('Error deleting url.');
         $transaction->rollback($ex->getMessage());
     }
     return $this->redirect('url');
 }
예제 #21
-1
 /**
  *@usage 项目创建涉及 project 及manager 
  */
 public static function addProject($project_info, $manager_info)
 {
     try {
         $manager = new TxManager();
         $transaction = $manager->get();
         #先分别存储project 和 manager
         $project = new Project();
         $project->setTransaction($transaction);
         foreach ($project_info as $key => $value) {
             $project->{$key} = $value;
         }
         $manager = new Manager();
         $manager->setTransaction($transaction);
         foreach ($manager_info as $key => $value) {
             $manager->{$key} = $value;
         }
         $manager->project_id = $project_info['id'];
         #先插入项目
         if ($project->create() == false) {
             $transaction->rollback("数据插入失败-" . print_r($project, true));
         }
         #再插入项目经理
         if ($manager->create() == false) {
             $transaction->rollback("数据删除失败-" . print_r($manager, true));
         }
         #再更新项目
         $project->manager_id = $manager->id;
         if ($project->save() == false) {
             $transaction->rollback("数据删除失败-" . print_r($project, true));
         }
         $transaction->commit();
         return true;
     } catch (TxFailed $e) {
         throw new Exception($e->getMessage());
     }
 }