load layout if result ist not terminated

@param MvcEvent $e
19730
public function loadLayout(MvcEvent $e)
    {
        /* @var $result ModelInterface */
        $result = $e->getViewModel();
        if (!$result->terminate()) {
            $this->layout->load();
        }
    }
370372
public function routeLoad(MvcEvent $event)
    {
        $request = $event->getRequest();
        if(!(
            $request instanceof HttpRequest &&
            $request->isGet() &&
            $request->getQuery()->count() == 0
        )) {
            // We do not cache route match for requests that can produce
            // different match.
            return;
        }

        $event->setParam('route-cacheable', true);

        // check if we have data in our cache
        $path = $request->getUri()->getPath();

        $services = $event->getApplication()->getServiceManager();

        $cacheName = $services->get(RouterCacheOptions::class)->getCache();
        $cache = $services->get($cacheName);

        $cacheKey = $this->getCacheKey($path);
        $cachedData = $cache->getItem($cacheKey);

        if($cachedData) {
            $event->setParam('route-cached', true);
            $router = $event->getRouter();
            $router->addRoute($cachedData['name'], $cachedData['spec'], round(PHP_INT_MAX/2));
        }
    }
757986
public function onDispatchedListener(MvcEvent $event)
    {
        $data = $event->getTarget()->getData();
        $config = [];
        try {
            $config = $event->getApplication()->getServiceManager()->get('ApplicationConfig');
        } catch (\Psr\Container\ContainerExceptionInterface $e) {
            //todo
        }
        $data['env'] = isset($config['application']['env']) ? $config['application']['env'] : 'development';


        if (BaseController::RESPONSE_JSON == $data[BaseController::RS_KEY_TYPE] ||
            BaseController::RESPONSE_PLAIN == $data[BaseController::RS_KEY_TYPE]
        ) {
            $response = $event->getResponse();
            if (!$response instanceof Response) {
                $response = new Response();
            }

            $contentType = new ContentType();
            $contentType->setCharset('UTF-8');

            $content = '';

            if (BaseController::RESPONSE_JSON == $data[BaseController::RS_KEY_TYPE]) {
                $contentType->setMediaType('application/json');

                $content = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
            }

            if (BaseController::RESPONSE_PLAIN == $data[BaseController::RS_KEY_TYPE]) {
                $contentType->setMediaType('text/plain');
                $data = $data[BaseController::RS_KEY_DATA];
                if (!$data instanceof \stdClass) {
                    $content = '';
                } else {
                    if (isset($data->content)) {
                        $content = $data->content;
                    } else {
                        $data = json_decode(json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE), true);
                        $content = implode('', $data);
                    }
                }
            }

            $response->getHeaders()->addHeader($contentType);
            $response->setContent($content);

            $event->setResult($response); //Stop render event

            return;
        }


        $request = $event->getRequest();
        if (!$request instanceof Request) {
            throw new RuntimeException('The request is invalid', 1001);
        }

        if ($request->isXmlHttpRequest()) {
            $result = $event->getResult();
            if ($result)
            if (!$result instanceof ViewModel) {
                $result = new ViewModel();
            }

            $result->setTerminal(true); //Disabled layout
            $result->setVariables($data);

            $event->setViewModel($result);
            $event->setResult($result);
        } else {
            $model = $event->getViewModel();
            $model->setVariables($data);
            if ($model->hasChildren()) {
                foreach($model->getChildren() as $child) {
                    if ($child instanceof ViewModel) {
                        $child->setVariables($data);
                    }
                }
            }
        }

    }
1196949
public function checkRedirect(MvcEvent $event)
    {
        if ($this->isConsoleRequest()) {
            return null;
        }

        // User defaults
        $redirectUrl = $this->redirectService->getRedirectUrl();

        if (empty($redirectUrl)) {
            return null;
        }


        $queryParams = $event->getRequest()->getQuery()->toArray();

        header(
            'Location: ' . $redirectUrl . (count($queryParams) ? '?' . http_build_query($queryParams) : null),
            true,
            302
        );
        exit;

        /* Below is the ZF2 way but Response is not short-circuiting the event like it should *
        $response = new Response();
        $response->setStatusCode(302);
        $response->getHeaders()
            ->addHeaderLine(
                'Location',
                $redirect->getRedirectUrl()
            );
        $event->stopPropagation(true);

        return $response;
        */
    }
