-
-
Notifications
You must be signed in to change notification settings - Fork 285
/
DatabaseTransactionHelpers.php
76 lines (64 loc) · 2.18 KB
/
DatabaseTransactionHelpers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
namespace Knuckles\Scribe\Extracting;
use Knuckles\Scribe\Exceptions\DatabaseTransactionsNotSupported;
use Knuckles\Scribe\Tools\DocumentationConfig;
use PDOException;
trait DatabaseTransactionHelpers
{
private function connectionsToTransact()
{
return $this->getConfig()->get('database_connections_to_transact', []);
}
private function startDbTransaction()
{
foreach ($this->connectionsToTransact() as $connection) {
$database ??= app('db');
$driver = $database->connection($connection);
if (self::driverSupportsTransactions($driver)) {
try {
$driver->beginTransaction();
} catch (PDOException $e) {
throw new \Exception(
"Failed to connect to database connection '$connection'." .
" Is the database running?" .
" If you aren't using this database, remove it from the `database_connections_to_transact` config array."
);
}
} else {
$driverClassName = get_class($driver);
throw DatabaseTransactionsNotSupported::create($connection, $driverClassName);
}
}
}
/**
* @return void
*/
private function endDbTransaction()
{
foreach ($this->connectionsToTransact() as $connection) {
$database ??= app('db');
$driver = $database->connection($connection);
try {
$driver->rollback();
} catch (\Exception $e) {
// Any error handling should have been done on the startDbTransaction() side
}
}
}
private static function driverSupportsTransactions($driver): bool
{
$methods = ['beginTransaction', 'rollback'];
foreach ($methods as $method) {
if (!method_exists($driver, $method)) {
return false;
}
}
return true;
}
/**
* Returns an instance of the documentation config
*
* @return DocumentationConfig
*/
abstract public function getConfig(): DocumentationConfig;
}