<?php
/**
 * Event mediator class
 * @author Jérôme Brilland
 * @version 1.0
 * @package Bluebird
 * @copyright Copyright &copy; 2014, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 * @since Version 1.6
 */
class EventMediator {
    
    /**
     * @var array Associative array of listeners
     * @access public
     */
    protected $listeners = array();
    
    /**
     * @param string eventName Event name
     * @param mixed callback Listener
     * @access public
     */
    public function attach( $eventName, $callback ) {
        if ( !is_string( $eventName ) ) {
            throw new InvalidArgumentException();
        }
        if ( !is_callable( $callback ) ) {
            throw new InvalidArgumentException();
        }
        if ( !array_key_exists( $eventName, $this->listeners ) ) {
            $this->listeners[$eventName] = array();
        }
        $this->listeners[$eventName][] = $callback;
    }
    
    /**
     * @param string eventName Event name
     * @param array data Parameters
     * @access public
     */
    public function trigger( $eventName, $data = null ) {
        if ( !is_string( $eventName ) ) {
            throw new InvalidArgumentException();
        }
        if ( array_key_exists( $eventName, $this->listeners ) ) {
            foreach( $this->listeners[$eventName] as $callback ) {
                if ( is_array( $data ) ) {
                    if ( !call_user_func_array( $callback, $data ) ) {
                        break;
                    }
                } else {
                    if ( !$callback( $data ) ) {
                        break;
                    }
                }
            }
        }
    }
    
}

