EventDispatcher.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Luracast\Restler;
  3. /**
  4. * Static event broadcasting system for Restler
  5. *
  6. * @category Framework
  7. * @package Restler
  8. * @author R.Arul Kumaran <arul@luracast.com>
  9. * @copyright 2010 Luracast
  10. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  11. * @link http://luracast.com/products/restler/
  12. *
  13. */
  14. use Closure;
  15. class EventDispatcher
  16. {
  17. private $listeners = array();
  18. protected static $_waitList = array();
  19. public static $self;
  20. protected $events = array();
  21. public function __construct() {
  22. static::$self = $this;
  23. if (!empty(static::$_waitList)) {
  24. foreach (static::$_waitList as $param) {
  25. call_user_func_array(array($this,$param[0]), $param[1]);
  26. }
  27. }
  28. }
  29. public static function __callStatic($eventName, $params)
  30. {
  31. if (0 === strpos($eventName, 'on')) {
  32. if(static::$self){
  33. return call_user_func_array(array(static::$self, $eventName), $params);
  34. }
  35. static::$_waitList[] = func_get_args();
  36. return false;
  37. }
  38. }
  39. public function __call($eventName, $params)
  40. {
  41. if (0 === strpos($eventName, 'on')) {
  42. if (!isset($this->listeners[$eventName]) || !is_array($this->listeners[$eventName]))
  43. $this->listeners[$eventName] = array();
  44. $this->listeners[$eventName][] = $params[0];
  45. }
  46. return $this;
  47. }
  48. public static function addListener($eventName, Closure $callback)
  49. {
  50. return static::$eventName($callback);
  51. }
  52. public function on(array $eventHandlers)
  53. {
  54. for (
  55. $count = count($eventHandlers),
  56. $events = array_map(
  57. 'ucfirst',
  58. $keys = array_keys(
  59. $eventHandlers = array_change_key_case(
  60. $eventHandlers,
  61. CASE_LOWER
  62. )
  63. )
  64. ),
  65. $i = 0;
  66. $i < $count;
  67. call_user_func(
  68. array($this, "on{$events[$i]}"),
  69. $eventHandlers[$keys[$i++]]
  70. )
  71. );
  72. }
  73. /**
  74. * Fire an event to notify all listeners
  75. *
  76. * @param string $eventName name of the event
  77. * @param array $params event related data
  78. */
  79. protected function dispatch($eventName, array $params = array())
  80. {
  81. $this->events[] = $eventName;
  82. $params = func_get_args();
  83. $eventName = 'on'.ucfirst(array_shift($params));
  84. if (isset($this->listeners[$eventName]))
  85. foreach ($this->listeners[$eventName] as $callback)
  86. call_user_func_array($callback, $params);
  87. }
  88. }