-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransaction.php
More file actions
83 lines (63 loc) · 1.95 KB
/
Transaction.php
File metadata and controls
83 lines (63 loc) · 1.95 KB
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
77
78
79
80
81
82
83
<?php declare(strict_types=1);
namespace Parable\Orm;
use Throwable;
class Transaction
{
protected bool $inTransaction = false;
public function __construct(
protected Database $database
) {
}
public function isInTransaction(): bool
{
return $this->inTransaction;
}
public function begin(): void
{
if ($this->inTransaction === true) {
throw new OrmException('Cannot start a transaction within a transaction');
}
if ($this->database->getType() === Database::TYPE_MYSQL) {
$this->database->query('START TRANSACTION');
} elseif ($this->database->getType() === Database::TYPE_SQLITE) {
$this->database->query('BEGIN TRANSACTION');
} else {
throw new OrmException('Cannot start transaction for database type ' . $this->database->getType());
}
$this->inTransaction = true;
}
public function commit(): void
{
if ($this->inTransaction === false) {
throw new OrmException('Cannot commit while not in a transaction');
}
$this->database->query('COMMIT');
$this->inTransaction = false;
}
public function rollback(): void
{
if ($this->inTransaction === false) {
throw new OrmException('Cannot rollback while not in a transaction');
}
$this->database->query('ROLLBACK');
$this->inTransaction = false;
}
public function withTransaction(callable $callable)
{
$this->begin();
try {
$returnValue = $callable();
} catch (Throwable $exception) {
$this->rollback();
throw new OrmException($exception->getMessage(), (int)$exception->getCode(), $exception);
}
$this->commit();
return $returnValue;
}
public function __destruct()
{
if ($this->inTransaction === true) {
$this->rollback();
}
}
}