DatabaseTransactionsManager.php 2.2 KB

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