<?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_ArrayRender extends Core_Application_Plugin_EventHandler_Abstract
{
    /**
     * @var array
     */
    protected $_subscriptions = array(
        array(
            'event'    => Core_Dispatcher::EVENT_POSTDISPATCH,
            'method'   => 'eventHandler',
            'priority' => 999,
            'filter'   => 'params.application.context == "web"',
        ),
    );

    /**
     * @var Twig_Environment
     */
    protected $_view;

    /**
     * @param Twig_Environment $view
     *
     * @return Core_Application_Plugin_EventHandler_ArrayRender
     */
    public function setView(Twig_Environment $view)
    {
        $this->_view = $view;
        return $this;
    }

    /**
     * @return Twig_Environment
     */
    public function getView()
    {
        if (null === $this->_view) {
            $this->setView(Core_Application::get('View'));
        }
        return $this->_view;
    }

    /**
     * @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 (is_array($data)) {
            $view     = $this->getView();
            $finder   = $this->getResourceFinder();

            $location = $event->getParam('location');
            $template = $finder->findTemplate($location);
            $data     = $view->loadTemplate($template)->render($data);
        }
        return $data;
    }
}
