| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace Illuminate\Foundation\Testing;
|
|
|
4 |
|
|
|
5 |
trait DatabaseTransactions
|
|
|
6 |
{
|
|
|
7 |
/**
|
|
|
8 |
* Handle database transactions on the specified connections.
|
|
|
9 |
*
|
|
|
10 |
* @return void
|
|
|
11 |
*/
|
|
|
12 |
public function beginDatabaseTransaction()
|
|
|
13 |
{
|
|
|
14 |
$database = $this->app->make('db');
|
|
|
15 |
|
|
|
16 |
foreach ($this->connectionsToTransact() as $name) {
|
|
|
17 |
$connection = $database->connection($name);
|
|
|
18 |
$dispatcher = $connection->getEventDispatcher();
|
|
|
19 |
|
|
|
20 |
$connection->unsetEventDispatcher();
|
|
|
21 |
$connection->beginTransaction();
|
|
|
22 |
$connection->setEventDispatcher($dispatcher);
|
|
|
23 |
|
|
|
24 |
if ($this->app->resolved('db.transactions')) {
|
|
|
25 |
$this->app->make('db.transactions')->callbacksShouldIgnore(
|
|
|
26 |
$this->app->make('db.transactions')->getTransactions()->first()
|
|
|
27 |
);
|
|
|
28 |
}
|
|
|
29 |
}
|
|
|
30 |
|
|
|
31 |
$this->beforeApplicationDestroyed(function () use ($database) {
|
|
|
32 |
foreach ($this->connectionsToTransact() as $name) {
|
|
|
33 |
$connection = $database->connection($name);
|
|
|
34 |
$dispatcher = $connection->getEventDispatcher();
|
|
|
35 |
|
|
|
36 |
$connection->unsetEventDispatcher();
|
|
|
37 |
$connection->rollBack();
|
|
|
38 |
$connection->setEventDispatcher($dispatcher);
|
|
|
39 |
$connection->disconnect();
|
|
|
40 |
}
|
|
|
41 |
});
|
|
|
42 |
}
|
|
|
43 |
|
|
|
44 |
/**
|
|
|
45 |
* The database connections that should have transactions.
|
|
|
46 |
*
|
|
|
47 |
* @return array
|
|
|
48 |
*/
|
|
|
49 |
protected function connectionsToTransact()
|
|
|
50 |
{
|
|
|
51 |
return property_exists($this, 'connectionsToTransact')
|
|
|
52 |
? $this->connectionsToTransact : [null];
|
|
|
53 |
}
|
|
|
54 |
}
|