PageRenderTime 72ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/libs/Event/Dispatcher.php

https://github.com/quarkness/piwik
PHP | 485 lines | 195 code | 34 blank | 256 comment | 52 complexity | 9fea5f62541fb5e8d81c751ec03de41d MD5 | raw file
  1. <?php
  2. // +-----------------------------------------------------------------------+
  3. // | Copyright (c) 2005, Bertrand Mansion |
  4. // | All rights reserved. |
  5. // | |
  6. // | Redistribution and use in source and binary forms, with or without |
  7. // | modification, are permitted provided that the following conditions |
  8. // | are met: |
  9. // | |
  10. // | o Redistributions of source code must retain the above copyright |
  11. // | notice, this list of conditions and the following disclaimer. |
  12. // | o Redistributions in binary form must reproduce the above copyright |
  13. // | notice, this list of conditions and the following disclaimer in the |
  14. // | documentation and/or other materials provided with the distribution.|
  15. // | o The names of the authors may not be used to endorse or promote |
  16. // | products derived from this software without specific prior written |
  17. // | permission. |
  18. // | |
  19. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  20. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  21. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
  22. // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
  23. // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
  24. // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
  25. // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
  26. // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
  27. // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
  28. // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
  29. // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
  30. // | |
  31. // +-----------------------------------------------------------------------+
  32. // | Author: Bertrand Mansion <bmansion@mamasam.com> |
  33. // | Stephan Schmidt <schst@php.net> |
  34. // +-----------------------------------------------------------------------+
  35. //
  36. // $Id$
  37. /**
  38. * Pseudo 'static property' for Notification object
  39. * @global array $GLOBALS["_Event_Dispatcher"]
  40. */
  41. $GLOBALS['_Event_Dispatcher'] = array(
  42. 'NotificationClass' => 'Event_Notification'
  43. );
  44. /**
  45. * Registers a global observer
  46. */
  47. define('EVENT_DISPATCHER_GLOBAL', '');
  48. /**
  49. * Dispatch notifications using PHP callbacks
  50. *
  51. * The Event_Dispatcher acts acts as a notification dispatch table.
  52. * It is used to notify other objects of interesting things, if
  53. * they meet certain criteria. This information is encapsulated
  54. * in {@link Event_Notification} objects. Client objects register
  55. * themselves with the Event_Dispatcher as observers of specific
  56. * notifications posted by other objects. When an event occurs,
  57. * an object posts an appropriate notification to the Event_Dispatcher.
  58. * The Event_Dispatcher dispatches a message to each
  59. * registered observer, passing the notification as the sole argument.
  60. *
  61. * The Event_Dispatcher is actually a combination of three design
  62. * patterns: the Singleton, {@link http://c2.com/cgi/wiki?MediatorPattern Mediator},
  63. * and Observer patterns. The idea behind Event_Dispatcher is borrowed from
  64. * {@link http://developer.apple.com/documentation/Cocoa/Conceptual/Notifications/index.html Apple's Cocoa framework}.
  65. *
  66. * @category Event
  67. * @package Event_Dispatcher
  68. * @author Bertrand Mansion <bmansion@mamasam.com>
  69. * @author Stephan Schmidt <schst@php.net>
  70. * @copyright 1997-2005 The PHP Group
  71. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  72. * @version Release: @package_version@
  73. * @link http://pear.php.net/package/Event_Dispatcher
  74. */
  75. class Event_Dispatcher
  76. {
  77. /**
  78. * Registered observer callbacks
  79. * @var array
  80. * @access private
  81. */
  82. var $_ro = array();
  83. /**
  84. * Pending notifications
  85. * @var array
  86. * @access private
  87. */
  88. var $_pending = array();
  89. /**
  90. * Nested observers
  91. * @var array
  92. * @access private
  93. */
  94. var $_nestedDispatchers = array();
  95. /**
  96. * Name of the dispatcher
  97. * @var string
  98. * @access private
  99. */
  100. var $_name = null;
  101. /**
  102. * Class used for notifications
  103. * @var string
  104. * @access private
  105. */
  106. var $_notificationClass = null;
  107. /**
  108. * PHP4 constructor
  109. *
  110. * Please use {@link getInstance()} instead.
  111. *
  112. * @access private
  113. * @param string Name of the notification dispatcher.
  114. */
  115. // function Event_Dispatcher($name)
  116. // {
  117. // Event_Dispatcher::__construct($name);
  118. // }
  119. /**
  120. * PHP5 constructor
  121. *
  122. * Please use {@link getInstance()} instead.
  123. *
  124. * @access private
  125. * @param string Name of the notification dispatcher.
  126. */
  127. function __construct($name)
  128. {
  129. $this->_name = $name;
  130. $this->_notificationClass = $GLOBALS['_Event_Dispatcher']['NotificationClass'];
  131. }
  132. /**
  133. * Returns a notification dispatcher singleton
  134. *
  135. * There is usually no need to have more than one notification
  136. * center for an application so this is the recommended way
  137. * to get a Event_Dispatcher object.
  138. *
  139. * @param string Name of the notification dispatcher.
  140. * The default notification dispatcher is named __default.
  141. *
  142. * @return object Event_Dispatcher
  143. */
  144. static function getInstance($name = '__default')
  145. {
  146. static $dispatchers = array();
  147. if (!isset($dispatchers[$name])) {
  148. $dispatchers[$name] = new Event_Dispatcher($name);
  149. }
  150. return $dispatchers[$name];
  151. }
  152. /**
  153. * Registers an observer callback
  154. *
  155. * This method registers a {@link http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback callback}
  156. * which is called when the notification corresponding to the
  157. * criteria given at registration time is posted.
  158. * The criteria are the notification name and eventually the
  159. * class of the object posted with the notification.
  160. *
  161. * If there are any pending notifications corresponding to the criteria
  162. * given here, the callback will be called straight away.
  163. *
  164. * If the notification name is empty, the observer will receive all the
  165. * posted notifications. Same goes for the class name.
  166. *
  167. * @access public
  168. * @param mixed A PHP callback
  169. * @param string Expected notification name, serves as a filter
  170. * @param string Expected contained object class, serves as a filter
  171. * @return void
  172. */
  173. function addObserver($callback, $nName = EVENT_DISPATCHER_GLOBAL, $class = null)
  174. {
  175. if (is_array($callback)) {
  176. if (is_object($callback[0])) {
  177. // Note : PHP4 does not allow correct object comparison so
  178. // only the class name is used for registration checks.
  179. $reg = get_class($callback[0]).'::'.$callback[1];
  180. } else {
  181. $reg = $callback[0].'::'.$callback[1];
  182. }
  183. } else {
  184. $reg = $callback;
  185. }
  186. $this->_ro[$nName][$reg] = array(
  187. 'callback' => $callback,
  188. 'class' => $class
  189. );
  190. // Post eventual pending notifications for this observer
  191. if (isset($this->_pending[$nName])) {
  192. foreach (array_keys($this->_pending[$nName]) as $k) {
  193. $notification =& $this->_pending[$nName][$k];
  194. if (!$notification->isNotificationCancelled()) {
  195. $object = $notification->getNotificationObject();
  196. $objClass = is_object($object) ? get_class($object) : null;
  197. if (empty($class) || strcasecmp($class, $objClass) == 0) {
  198. call_user_func_array($callback, array(&$notification));
  199. //-- Piwik Hack --//
  200. $notification->increaseNotificationCount($callback);
  201. //-- End Piwik Hack --//
  202. }
  203. }
  204. }
  205. }
  206. }
  207. /**
  208. * Creates and posts a notification object
  209. *
  210. * The purpose of the optional associated object is generally to pass
  211. * the object posting the notification to the observers, so that the
  212. * observers can query the posting object for more information about
  213. * the event.
  214. *
  215. * Notifications are by default added to a pending notification list.
  216. * This way, if an observer is not registered by the time they are
  217. * posted, it will still be notified when it is added as an observer.
  218. * This behaviour can be turned off in order to make sure that only
  219. * the registered observers will be notified.
  220. *
  221. * The info array serves as a container for any kind of useful
  222. * information. It is added to the notification object and posted along.
  223. *
  224. * @access public
  225. * @param object Notification associated object
  226. * @param string Notification name
  227. * @param array Optional user information
  228. * @param bool Whether the notification is pending
  229. * @param bool Whether you want the notification to bubble up
  230. * @return object The notification object
  231. */
  232. function &post(&$object, $nName, $info = array(), $pending = true, $bubble = true)
  233. {
  234. $notification = new $this->_notificationClass($object, $nName, $info);
  235. return $this->postNotification($notification, $pending, $bubble);
  236. }
  237. /**
  238. * Posts the {@link Event_Notification} object
  239. *
  240. * @access public
  241. * @param object The Notification object
  242. * @param bool Whether to post the notification immediately
  243. * @param bool Whether you want the notification to bubble up
  244. * @see Event_Dispatcher::post()
  245. * @return object The notification object
  246. */
  247. function &postNotification(&$notification, $pending = true, $bubble = true)
  248. {
  249. $nName = $notification->getNotificationName();
  250. if ($pending === true) {
  251. $this->_pending[$nName][] =& $notification;
  252. }
  253. $object = $notification->getNotificationObject();
  254. $objClass = is_object($object) ? get_class($object) : null;
  255. // Find the registered observers
  256. if (isset($this->_ro[$nName])) {
  257. foreach (array_keys($this->_ro[$nName]) as $k) {
  258. $rObserver =& $this->_ro[$nName][$k];
  259. if ($notification->isNotificationCancelled()) {
  260. return $notification;
  261. }
  262. if (empty($rObserver['class']) ||
  263. strcasecmp($rObserver['class'], $objClass) == 0) {
  264. $callback = $rObserver['callback'];
  265. call_user_func_array($callback, array(&$notification));
  266. //-- Piwik Hack --//
  267. $notification->increaseNotificationCount($callback);
  268. //-- End Piwik Hack --//
  269. }
  270. }
  271. }
  272. // Notify globally registered observers
  273. if (isset($this->_ro[EVENT_DISPATCHER_GLOBAL])) {
  274. foreach (array_keys($this->_ro[EVENT_DISPATCHER_GLOBAL]) as $k) {
  275. $rObserver =& $this->_ro[EVENT_DISPATCHER_GLOBAL][$k];
  276. if ($notification->isNotificationCancelled()) {
  277. return $notification;
  278. }
  279. if (empty($rObserver['class']) ||
  280. strcasecmp($rObserver['class'], $objClass) == 0) {
  281. call_user_func_array($rObserver['callback'], array(&$notification));
  282. //-- Piwik Hack --//
  283. $notification->increaseNotificationCount(get_class($rObserver['callback'][0]), $rObserver['callback'][1]);
  284. //-- End Piwik Hack --//
  285. }
  286. }
  287. }
  288. if ($bubble === false) {
  289. return $notification;
  290. }
  291. // Notify in nested dispatchers
  292. foreach (array_keys($this->_nestedDispatchers) as $nested) {
  293. $notification =& $this->_nestedDispatchers[$nested]->postNotification($notification, $pending);
  294. }
  295. return $notification;
  296. }
  297. /**
  298. * Removes a registered observer that correspond to the given criteria
  299. *
  300. * @access public
  301. * @param mixed A PHP callback
  302. * @param string Notification name
  303. * @param string Contained object class
  304. * @return bool True if an observer was removed, false otherwise
  305. */
  306. function removeObserver($callback, $nName = EVENT_DISPATCHER_GLOBAL, $class = null)
  307. {
  308. if (is_array($callback)) {
  309. if (is_object($callback[0])) {
  310. $reg = get_class($callback[0]).'::'.$callback[1];
  311. } else {
  312. $reg = $callback[0].'::'.$callback[1];
  313. }
  314. } else {
  315. $reg = $callback;
  316. }
  317. $removed = false;
  318. if (isset($this->_ro[$nName][$reg])) {
  319. if (!empty($class)) {
  320. if (strcasecmp($this->_ro[$nName][$reg]['class'], $class) == 0) {
  321. unset($this->_ro[$nName][$reg]);
  322. $removed = true;
  323. }
  324. } else {
  325. unset($this->_ro[$nName][$reg]);
  326. $removed = true;
  327. }
  328. }
  329. if (isset($this->_ro[$nName]) && count($this->_ro[$nName]) == 0) {
  330. unset($this->_ro[$nName]);
  331. }
  332. return $removed;
  333. }
  334. /**
  335. * Check, whether the specified observer has been registered with the
  336. * dispatcher
  337. *
  338. * @access public
  339. * @param mixed A PHP callback
  340. * @param string Notification name
  341. * @param string Contained object class
  342. * @return bool True if the observer has been registered, false otherwise
  343. */
  344. function observerRegistered($callback, $nName = EVENT_DISPATCHER_GLOBAL, $class = null)
  345. {
  346. if (is_array($callback)) {
  347. if (is_object($callback[0])) {
  348. $reg = get_class($callback[0]).'::'.$callback[1];
  349. } else {
  350. $reg = $callback[0].'::'.$callback[1];
  351. }
  352. } else {
  353. $reg = $callback;
  354. }
  355. if (!isset($this->_ro[$nName][$reg])) {
  356. return false;
  357. }
  358. if (empty($class)) {
  359. return true;
  360. }
  361. if (strcasecmp($this->_ro[$nName][$reg]['class'], $class) == 0) {
  362. return true;
  363. }
  364. return false;
  365. }
  366. /**
  367. * Get all observers, that have been registered for a notification
  368. *
  369. * @access public
  370. * @param string Notification name
  371. * @param string Contained object class
  372. * @return array List of all observers
  373. */
  374. function getObservers($nName = EVENT_DISPATCHER_GLOBAL, $class = null)
  375. {
  376. $observers = array();
  377. if (!isset($this->_ro[$nName])) {
  378. return $observers;
  379. }
  380. foreach ($this->_ro[$nName] as $reg => $observer) {
  381. if ($class == null || $observer['class'] == null || strcasecmp($observer['class'], $class) == 0) {
  382. $observers[] = $reg;
  383. }
  384. }
  385. return $observers;
  386. }
  387. /**
  388. * Get the name of the dispatcher.
  389. *
  390. * The name is the unique identifier of a dispatcher.
  391. *
  392. * @access public
  393. * @return string name of the dispatcher
  394. */
  395. function getName()
  396. {
  397. return $this->_name;
  398. }
  399. /**
  400. * add a new nested dispatcher
  401. *
  402. * Notifications will be broadcasted to this dispatcher as well, which
  403. * allows you to create event bubbling.
  404. *
  405. * @access public
  406. * @param Event_Dispatcher The nested dispatcher
  407. */
  408. function addNestedDispatcher(&$dispatcher)
  409. {
  410. $name = $dispatcher->getName();
  411. $this->_nestedDispatchers[$name] =& $dispatcher;
  412. }
  413. /**
  414. * remove a nested dispatcher
  415. *
  416. * @access public
  417. * @param Event_Dispatcher Dispatcher to remove
  418. * @return boolean
  419. */
  420. function removeNestedDispatcher($dispatcher)
  421. {
  422. if (is_object($dispatcher)) {
  423. $dispatcher = $dispatcher->getName();
  424. }
  425. if (!isset($this->_nestedDispatchers[$dispatcher])) {
  426. return false;
  427. }
  428. unset($this->_nestedDispatchers[$dispatcher]);
  429. return true;
  430. }
  431. /**
  432. * Changes the class used for notifications
  433. *
  434. * You may call this method on an object to change it for a single
  435. * dispatcher or statically, to set the default for all dispatchers
  436. * that will be created.
  437. *
  438. * @access public
  439. * @param string name of the notification class
  440. * @return boolean
  441. */
  442. function setNotificationClass($class)
  443. {
  444. if (isset($this) && is_a($this, 'Event_Dispatcher')) {
  445. $this->_notificationClass = $class;
  446. return true;
  447. }
  448. $GLOBALS['_Event_Dispatcher']['NotificationClass'] = $class;
  449. return true;
  450. }
  451. }