|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Pace\Services; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use SoapFault; |
| 7 | +use Throwable; |
| 8 | +use Pace\Service; |
| 9 | +use Pace\Soap\SoapClient; |
| 10 | +use Pace\Soap\Middleware\Transaction; |
| 11 | +use Pace\Soap\Middleware\StartTransaction; |
| 12 | +use Pace\Soap\Middleware\CommitTransaction; |
| 13 | +use Pace\Soap\Middleware\RollbackTransaction; |
| 14 | + |
| 15 | +class TransactionService extends Service |
| 16 | +{ |
| 17 | + /** |
| 18 | + * Wrap the specified closure in a transaction. |
| 19 | + * |
| 20 | + * @param Closure $callback |
| 21 | + */ |
| 22 | + public function transaction(Closure $callback) |
| 23 | + { |
| 24 | + $this->startTransaction(); |
| 25 | + |
| 26 | + try { |
| 27 | + $callback(); |
| 28 | + } catch (SoapFault $exception) { |
| 29 | + // Pace has already rolled the transaction back. |
| 30 | + SoapClient::removeMiddleware('transaction'); |
| 31 | + throw $exception; |
| 32 | + } catch (Throwable $exception) { |
| 33 | + $this->rollback(); |
| 34 | + throw $exception; |
| 35 | + } |
| 36 | + |
| 37 | + $this->commit(); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * Start a new transaction. |
| 42 | + * |
| 43 | + * @param int $timeout |
| 44 | + */ |
| 45 | + public function startTransaction(int $timeout = 60) |
| 46 | + { |
| 47 | + SoapClient::addMiddleware('startTransaction', new StartTransaction); |
| 48 | + |
| 49 | + $response = $this->soap->startTransaction(['in0' => $timeout]); |
| 50 | + |
| 51 | + SoapClient::removeMiddleware('startTransaction'); |
| 52 | + SoapClient::addMiddleware('transaction', new Transaction($response->out)); |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Rollback the transaction. |
| 57 | + */ |
| 58 | + public function rollback() |
| 59 | + { |
| 60 | + SoapClient::addMiddleware('rollback', new RollbackTransaction); |
| 61 | + |
| 62 | + $this->soap->rollback(); |
| 63 | + |
| 64 | + SoapClient::removeMiddleware('rollback'); |
| 65 | + SoapClient::removeMiddleware('transaction'); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Commit the transaction. |
| 70 | + */ |
| 71 | + public function commit() |
| 72 | + { |
| 73 | + SoapClient::addMiddleware('commit', new CommitTransaction); |
| 74 | + |
| 75 | + $this->soap->commit(); |
| 76 | + |
| 77 | + SoapClient::removeMiddleware('commit'); |
| 78 | + SoapClient::removeMiddleware('transaction'); |
| 79 | + } |
| 80 | +} |
0 commit comments