- Basic event manager middleware

This commit is contained in:
Dave Mc Nicoll 2023-05-30 15:40:31 -04:00
parent 4d73913bef
commit f36228b7a6
4 changed files with 45 additions and 4 deletions

12
src/EventDefinition.php Normal file
View File

@ -0,0 +1,12 @@
<?php
namespace Mcnd\Event;
use Psr\Container\ContainerInterface;
class EventDefinition
{
public function __construct(
public array $list
) {}
}

View File

@ -29,17 +29,25 @@ class EventManager
public function eventFromName(string $name) : array public function eventFromName(string $name) : array
{ {
return array_filter($this->eventList, fn($ev) => $ev->name === $name); return array_filter($this->eventList, fn($ev) => property_exists($ev, 'name') && $ev->name === $name);
} }
public function execute(string $name, ...$arguments) : void public function execute(string $name, &...$arguments) : void
{ {
$continue = true;
foreach($this->eventFromName($name) as $event) { foreach($this->eventFromName($name) as $event) {
if ($continue) {
$event->execute($this->container, ...$arguments); $event->execute($this->container, ...$arguments);
$continue = empty($event->stopPropagation);
}
} }
foreach($this->eventfromType($name) as $event) { foreach($this->eventfromType($name) as $event) {
if ($continue) {
call_user_func_array([ $event, 'execute'], $arguments); call_user_func_array([ $event, 'execute'], $arguments);
$continue = empty($event->stopPropagation);
}
} }
} }
} }

View File

@ -34,4 +34,13 @@ class EventMiddleware implements MiddlewareInterface
return $this; return $this;
} }
public function fromDefinition(EventDefinition $definition) : self
{
foreach($definition->list as $event) {
$this->eventManager->eventRegister($event);
}
return $this;
}
} }

12
src/EventTrait.php Normal file
View File

@ -0,0 +1,12 @@
<?php
namespace Mcnd\Event;
trait EventTrait
{
public function __construct(
protected bool $stopPropagation = false,
) {
}
}