Skip to content

Commit

Permalink
Merge interfaces and parents for adding event listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
vbergerondev committed Jul 25, 2024
1 parent b18f333 commit ce9630b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
14 changes: 8 additions & 6 deletions src/Illuminate/Events/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ public function getListeners($eventName)
);

return class_exists($eventName, false)
? $this->addInterfaceListeners($eventName, $listeners)
? $this->addInterfaceAndParentListeners($eventName, $listeners)
: $listeners;
}

Expand All @@ -397,17 +397,19 @@ protected function getWildcardListeners($eventName)
}

/**
* Add the listeners for the event's interfaces to the given array.
* Add the listeners for the event's interfaces and parents to the given array.
*
* @param string $eventName
* @param array $listeners
* @return array
*/
protected function addInterfaceListeners($eventName, array $listeners = [])
protected function addInterfaceAndParentListeners($eventName, array $listeners = [])
{
foreach (class_implements($eventName) as $interface) {
if (isset($this->listeners[$interface])) {
foreach ($this->prepareListeners($interface) as $names) {
$types = [...class_implements($eventName), ...class_parents($eventName)];

foreach ($types as $type) {
if (isset($this->listeners[$type])) {
foreach ($this->prepareListeners($type) as $names) {
$listeners = array_merge($listeners, (array) $names);
}
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Events/EventsDispatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,18 @@ public function testInterfacesWork()
$this->assertSame('bar', $_SERVER['__event.test']);
}

public function testParentsWork()
{
unset($_SERVER['__event.test']);
$d = new Dispatcher;
$d->listen(ParentEvent::class, function () {
$_SERVER['__event.test'] = 'bar';
});
$d->dispatch(new EventWithParent);

$this->assertSame('bar', $_SERVER['__event.test']);
}

public function testBothClassesAndInterfacesWork()
{
unset($_SERVER['__event.test']);
Expand Down Expand Up @@ -628,6 +640,11 @@ class ExampleEvent
//
}

class ParentEvent
{
//
}

interface SomeEventInterface
{
//
Expand All @@ -638,6 +655,11 @@ class AnotherEvent implements SomeEventInterface
//
}

class EventWithParent extends ParentEvent
{
//
}

class TestEventListener
{
public function handle($foo, $bar)
Expand Down

0 comments on commit ce9630b

Please sign in to comment.