300482
public function setupLayout(MvcEvent $event)
    {
        $viewModel = $event->getResult();
        if (!$this->viewRenderer instanceof PhpRenderer
            || !$viewModel instanceof ViewModel
            || $viewModel->terminate()) {
            return;
        }
        $this->configureView();
    }
664223
public function onDispatchError(MvcEvent $event)
    {
        // Do nothing if the result is a response object
        $result     = $event->getResult();
        $routeMatch = $event->getRouteMatch();
        $response   = $event->getResponse();
        $router     = $event->getRouter();
        $error      = $event->getError();
        $url        = $this->redirectUri;

        if ($result instanceof Response
            || ! $routeMatch
            || ($response && ! $response instanceof Response)
            || ! (
                Route::ERROR === $error
                || Controller::ERROR === $error
                || (
                    Application::ERROR_EXCEPTION === $error
                    && ($event->getParam('exception') instanceof UnAuthorizedException)
                )
            )
        ) {
            return;
        }

        if (null === $url) {
            $url = $router->assemble(array(), array('name' => $this->redirectRoute));
        }

        $response = $response ?: new Response();

        $response->getHeaders()->addHeaderLine('Location', $url);
        $response->setStatusCode(302);

        $event->setResponse($response);
    }
701761
public function processRcmResponses(MvcEvent $event)
    {
        $response = $event->getResult();

        if (!$response instanceof RcmResponse) {
            return null;
        }

        $this->responseHandler->processResponse($response);

        return null;
    }
258963
function onMvcErrorInjectViewTemplate($e)
    {
        if (!$this->error)
            // We have no error detected on prev. event
            return;

        $result = $e->getResult();
        if ($result instanceof Response)
            // Already Have A Response As Result
            return;

        if ($result instanceof ModelInterface)
            // Already Have A View Model
            return;

        if (ArrayUtils::hasStringKeys($result, true))
            $result = new ViewModel($result);
        else
            $result = new ViewModel(['exception_result' => $result]);

        $result->setVariable('exception'
            , new \Exception(
                'An error occurred during execution; please try again later.'
                , null
                , $e->getError()
            )
        );

        $result->setVariable('original_exception', $e->getError());

        $result->setVariable('display_exceptions', (error_reporting() != 0));

        $result->setTemplate(
            $this->__getExceptionTemplate($this->error)
        );

        $e->setResult($result);
    }
1160302
public function onDispatch(MvcEvent $e)
    {
        $request = $e->getRequest();
        if (!$request instanceof HttpRequest) {
            throw new RuntimeException('CRUD controller from CmsCommon can only handle HTTP requests');
        }

        $action = $this->params()->fromRoute('action', 'not-found');
        $method = static::getMethodFromAction($action);

        if (!method_exists($this, $method)) {
            $method = 'notFoundAction';
        }

        $object = null;
        if ($action === static::ACTION_READ ||
            $action === static::ACTION_UPDATE ||
            $action === static::ACTION_DELETE
        ) {
            $options = $this->getOptions();
            $id = $this->params()->fromRoute($options->getIdentifierKey());

            if (null === $id) {
                $this->flashMessenger()->addWarningMessage(sprintf(
                    $this->translate('An identifier must be provided to %s an object'),
                    $this->translate($action)
                ));

                return $this->redirectToBaseRoute();
            }

            if (!($object = $this->getDomainService()->getMapper()->find($id))) {
                $this->flashMessenger()->addWarningMessage($this->translate('An object cannot be found'));
                return $this->redirectToBaseRoute();
            }
        }

        $data = $this->getData($object);

        // Return early if getData method returned a response
        if ($data instanceof ResponseInterface) {
            $actionResponse = $data;
        } else {
            switch ($action) {
                case static::ACTION_READ:
                case static::ACTION_DELETE:
                    $actionResponse = $this->$method($data, $object);
                    break;
                case static::ACTION_UPDATE:
                    $actionResponse = $this->$method($data, $object);
                    break;
                default:
                    $actionResponse = $this->$method($data);
            }
        }

        $e->setResult($actionResponse);
    }
