Skip to content

Commit

Permalink
feat: adds EventProjectorRegistry
Browse files Browse the repository at this point in the history
  • Loading branch information
matiux committed Nov 1, 2022
1 parent 3421f43 commit 3f388b0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Matiux/DDDStarterPack/Query/EventProjector.php
Expand Up @@ -9,10 +9,15 @@
/**
* @template T of DomainEvent
*/
interface Projector
interface EventProjector
{
/**
* @param T $event
*/
public function project($event): void;

/**
* @param T $event
*/
public function supports($event): bool;
}
51 changes: 51 additions & 0 deletions src/Matiux/DDDStarterPack/Query/EventProjectorRegistry.php
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace DDDStarterPack\Query;

use DDDStarterPack\Event\DomainEvent;
use InvalidArgumentException;
use Traversable;

class EventProjectorRegistry
{
/** @var EventProjector[] */
protected array $eventProjectors = [];

/**
* @param EventProjector[]|Traversable<EventProjector> $eventProjectors
*/
public function __construct($eventProjectors = [])
{
if ($eventProjectors instanceof Traversable) {
$eventProjectors = iterator_to_array($eventProjectors);
}

foreach ($eventProjectors as $eventProjector) {
$this->addEventProjector($eventProjector);
}
}

public function addEventProjector(EventProjector $eventProjector): void
{
if (isset($this->eventProjectors[$eventProjector::class])) {
throw new InvalidArgumentException(
sprintf("EventProjector for key '%s' is already set", $eventProjector::class)
);
}

$this->eventProjectors[$eventProjector::class] = $eventProjector;
}

public function project(DomainEvent $event): void
{
foreach ($this->eventProjectors as $eventProjector) {
if ($eventProjector->supports($event)) {
$eventProjector->project($event);

return;
}
}
}
}

0 comments on commit 3f388b0

Please sign in to comment.