Skip to content

Commit

Permalink
[zendframework#40] Implement array of events support for attach()
Browse files Browse the repository at this point in the history
  • Loading branch information
weierophinney committed Mar 13, 2012
1 parent ffc97f8 commit 0f4c6fb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
10 changes: 9 additions & 1 deletion library/Zend/EventManager/EventManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ public function triggerUntil($event, $target, $argv = null, $callback = null)
* executed. By default, this value is 1; however, you may set it for any
* integer value. Higher values have higher priority (i.e., execute first).
*
* @param string|ListenerAggregate $event
* @param string|array|ListenerAggregate $event An event or array of event names. If a ListenerAggregate, proxies to {@link attachAggregate()}.
* @param callback|int $callback If string $event provided, expects PHP callback; for a ListenerAggregate $event, this will be the priority
* @param int $priority If provided, the priority at which to register the callback
* @return CallbackHandler|mixed CallbackHandler if attaching callback (to allow later unsubscribe); mixed if attaching aggregate
Expand All @@ -272,6 +272,14 @@ public function attach($event, $callback = null, $priority = 1)
));
}

if (is_array($event)) {
$listeners = array();
foreach ($event as $name) {
$listeners[] = $this->attach($name, $callback, $priority);
}
return $listeners;
}

if (empty($this->events[$event])) {
$this->events[$event] = new PriorityQueue();
}
Expand Down
31 changes: 31 additions & 0 deletions tests/Zend/EventManager/EventManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,37 @@ public function testAttachShouldAddEventIfItDoesNotExist()
$this->assertContains('test', $events);
}

public function testAllowsPassingArrayOfEventNamesWhenAttaching()
{
$callback = function ($e) {
return $e->getName();
};
$this->events->attach(array('foo', 'bar'), $callback);

foreach (array('foo', 'bar') as $event) {
$listeners = $this->events->getListeners($event);
$this->assertTrue(count($listeners) > 0);
foreach ($listeners as $listener) {
$this->assertSame($callback, $listener->getCallback());
}
}
}

public function testPassingArrayOfEventNamesWhenAttachingReturnsArrayOfCallbackHandlers()
{
$callback = function ($e) {
return $e->getName();
};
$listeners = $this->events->attach(array('foo', 'bar'), $callback);

$this->assertInternalType('array', $listeners);

foreach ($listeners as $listener) {
$this->assertInstanceOf('Zend\Stdlib\CallbackHandler', $listener);
$this->assertSame($callback, $listener->getCallback());
}
}

public function testDetachShouldRemoveListenerFromEvent()
{
$listener = $this->events->attach('test', array($this, __METHOD__));
Expand Down

0 comments on commit 0f4c6fb

Please sign in to comment.