hfw /
db
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Helix\DB; |
||
| 4 | |||
| 5 | use Helix\DB; |
||
| 6 | |||
| 7 | /** |
||
| 8 | * Scoped transaction/savepoint. |
||
| 9 | * |
||
| 10 | * If the instance isn't committed before it loses scope, it's rolled back. |
||
| 11 | * There is no `rollback()` method. |
||
| 12 | * |
||
| 13 | * In order to ensure proper destruction, the instance MUST NOT leave the scope it's created in. |
||
| 14 | * |
||
| 15 | * @method static static factory(DB $db) |
||
| 16 | */ |
||
| 17 | class Transaction |
||
| 18 | { |
||
| 19 | |||
| 20 | use FactoryTrait; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var bool |
||
| 24 | */ |
||
| 25 | protected $committed = false; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var DB |
||
| 29 | */ |
||
| 30 | protected $db; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * Begins the transaction/savepoint. |
||
| 34 | * |
||
| 35 | * @param DB $db |
||
| 36 | */ |
||
| 37 | public function __construct(DB $db) |
||
| 38 | { |
||
| 39 | $this->db = $db; |
||
| 40 | $db->beginTransaction(); |
||
| 41 | } |
||
| 42 | |||
| 43 | /** |
||
| 44 | * Rolls back if the instance wasn't committed. |
||
| 45 | */ |
||
| 46 | public function __destruct() |
||
| 47 | { |
||
| 48 | if (!$this->committed) { |
||
| 49 | $this->db->rollBack(); |
||
| 50 | } |
||
| 51 | } |
||
| 52 | |||
| 53 | /** |
||
| 54 | * Commits the transaction/savepoint. |
||
| 55 | * |
||
| 56 | * This is safe to call multiple times, it won't have any effect after the first time. |
||
| 57 | * |
||
| 58 | * @return true |
||
| 59 | */ |
||
| 60 | public function commit(): bool |
||
| 61 | { |
||
| 62 | return $this->committed or $this->committed = $this->db->commit(); |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 63 | } |
||
| 64 | |||
| 65 | /** |
||
| 66 | * @return bool |
||
| 67 | */ |
||
| 68 | final public function wasCommitted(): bool |
||
| 69 | { |
||
| 70 | return $this->committed; |
||
| 71 | } |
||
| 72 | } |
||
| 73 |