move code to repository root
This commit is contained in:
parent
47e227257c
commit
9ce2c0ae4c
35 changed files with 2025 additions and 0 deletions
60
src/Infrastructure/Event/Dispatcher.php
Normal file
60
src/Infrastructure/Event/Dispatcher.php
Normal file
|
@ -0,0 +1,60 @@
|
|||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Lubian\AttributeMagic\Infrastructure\Event;
|
||||
|
||||
use Invoker\InvokerInterface;
|
||||
|
||||
use function Lubian\AttributeMagic\Infrastructure\arrayFilter;
|
||||
use function usort;
|
||||
|
||||
final class Dispatcher
|
||||
{
|
||||
/**
|
||||
* @param Listener[] $listeners
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly InvokerInterface $invoker,
|
||||
private array $listeners = [],
|
||||
) {
|
||||
}
|
||||
|
||||
public function addListener(Listener $listener): void
|
||||
{
|
||||
$this->listeners[] = $listener;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Listener[]
|
||||
*/
|
||||
public function getListenerForEvent(GenericEvent $event): array
|
||||
{
|
||||
return arrayFilter(
|
||||
$this->listeners,
|
||||
static fn (Listener $l): bool => $l->eventClass === $event::class,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Listener[]
|
||||
*/
|
||||
public function getSortedListenerForEvent(GenericEvent $event): array
|
||||
{
|
||||
$filtered = $this->getListenerForEvent($event);
|
||||
usort($filtered, static fn (Listener $a, Listener $b): int => $a->priority <=> $b->priority);
|
||||
return $filtered;
|
||||
}
|
||||
|
||||
public function dispatch(GenericEvent $event): void
|
||||
{
|
||||
foreach ($this->getSortedListenerForEvent($event) as $listener) {
|
||||
if ($event->stopped === true) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->invoker->call(
|
||||
[$listener->listenerClass, $listener->listenerMethod],
|
||||
[$event],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue