<?php
/**
 * @link      http://github.com/zendframework/zend-mvc-console for the canonical source repository
 * @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Mvc\Console\View;

use Zend\Console\Request as ConsoleRequest;
use Zend\EventManager\AbstractListenerAggregate;
use Zend\EventManager\EventManagerInterface as Events;
use Zend\Mvc\MvcEvent;

class InjectNamedConsoleParamsListener extends AbstractListenerAggregate
{
    /**
     * {@inheritDoc}
     */
    public function attach(Events $events, $priority = 1)
    {
        $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH, [$this, 'injectNamedParams'], -80);
    }

    /**
     * Inspect the result, and cast it to a ViewModel if a string is detected
     *
     * @param MvcEvent $e
     * @return void
    */
    public function injectNamedParams(MvcEvent $e)
    {
        if (! $routeMatch = $e->getRouteMatch()) {
            return; // cannot work without route match
        }

        $request = $e->getRequest();
        if (! $request instanceof ConsoleRequest) {
            return; // will not inject non-console requests
        }

        // Inject route match params into request
        $params = array_merge(
            $request->getParams()->toArray(),
            $routeMatch->getParams()
        );
        $request->getParams()->fromArray($params);
    }
}
