Skip to content

Commit

Permalink
Implemented Transaction::finally() method for always firing an operat…
Browse files Browse the repository at this point in the history
…ion outside the transaction.
  • Loading branch information
Nick Bedford committed Nov 25, 2021
1 parent 937bbb2 commit c5de253
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Transaction.php
Expand Up @@ -99,6 +99,7 @@ public function execute(): self
finally
{
$this->unlockTableIfNecessary();
$this->finally();
}
$this->fireEvent();
return $this;
Expand All @@ -117,6 +118,14 @@ protected abstract function perform(): void;
protected function validate(): void
{
}

/**
* Executes any post-transaction operations regardless of the success or failure of the transaction.
* @throws Throwable
*/
protected function finally(): void
{
}

/**
* Reverts all side effects in the transaction.
Expand Down
2 changes: 2 additions & 0 deletions tests/TransactionTests.php
Expand Up @@ -33,13 +33,15 @@ function testEventFiringTransactionFires()
{
TransactionFired::$instances = [];
$transaction = new EventFiringTransaction();
$this->assertFalse($transaction->finally);

$transaction->execute();
$event = TransactionFired::$instances[$transaction->eventKey] ?? null;

$this->assertNotNull($event);
$this->assertSame($event->transaction, $transaction);
$this->assertTrue($event->listenedTo);
$this->assertTrue($transaction->finally);
}

function testSideEffectsAreReverted()
Expand Down
7 changes: 7 additions & 0 deletions tests/Transactions/EventFiringTransaction.php
Expand Up @@ -8,9 +8,16 @@ class EventFiringTransaction extends Transaction
{
protected ?string $event = TransactionFired::class;
public string $eventKey;
public bool $finally = false;

protected function perform(): void
{
$this->eventKey = bin2hex(random_bytes(8));
}

protected function finally(): void
{
parent::finally();
$this->finally = true;
}
}

0 comments on commit c5de253

Please sign in to comment.