Skip to content

Commit

Permalink
Implements a stack of dispatched events #7404
Browse files Browse the repository at this point in the history
  • Loading branch information
Florian Krämer committed May 19, 2016
1 parent b98b14d commit 5dbb93a
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Event/EventManager.php
Expand Up @@ -53,6 +53,13 @@ class EventManager
*/
protected $_isGlobal = false;

/**
* A list of already dispatched events
*
* @var array
*/
protected $_dispatchedEvents = [];

/**
* Returns the globally available instance of a Cake\Event\EventManager
* this is used for dispatching events attached from outside the scope
Expand Down Expand Up @@ -346,6 +353,7 @@ public function dispatch($event)

$listeners = $this->listeners($event->name());
if (empty($listeners)) {
$this->_dispatchedEvents[] = $event;
return $event;
}

Expand All @@ -361,6 +369,7 @@ public function dispatch($event)
$event->result = $result;
}
}
$this->_dispatchedEvents[] = $event;
return $event;
}

Expand Down Expand Up @@ -460,6 +469,16 @@ public function matchingListeners($eventKeyPattern)
return $matches;
}

/**
* Returns a list of dispatched event objects.
*
* @return array
*/
public function getDispatchedEvents()
{
return $this->_dispatchedEvents;
}

/**
* Debug friendly object properties.
*
Expand All @@ -473,6 +492,9 @@ public function __debugInfo()
foreach ($this->_listeners as $key => $listeners) {
$properties['_listeners'][$key] = count($listeners) . ' listener(s)';
}
foreach ($this->_dispatchedEvents as $event) {
$properties['_dispatchedEvents'][] = $event->name() . ' with subject ' . get_class($event->subject());
}
return $properties;
}
}
22 changes: 22 additions & 0 deletions tests/TestCase/Event/EventManagerTest.php
Expand Up @@ -710,4 +710,26 @@ public function testDispatchWithGlobalAndLocalEvents()
$this->assertEquals(['listenerFunction'], $listener->callStack);
$this->assertEquals(['listenerFunction'], $listener2->callStack);
}

/**
* Test getting a list of dispatched events from the manager.
*
* @return void
* @triggers my_event $this)
* @triggers my_second_event $this)
*/
public function testGetDispatchedEvents()
{
$event = new Event('my_event', $this);
$event2 = new Event('my_second_event', $this);

$manager = new EventManager();
$manager->dispatch($event);
$manager->dispatch($event2);

$result = $manager->getDispatchedEvents();
$this->assertCount(2, $result);
$this->assertEquals($result[0], $event);
$this->assertEquals($result[1], $event2);
}
}

0 comments on commit 5dbb93a

Please sign in to comment.