Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
57 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
51 changes: 51 additions & 0 deletions
51
src/Matiux/DDDStarterPack/Query/EventProjectorRegistry.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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; | ||
} | ||
} | ||
} | ||
} |