67 lines
1.3 KiB
PHP
67 lines
1.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Infrastructure\Adapters\Events;
|
|
|
|
use Illuminate\Support\Facades\Event;
|
|
use Shared\DDD\DomainEventDispatcher;
|
|
use Shared\DDD\Event as LibEvent;
|
|
|
|
class LaravelDomainEventDispatcher implements DomainEventDispatcher
|
|
{
|
|
private int $bufferDepth = 0;
|
|
|
|
/** @var list<\Shared\DDD\Event> */
|
|
private array $bufferedEvents = [];
|
|
|
|
public function beginBuffering(): void
|
|
{
|
|
$this->bufferDepth++;
|
|
}
|
|
|
|
#[\Override]
|
|
public function dispatch(LibEvent $event): void
|
|
{
|
|
if ($this->bufferDepth > 0) {
|
|
$this->bufferedEvents[] = $event;
|
|
|
|
return;
|
|
}
|
|
|
|
Event::dispatch($event);
|
|
}
|
|
|
|
public function flush(): void
|
|
{
|
|
if ($this->bufferDepth === 0) {
|
|
return;
|
|
}
|
|
|
|
$this->bufferDepth--;
|
|
|
|
if ($this->bufferDepth > 0) {
|
|
return;
|
|
}
|
|
|
|
$events = $this->bufferedEvents;
|
|
$this->bufferedEvents = [];
|
|
|
|
foreach ($events as $event) {
|
|
Event::dispatch($event);
|
|
}
|
|
}
|
|
|
|
public function discard(): void
|
|
{
|
|
if ($this->bufferDepth === 0) {
|
|
return;
|
|
}
|
|
|
|
$this->bufferDepth--;
|
|
|
|
if ($this->bufferDepth === 0) {
|
|
$this->bufferedEvents = [];
|
|
}
|
|
}
|
|
}
|