Skip to content

Commit

Permalink
Add CombinedTransaction::try()
Browse files Browse the repository at this point in the history
  • Loading branch information
Composite PHP committed Jul 13, 2024
1 parent 5830b1e commit 0945254
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/CombinedTransaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,19 @@ public function delete(AbstractTable $table, AbstractEntity &$entity): void
});
}

/**
* @throws Exceptions\DbException
*/
public function try(callable $callback): void
{
try {
$callback();
} catch (\Throwable $e) {
$this->rollback();
throw new Exceptions\DbException($e->getMessage(), 500, $e);
}
}

public function rollback(): void
{
foreach ($this->transactions as $connection) {
Expand Down
14 changes: 14 additions & 0 deletions tests/Table/CombinedTransactionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,20 @@ public function test_failedDelete(): void
$this->assertNotNull($compositeTable->findOne($cEntity->user_id, $cEntity->post_id));
}

public function test_try(): void
{
$compositeTable = new Tables\TestCompositeTable();
$entity = new Entities\TestCompositeEntity(user_id: mt_rand(1, 1000), post_id: mt_rand(1, 1000), message: 'Bar');;

try {
$transaction = new CombinedTransaction();
$transaction->save($compositeTable, $entity);
$transaction->try(fn() => throw new \Exception('test'));
$transaction->commit();
} catch (DbException) {}
$this->assertNull($compositeTable->findOne($entity->user_id, $entity->post_id));
}

public function test_lockFailed(): void
{
$cache = new Helpers\FalseCache();
Expand Down

0 comments on commit 0945254

Please sign in to comment.