Skip to content

Commit 0945254

Browse files
author
Composite PHP
committed
Add CombinedTransaction::try()
1 parent 5830b1e commit 0945254

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/CombinedTransaction.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,19 @@ public function delete(AbstractTable $table, AbstractEntity &$entity): void
5454
});
5555
}
5656

57+
/**
58+
* @throws Exceptions\DbException
59+
*/
60+
public function try(callable $callback): void
61+
{
62+
try {
63+
$callback();
64+
} catch (\Throwable $e) {
65+
$this->rollback();
66+
throw new Exceptions\DbException($e->getMessage(), 500, $e);
67+
}
68+
}
69+
5770
public function rollback(): void
5871
{
5972
foreach ($this->transactions as $connection) {

tests/Table/CombinedTransactionTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,20 @@ public function test_failedDelete(): void
130130
$this->assertNotNull($compositeTable->findOne($cEntity->user_id, $cEntity->post_id));
131131
}
132132

133+
public function test_try(): void
134+
{
135+
$compositeTable = new Tables\TestCompositeTable();
136+
$entity = new Entities\TestCompositeEntity(user_id: mt_rand(1, 1000), post_id: mt_rand(1, 1000), message: 'Bar');;
137+
138+
try {
139+
$transaction = new CombinedTransaction();
140+
$transaction->save($compositeTable, $entity);
141+
$transaction->try(fn() => throw new \Exception('test'));
142+
$transaction->commit();
143+
} catch (DbException) {}
144+
$this->assertNull($compositeTable->findOne($entity->user_id, $entity->post_id));
145+
}
146+
133147
public function test_lockFailed(): void
134148
{
135149
$cache = new Helpers\FalseCache();

0 commit comments

Comments
 (0)