Skip to content

Commit

Permalink
Fix #27
Browse files Browse the repository at this point in the history
  • Loading branch information
fntneves committed Sep 7, 2019
1 parent 5786a5c commit a50e904
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Neves/Events/TransactionalDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ protected function addPendingEvent($event, $payload) : void
*/
private function onTransactionCommit() : void
{
if (! $this->isTransactionRunning()) {
return;
}

$committedTransaction = $this->finishTransaction();

if (! $committedTransaction->isRoot()) {
Expand All @@ -174,6 +178,10 @@ private function onTransactionCommit() : void
*/
private function onTransactionRollback() : void
{
if (! $this->isTransactionRunning()) {
return;
}

$rolledBackTransaction = $this->finishTransaction();

if ($rolledBackTransaction->isRoot()) {
Expand All @@ -185,6 +193,20 @@ private function onTransactionRollback() : void
$this->nextEventIndex -= $rolledBackTransaction->getValue()->count();
}

/**
* Check whether there is at least one transaction running.
*
* @return bool
*/
private function isTransactionRunning() : bool
{
if ($this->currentTransaction) {
return true;
}

return false;
}

/**
* Flush all pending events.
*
Expand Down
45 changes: 45 additions & 0 deletions tests/TransactionalDispatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,36 @@ public function it_works_with_non_default_connections()
$this->assertEquals('second', $_SERVER['__events'][1]);
}

/**
* Regression test: Call to a member function getParent() on null (#27).
* This reproduces the use of DatabaseTransactions and RefreshDatabase traits.
* @test
*/
public function it_ignores_commits_or_rollbacks_when_transactions_are_not_running()
{
$this->withoutEvents(function () {
DB::beginTransaction();
});

$this->dispatcher->listen('foo', function () {
throw new \Exception();
});

try {
DB::beginTransaction();
$this->dispatcher->dispatch('foo');
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
}

$this->withoutEvents(function () {
DB::rollBack();
});

$this->assertTrue(true);
}

protected function getPackageProviders($app)
{
// Add an event listener to the previous event dispatcher.
Expand All @@ -338,6 +368,21 @@ protected function getEnvironmentSetUp($app)
'database' => ':memory:',
]);
}

protected function withoutEvents(Closure $callback)
{
// Disable Transactional dispatcher.
DB::connection()->unsetEventDispatcher();

try {
$callback();
} catch (\Exception $e) {
throw $e;
} finally {
// Restore the Transactional dispatcher.
DB::connection()->setEventDispatcher($this->dispatcher);
}
}
}

class CustomEvent implements TransactionalEvent
Expand Down

0 comments on commit a50e904

Please sign in to comment.