280098
public function setupModuleOptionsEventParam(MvcEvent $e)
    {
        $services = $e->getApplication()->getServiceManager();
        $config = $services->get('Config');
        if (empty($config[static::OPTIONS_CONFIG_KEY])) {
            return;
        }

        $routeMatch = $e->getRouteMatch();
        $moduleNamespace = $routeMatch->getParam(
            ModuleRouteListener::MODULE_NAMESPACE,
            $routeMatch->getParam('controller')
        );

        $module = strstr($moduleNamespace, '\\', true);

        foreach ($config[static::OPTIONS_CONFIG_KEY] as $suffix) {
            $name = "$module\\$suffix";
            if ((class_exists($name) || interface_exists($name)) && $services->has($name)) {
                $moduleOptions = $services->get($name);
                if ($moduleOptions instanceof AbstractOptions) {
                    //set module options as MvcEvent param
                    $e->setParam('module-options', $moduleOptions);
                }

                break;
            }
        }
    }
553664
public function onDispatch( MvcEvent $event )
    {
        $this->paragraphId = (int) $this->params()
                                        ->fromRoute( 'paragraphId' );

        if ( empty( $this->paragraphId ) )
        {
            $this->paragraphId = null;
        }

        return parent::onDispatch( $event );
    }
98817
public function setAssets(MvcEvent $e)
    {
        /* @var AssetsServiceInterface $assetsService */
        $assetsService = $e->getApplication()->getServiceManager()->get('AcAssets\Service\AssetsService');
        $assetsService->initHeadLink()
                      ->initHeadScript()
                      ->initInlineScript();
    }
602031
public function logError(MvcEvent $e)
    {
        /** @var \Exception $exception */
        $exception = $e->getResult()->exception;

        if (!$exception) {
            return;
        }

        $extra = [
            'file'  => $exception->getFile(),
            'line'  => $exception->getLine(),
            'trace' => $exception->getTrace()
        ];

        if ($exception instanceof ErrorException) {
            /** @var ErrorException $exception */
            $extra['severity'] = $exception->getSeverity();
        }

        $this->logger->err($exception->getMessage(), $extra);
    }
319235
function onRenderRenderWidgets(ViewEvent $e)
    {
        $viewModel = $e->getModel();

        $return = false;

        $options = $viewModel->getOptions();
        if (/*!array_key_exists('has_parent', $options) &&*/ !self::$resolved) {
            $return = new PhpRenderer;
            $return->setServiceLocator($this->sm);

             //self::$resolved = true;
        }

        return $return;
    }
61980
public function preDispatch(MvcEvent $event)
    {
        $this->layout()->setVariable('lang', $this->params('lang'));

        $p       = $this->params()->fromQuery('p');
        $request = $this->getRequest();

        if ($p && $request->isXmlHttpRequest()) {
            $routeMatch = $event->getRouteMatch();
            $routeMatch->setParam('action', $p);
            $response = $this->getResponse();
            $response->getHeaders()
                     ->addHeaderLine('Content-Type', 'application/json')
                     ->addHeaderLine('Content-Encoding', 'utf8');
        }
    }
210394
public function preDispatch(MvcEvent $e)
    {
        if ('calculate' == $this->params()->fromQuery('do')) {
            return;
        }
        $routeMatch = $e->getRouteMatch();
        $action = $routeMatch->getParam('action');
	    $services = $e->getApplication()->getServiceManager();
        if (in_array($action, array('edit', 'approval', 'completion'))) {
            $jobEvents = $services->get('Jobs/Events');
            $mailSender = $services->get('Jobs/Listener/MailSender');

            $mailSender->attach($jobEvents);
        }
    }
1364162
public function addLocale(MvcEvent $event)
    {
        $locale = $this->siteService->getCurrentSite()->getLocale();

        $this->localeService->setLocale($locale);

        return null;
    }