DatabaseTransactionsManager.php
| 1 | <?php |
| 2 | |
| 3 | namespace IAWP_SCOPED\Illuminate\Database; |
| 4 | |
| 5 | class DatabaseTransactionsManager |
| 6 | { |
| 7 | /** |
| 8 | * All of the recorded transactions. |
| 9 | * |
| 10 | * @var \Illuminate\Support\Collection |
| 11 | */ |
| 12 | protected $transactions; |
| 13 | /** |
| 14 | * Create a new database transactions manager instance. |
| 15 | * |
| 16 | * @return void |
| 17 | */ |
| 18 | public function __construct() |
| 19 | { |
| 20 | $this->transactions = \IAWP_SCOPED\collect(); |
| 21 | } |
| 22 | /** |
| 23 | * Start a new database transaction. |
| 24 | * |
| 25 | * @param string $connection |
| 26 | * @param int $level |
| 27 | * @return void |
| 28 | */ |
| 29 | public function begin($connection, $level) |
| 30 | { |
| 31 | $this->transactions->push(new DatabaseTransactionRecord($connection, $level)); |
| 32 | } |
| 33 | /** |
| 34 | * Rollback the active database transaction. |
| 35 | * |
| 36 | * @param string $connection |
| 37 | * @param int $level |
| 38 | * @return void |
| 39 | */ |
| 40 | public function rollback($connection, $level) |
| 41 | { |
| 42 | $this->transactions = $this->transactions->reject(function ($transaction) use($connection, $level) { |
| 43 | return $transaction->connection == $connection && $transaction->level > $level; |
| 44 | })->values(); |
| 45 | } |
| 46 | /** |
| 47 | * Commit the active database transaction. |
| 48 | * |
| 49 | * @param string $connection |
| 50 | * @return void |
| 51 | */ |
| 52 | public function commit($connection) |
| 53 | { |
| 54 | [$forThisConnection, $forOtherConnections] = $this->transactions->partition(function ($transaction) use($connection) { |
| 55 | return $transaction->connection == $connection; |
| 56 | }); |
| 57 | $this->transactions = $forOtherConnections->values(); |
| 58 | $forThisConnection->map->executeCallbacks(); |
| 59 | } |
| 60 | /** |
| 61 | * Register a transaction callback. |
| 62 | * |
| 63 | * @param callable $callback |
| 64 | * @return void |
| 65 | */ |
| 66 | public function addCallback($callback) |
| 67 | { |
| 68 | if ($current = $this->transactions->last()) { |
| 69 | return $current->addCallback($callback); |
| 70 | } |
| 71 | \call_user_func($callback); |
| 72 | } |
| 73 | /** |
| 74 | * Get all the transactions. |
| 75 | * |
| 76 | * @return \Illuminate\Support\Collection |
| 77 | */ |
| 78 | public function getTransactions() |
| 79 | { |
| 80 | return $this->transactions; |
| 81 | } |
| 82 | } |
| 83 |