mirror of
https://github.com/kamilwylegala/cakephp2-php8.git
synced 2024-11-15 11:28:25 +00:00
Implementing subscriber detaching
This commit is contained in:
parent
adf95a7ac6
commit
bb62f05890
2 changed files with 47 additions and 0 deletions
|
@ -88,6 +88,9 @@ class CakeEventManager {
|
|||
* @return void
|
||||
*/
|
||||
public function detach($callable, $eventKey = null) {
|
||||
if ($callable instanceof CakeEventListener) {
|
||||
return $this->_detachSubscriber($callable, $eventKey);
|
||||
}
|
||||
if (empty($eventKey)) {
|
||||
foreach (array_keys($this->_listeners) as $eventKey) {
|
||||
$this->detach($callable, $eventKey);
|
||||
|
@ -107,6 +110,28 @@ class CakeEventManager {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Auxiliary function to help detach all listeners provided by an object implementing CakeEventListener
|
||||
*
|
||||
* @param CakeEventListener $subscriber the subscriber to be detached
|
||||
* @param string $eventKey optional event key name to unsubscribe the listener from
|
||||
* @return void
|
||||
*/
|
||||
protected function _detachSubscriber(CakeEventListener $subscriber, $eventKey = null) {
|
||||
$events = $subscriber->implementedEvents();
|
||||
if (!empty($eventKey) && empty($events[$eventKey])) {
|
||||
return;
|
||||
} else if (!empty($eventKey)) {
|
||||
$events = array($eventKey => $events[$eventKey]);
|
||||
}
|
||||
foreach ($events as $key => $function) {
|
||||
if (is_array($function)) {
|
||||
$function = $function['callable'];
|
||||
}
|
||||
$this->detach(array($subscriber, $function), $key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches a new event to all configured listeners
|
||||
*
|
||||
|
|
|
@ -251,4 +251,26 @@ class CakeEventManagerTest extends CakeTestCase {
|
|||
$event = new CakeEvent('another.event', $this, array('some' => 'data'));
|
||||
$manager->dispatch($event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests subscribing a listener object and firing the events it subscribed to
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function testDetachSubscriber() {
|
||||
$manager = new CakeEventManager;
|
||||
$listener = $this->getMock('CustomTestEventListerner', array('secondListenerFunction'));
|
||||
$manager->attach($listener);
|
||||
$expected = array(
|
||||
array('callable' => array($listener, 'secondListenerFunction'), 'passParams' => true)
|
||||
);
|
||||
$this->assertEquals($expected, $manager->listeners('another.event'));
|
||||
$expected = array(
|
||||
array('callable' => array($listener, 'listenerFunction'), 'passParams' => false)
|
||||
);
|
||||
$this->assertEquals($expected, $manager->listeners('fake.event'));
|
||||
$manager->detach($listener);
|
||||
$this->assertEquals(array(), $manager->listeners('fake.event'));
|
||||
$this->assertEquals(array(), $manager->listeners('another.event'));
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue