Skip to content

[8.x] Implement transactional events via marker interface #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"egulias/email-validator": "^2.1.10",
"league/commonmark": "^1.3",
"league/flysystem": "^1.0.8",
"loophp/phptree": "^2.6",
"monolog/monolog": "^2.0",
"nesbot/carbon": "^2.17",
"opis/closure": "^3.5",
Expand Down
14 changes: 14 additions & 0 deletions src/Illuminate/Contracts/Events/TransactionalEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Illuminate\Contracts\Events;

/**
* Any Event implementing this (marker) interface will respect
* the currently ongoing database transactions and will:
*
* - purge the events in case of a rollback
* - dispatch them once the transaction is commited
*/
interface TransactionalEvent
{
}
24 changes: 23 additions & 1 deletion src/Illuminate/Events/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
class Dispatcher implements DispatcherContract
{
use Macroable;
use HandlesTransactions;

/**
* The IoC container instance.
Expand Down Expand Up @@ -62,6 +63,8 @@ class Dispatcher implements DispatcherContract
public function __construct(ContainerContract $container = null)
{
$this->container = $container ?: new Container;

$this->setupDatabaseListeners();
}

/**
Expand Down Expand Up @@ -192,14 +195,33 @@ public function until($event, $payload = [])
}

/**
* Fire an event and call the listeners.
* Fire an event and call the listeners, respect transactional events
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return array|null
*/
public function dispatch($event, $payload = [], $halt = false)
{
if (!$halt && $this->isTransactionalEvent($event)) {
$this->addPendingEvent($event, $payload);

return null;
}

return $this->dispatchEvent($event, $payload, $halt);
}

/**
* Fire an event and call the listeners.
*
* @param string|object $event
* @param mixed $payload
* @param bool $halt
* @return array|null
*/
protected function dispatchEvent($event, $payload = [], $halt = false)
{
// When the given "event" is actually an object we will assume it is an event
// object and use the class as the event name and this event itself as the
Expand Down
212 changes: 212 additions & 0 deletions src/Illuminate/Events/HandlesTransactions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
<?php

namespace Illuminate\Events;

use Illuminate\Collections\Collection;
use Illuminate\Contracts\Events\TransactionalEvent;
use Illuminate\Database\Events\TransactionBeginning;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use loophp\phptree\Node\ValueNode;
use loophp\phptree\Node\ValueNodeInterface;

trait HandlesTransactions
{
/**
* The current prepared transaction.
*
* @var \loophp\phptree\Node\ValueNodeInterface
*/
protected $currentTransaction;

/**
* All pending events in order.
*
* @var array
*/
protected $events = [];

/**
* Next position for event storing.
*
* @var int
*/
protected $nextEventIndex = 0;

/**
* Setup listeners for transaction events.
*
* @return void
*/
protected function setupDatabaseListeners(): void
{
$this->listen(TransactionBeginning::class, function () {
$this->onTransactionBegin();
});

$this->listen(TransactionCommitted::class, function () {
$this->onTransactionCommit();
});

$this->listen(TransactionRolledBack::class, function () {
$this->onTransactionRollback();
});
}

/**
* Prepare a new transaction.
*
* @return void
*/
protected function onTransactionBegin(): void
{
$transactionNode = new ValueNode(new Collection());

$this->currentTransaction = $this->isTransactionRunning()
? $this->currentTransaction->add($transactionNode)
: $transactionNode;

$this->currentTransaction = $transactionNode;
}

/**
* Add a pending transactional event to the current transaction.
*
* @param string|object $event
* @param mixed $payload
* @return void
*/
protected function addPendingEvent($event, $payload): void
{
$eventData = [
'event' => $event,
'payload' => is_object($payload) ? clone $payload : $payload,
];

$this->currentTransaction->getValue()->push($eventData);
$this->events[$this->nextEventIndex++] = $eventData;
}

/**
* Handle transaction commit.
*
* @return void
*/
protected function onTransactionCommit(): void
{
if (! $this->isTransactionRunning()) {
return;
}

$committedTransaction = $this->finishTransaction();

if (! $committedTransaction->isRoot()) {
return;
}

$this->dispatchPendingEvents();
}

/**
* Clear enqueued events for the rollbacked transaction.
*
* @return void
*/
protected function onTransactionRollback(): void
{
if (! $this->isTransactionRunning()) {
return;
}

$rolledBackTransaction = $this->finishTransaction();

if ($rolledBackTransaction->isRoot()) {
$this->resetEvents();

return;
}

$this->nextEventIndex -= $rolledBackTransaction->getValue()->count();
}

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

return false;
}

/**
* Flush all pending events.
*
* @return void
*/
protected function dispatchPendingEvents(): void
{
$events = $this->events;
$eventsCount = $this->nextEventIndex;
$this->resetEvents();

for ($i = 0; $i < $eventsCount; $i++) {
$event = $events[$i];
$this->dispatchEvent($event['event'], $event['payload']);
}
}

/**
* Check whether an event is a transactional event or not.
*
* @param string|object $event
* @return bool
*/
protected function isTransactionalEvent($event): bool
{
if (! $this->isTransactionRunning()) {
return false;
}

return $this->shouldHandleTransaction($event);
}

/**
* Finish current transaction.
*
* @return \loophp\phptree\Node\ValueNodeInterface
*/
protected function finishTransaction(): ValueNodeInterface
{
$finished = $this->currentTransaction;
$this->currentTransaction = $finished->getParent();

return $finished;
}

/**
* Reset events list.
*
* @return void
*/
protected function resetEvents(): void
{
$this->events = [];
$this->nextEventIndex = 0;
}

/**
* Check whether an event should be handled by this layer or not.
*
* @param string|object $event
* @return bool
*/
protected function shouldHandleTransaction($event): bool
{
return $event instanceof TransactionalEvent;
}
}
4 changes: 3 additions & 1 deletion src/Illuminate/Events/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
"illuminate/collections": "^8.0",
"illuminate/container": "^8.0",
"illuminate/contracts": "^8.0",
"illuminate/database": "^8.0",
"illuminate/macroable": "^8.0",
"illuminate/support": "^8.0"
"illuminate/support": "^8.0",
"loophp/phptree": "^2.6"
},
"autoload": {
"psr-4": {
Expand Down
Loading