Browse Source

Implements a stack of dispatched events #7404

Florian Krämer 10 years ago
parent
commit
5dbb93a785
2 changed files with 44 additions and 0 deletions
  1. 22 0
      src/Event/EventManager.php
  2. 22 0
      tests/TestCase/Event/EventManagerTest.php

+ 22 - 0
src/Event/EventManager.php

@@ -54,6 +54,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
      * other managers were created. Usually for creating hook systems or inter-class
@@ -346,6 +353,7 @@ class EventManager
 
         $listeners = $this->listeners($event->name());
         if (empty($listeners)) {
+            $this->_dispatchedEvents[] = $event;
             return $event;
         }
 
@@ -361,6 +369,7 @@ class EventManager
                 $event->result = $result;
             }
         }
+        $this->_dispatchedEvents[] = $event;
         return $event;
     }
 
@@ -461,6 +470,16 @@ class EventManager
     }
 
     /**
+     * Returns a list of dispatched event objects.
+     *
+     * @return array
+     */
+    public function getDispatchedEvents()
+    {
+        return $this->_dispatchedEvents;
+    }
+
+    /**
      * Debug friendly object properties.
      *
      * @return array
@@ -473,6 +492,9 @@ class EventManager
         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 - 0
tests/TestCase/Event/EventManagerTest.php

@@ -710,4 +710,26 @@ class EventManagerTest extends TestCase
         $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);
+    }
 }