<?php
/**
 * core.framework
 *
 * @category  Core
 * @package   Core_Application
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */

/**
 * @category  Core
 * @package   Core_Application
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */
class Core_Application_Plugin_EventHandler_AutoResponse extends Core_Application_Plugin_EventHandler_Abstract
{
    /**
     * @var array
     */
    protected $_subscriptions = array(
        array(
            'event'    => Core_Dispatcher::EVENT_POSTDISPATCH,
            'method'   => 'eventHandler',
            'priority' => 999999,
        ),
    );

    /**
     * @var Core_Response
     */
    protected $_response;

    /**
     * @param Core_Response $response
     *
     * @return Core_Application_Plugin_EventHandler_AutoResponse
     */
    public function setResponse(Core_Response $response)
    {
        $this->_response = $response;
        return $this;
    }

    /**
     * @return Core_Response
     */
    public function getResponse()
    {
        if (null === $this->_response) {
            $this->setResponse(Core_Application::get('Response'));
        }
        return $this->_response;
    }

    /**
     * @param Core_Event_Interface $event Event to handle
     * @param mixed                $data  Data to evaluate in event handler
     *
     * @return mixed
     */
    public function eventHandler(Core_Event_Interface $event, $data = null)
    {
        if (!$data instanceof Core_Response) {
            $response = $this->getResponse();
            $response->setBody($data);
            return $response;
        }
        return $data;
    }
}
