scanner/ncurses/signals.php

54 lines
1.4 KiB
PHP
Raw Normal View History

<?php
class Signaler {
private $_listeners = array();
protected static $current = false;
static public function connect(Signaler &$emitter, $signal, &$responder, $slot) {
if( !is_object($responder) ) {
return false;
}
elseif( !method_exists($responder, $slot) ) {
return false;
}
if( !array_key_exists($signal, $emitter->_listeners) ) {
$emitter->_listeners[$signal] = array();
}
$emitter->_listeners[$signal][] = array(
'object' => &$responder,
'method' => $slot
);
}
protected function emit() {
self::$current = &$this;
$args = func_get_args();
if( count($args) == 0 ) {
// Called without any arguments, raise an error
return false;
}
$signal = array_shift($args);
$sent = 0;
if( array_key_exists($signal, $this->_listeners) ) {
foreach( $this->_listeners[$signal] as $key => $listener ) {
if(
!is_object($listener['object'])
|| !method_exists($listener['object'], $listener['method'])
) {
// Something happened to the object since it was connected,
// and it is no longer usable. Drop it.
unset($this->_listeners[$key]);
} else {
// Everything's good, set the callback loose.
$result = call_user_func_array(array($listener['object'], $listener['method']), $args);
if( $result !== false ) {
$sent++;
}
}
}
}
// Special signal for debugging purposes
if( $signal !== '__emit' ) { $this->emit('__emit', $signal, $args); }
return $sent;
}
}
?>