Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions doc/01-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,28 @@ $result = $a + $b;
$emitter->emit('numbers_added', [$result, $a, $b]);
```

## emit_regex($pattern, array $arguments = [])

Emit an event, which will call all listeners by regular expression.

Example:

```php
$events->on('note_a1', function($channel, $velocity) {
echo "paying note a1\n";
});

$events->on('note_a2', function($channel, $velocity) {
echo "paying note a2\n";
});

$events->on('note_b2', function($channel, $velocity) {
echo "paying note b2\n";
});

$events->emit_regex("/note_a/i", [0, 127]);
```

## listeners($event)

Allows you to inspect the listeners attached to an event. Particularly useful
Expand Down
28 changes: 27 additions & 1 deletion src/EventEmitterTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public function emit($event, array $arguments = [])
$onceListeners = array_values($this->onceListeners[$event]);
}

if(empty($listeners) === false) {
if(empty($listeners) === false) {
foreach ($listeners as $listener) {
$listener(...$arguments);
}
Expand All @@ -151,4 +151,30 @@ public function emit($event, array $arguments = [])
}
}
}

public function emit_regex($pattern, array $arguments = [])
{
if ($pattern === null) {
throw new InvalidArgumentException('event name must not be null');
}

$listeners = [];
foreach($this->listeners as $_event => $_listeners) {
if(preg_match($pattern, $_event, $matches)) {
foreach ($_listeners as $listener) {
$listener(...$arguments);
}
}
}

$onceListeners = [];
foreach($this->onceListeners as $_event => $_listeners) {
if(preg_match($pattern, $_event, $matches)) {
unset($this->onceListeners[$_event]);
foreach ($_listeners as $listener) {
$listener(...$arguments);
}
}
}
}
}