Inject identity view model into layout

@param MvcEvent $event
@throws \Exception
555985
public function injectIdentityModel(MvcEvent $event)
	{
	    $viewModel = $event->getViewModel();
	    if ($viewModel->getTemplate() == 'layout/layout') {
	        $servies = $event->getApplication()->getServiceManager();
	        $appConfig = $servies->get('config');
	        if (isset($appConfig['view_model_identity'])) {
	            $config = $appConfig['view_model_identity'];
	        } else {
	            throw new \Exception('view_model_identity key not found in configuration');
	        }
	        if (!$servies->has($config['authenticationService'])) {
	            throw new \Exception('Auththentication service not found');
	        }
	        if (!$servies->has($config['identity'])) {
	            throw new \Exception('Identity not found');
	        }
	        $childViewModel = new IdentityViewModel(array(
	            'auth'     => $servies->get($config['authenticationService']),
	            'identity' => $servies->get($config['identity']),
	        ));
	        if (isset($config['template'])) {
	            $childViewModel->setTemplate($config['template']);
	        }
	        if (isset($config['captureTo'])) {
	            $childViewModel->setCaptureTo($config['captureTo']);
	        }
	        $viewModel->addChild($childViewModel);
	    }
	}
877069
public function meAction()
    {
        $event = $this->getEvent();
        $identity = $event->getParam('ZF\MvcAuth\Identity');
        $id = $identity->getName();
        
        $identity = $this->getServiceLocator()->get('KapSecurity\IdentityRepository')->find($id);

        return new ViewModel(array(
            'payload' => new Entity($identity, $identity['id']),
        ));
    }
808173
public function onRoute(MvcEvent $e)
    {
        /* @var $request \Zend\Http\PhpEnvironment\Request */
        $request = $e->getRequest();

        /* Detect language */
        $lang = $request->getQuery('lang');

        if (!$lang) {
            $headers = $request->getHeaders();
            if ($headers->has('Accept-Language')) {
                /* @var $acceptLangs \Zend\Http\Header\AcceptLanguage */
                $acceptLangs = $headers->get('Accept-Language');
                $locales = $acceptLangs->getPrioritized();
                $locale  = $locales[0];
                $lang    = $locale->type;
            } else {
                $lang = 'en';
            }
        }

        /* Set locale */
        $translator = $e->getApplication()->getServiceManager()->get('mvctranslator');
        $locale     = $lang . '_' . strtoupper($lang);

        setlocale(
            LC_ALL,
            array(
                            $locale . ".utf8",
                            $locale . ".iso88591",
                            $locale,
                            substr($locale, 0, 2),
                            'de_DE.utf8',
                            'de_DE',
                            'de'
                        )
        );
        \Locale::setDefault($locale);
        $translator->setLocale($locale);
        $routeMatch = $e->getRouteMatch();
        if ($routeMatch && $routeMatch->getParam('lang') === null) {
            $routeMatch->setParam('lang', $lang);
        }

        /* @var $router \Zend\Mvc\Router\SimpleRouteStack */
        $router = $e->getRouter();
        $router->setDefaultParam('lang', $lang);
    }
560901
public function collect(MvcEvent $mvcEvent)
    {
        if (!$application = $mvcEvent->getApplication()) {
            return;
        }

        $serviceManager = $application->getServiceManager();

        /* @var \ZfcRbac\Service\RoleService $roleService */
        $roleService = $serviceManager->get('ZfcRbac\Service\RoleService');

        /* @var \ZfcRbac\Options\ModuleOptions $options */
        $options = $serviceManager->get('ZfcRbac\Options\ModuleOptions');

        // Start collect all the data we need!
        $this->collectOptions($options);
        $this->collectGuards($options->getGuards());
        $this->collectIdentityRolesAndPermissions($roleService);
    }
846550
public function getTags(MvcEvent $event)
    {
        $routeName = $event->getRouteMatch()->getMatchedRouteName();
        $tags = [
            'route_' . $routeName
        ];
        foreach ($event->getRouteMatch()->getParams() as $key => $value) {
            if ($key == 'controller') {
                $tags[] = 'controller_' . $value;
            } else {
                $tags[] = 'param_' . $key . '_' . $value;
            }
        }

        return $tags;
    }
913331
public function dispatchEvent(MvcEvent $event)
    {
        /**
         * Don't do anything for assets
         */
        $matchRoute = $event->getRouteMatch();
        if (empty($matchRoute)) {
            return null;
        }

        /** @var \Rcm\EventListener\DispatchListener $dispatchListener */
        $dispatchListener
            = $this->serviceLocator->get(\Rcm\EventListener\DispatchListener::class);

        $return = $dispatchListener->setSiteLayout($event);

        if (!empty($return)) {
            return $return;
        }

        return null;
    }
646907
protected function injectLayoutTemplate(MvcEvent $event)
    {
        $model = $event->getResult();

        if (! $model instanceof ViewModel) {
            return $this;
        }
        if ($model->terminate()) {
            return $this;
        }

        $viewManager  = $this->getViewManager();
        $renderer     = $viewManager->getRenderer();

        $themeName    = $this->getThemeName();
        $themeOptions = $this->getThemeOptions();

        $options = [];
        if (isset($themeOptions[static::$side])) {
            $options = $themeOptions[static::$side];
        }

        if (isset($options['layouts'])) {
            $layoutsPath = rtrim($options['layouts'], '/') . '/';
        } else {
            $layoutsPath = str_replace(
                ['{theme}', '{side}'],
                [$themeName, static::$side],
                self::DefaultLayoutsPath
            );
        }

        $layout = $event->getViewModel();
        if ($layout && 'layout/layout' !== $layout->getTemplate()) {
            $layout->setTemplate(
                str_replace('{layouts}', $layoutsPath, $layout->getTemplate())
            );
            return $this;
        }

        $defaultLayout = self::DefaultLayout;
        if(isset($options['default_layout'])) {
            $defaultLayout = $options['default_layout'];
        }
        $renderer->layout()->setTemplate($layoutsPath . $defaultLayout);

        return $this;
    }
623052
public function injectLinkHeader(MvcEvent $e)
    {
    	$response = $e->getResponse();
    	$headers  = $response->getHeaders();
//     	$headers->addHeaderLine('Link', sprintf(
// 			'<%s>; rel="describedby"',
// 			$this->url()->fromRoute('static-classified-service')
//     	));
    	$headers->addHeaderLine('Access-Control-Allow-Origin', '*');
    	$headers->addHeaderLine('Access-Control-Allow-Methods', 'POST PUT DELETE GET');
    	 
    }
1265150
public function preDispatch(MvcEvent $e) {
		if ($this->zfcUserAuthentication ()->hasIdentity ()) {
			$userName = $this->zfcUserAuthentication ()->getIdentity ()->getUsername ();
		} else {
			$userName = 'anonymous';
		}
		$this->layout ()->setVariable ( 'dataTypes', $this->getDataTypesHandler ()->getDataTypes () );
		$this->layout ()->setVariable ( 'userName', $userName );
		$this->layout ()->setVariable ( 'action', $this->params ( 'action' ) );
		$this->layout ()->setVariable ( 'authService', $this->getFileAuthService () );
		$this->layout ()->setVariable ( 'jqueryUiTheme', $this->getJqueryUiTheme () );
		$controller = $this->params ( 'controller' );
		$controller = explode ( '\\', $controller );
		$controller = array_pop ( $controller );
		$controller = strtolower ( $controller );
		$this->layout ()->setVariable ( 'controller', $controller );
	}
122554
public function routeSave(MvcEvent $event)
    {
        $match = $event->getRouteMatch();
        if(!$match) {
            return;
        }
    
        if($event->getParam('route-cached') || !$event->getParam('route-cacheable')) {
            return;
        }
    
        $path = $event->getRequest()
                      ->getUri()
                      ->getPath();
    
        // save the route match into the cache.
        $cache = $event->getApplication()->getServiceManager()->get('var-cache');
        $cacheKey = $this->getCacheKey($path);
        $data = array (
            'name'  => $event->getRouteMatch()->getMatchedRouteName(),
            'route' => $path,
            'defaults' => $event->getRouteMatch()->getParams(),
        );
        $cache->setItem($cacheKey, $data);
    }
1289487
public function onDispatch(MvcEvent $e)
    {
        $console = $this->getServiceLocator()->get('Console');
        if (!$console instanceof ConsoleAdapterInterface) {
            throw new \DomainException('Could not find console service. Are you sure this was invoked from command line?');
        }

        $manager = $this->getServiceLocator()->get('ModuleManager');
        if (!$manager instanceof ModuleManager) {
            $console->write('Could not find module manager - exit!' . "\n", ColorInterface::RED);
            return;
        }

        foreach ($manager->getLoadedModules() as $name => $module) {
            if (!is_callable(array($module, 'compile'))) {
                continue;
            }

            $console->write(sprintf('Compiling module "%s" ...' . "\n", $name));
            $module->compile();
        }

        $console->write('Done!' . "\n\n", ColorInterface::LIGHT_GREEN);
    }
830955
public function handleView(ViewEvent $event)
    {
        if (!$this->scopeDeterminator->currentScopeIsBackend()) {
            return;
        }

        if (DcGeneralViews::CLIPBOARD !== $event->getViewName()) {
            return;
        }

        $environment     = $event->getEnvironment();
        $input           = $environment->getInputProvider();
        $eventDispatcher = $environment->getEventDispatcher();
        $basicDefinition = $environment->getDataDefinition()->getBasicDefinition();

        $filter = new Filter();
        $filter->andModelIsFromProvider($basicDefinition->getDataProvider());
        if ($parentProviderName = $basicDefinition->getParentDataProvider()) {
            $filter->andParentIsFromProvider($parentProviderName);
        } else {
            $filter->andHasNoParent();
        }

        $options = [];
        foreach ($environment->getClipboard()->fetch($filter) as $item) {
            $modelId      = $item->getModelId();
            $dataProvider = $environment->getDataProvider($item->getDataProviderName());

            if ($modelId) {
                $config = $dataProvider->getEmptyConfig();
                $config->setId($modelId->getId());
                $model = $dataProvider->fetch($config);

                // The model might have been deleted meanwhile.
                if (!$model) {
                    continue;
                }

                $formatModelLabelEvent = new FormatModelLabelEvent($environment, $model);
                $eventDispatcher->dispatch(DcGeneralEvents::FORMAT_MODEL_LABEL, $formatModelLabelEvent);
                $label = $formatModelLabelEvent->getLabel();
                $label = \array_shift($label);
                $label = $label['content'];
            } else {
                $model = $dataProvider->getEmptyModel();
                $label = $environment->getTranslator()->translate('new.0', $item->getDataProviderName());
            }

            $options[$item->getClipboardId()] = ['item'  => $item, 'model' => $model, 'label' => $label];
        }

        $inputAction   = $input->getParameter('act');
        $addToUrlEvent = new AddToUrlEvent('act=clear-clipboard&original-act=' . $inputAction);
        $eventDispatcher->dispatch(ContaoEvents::BACKEND_ADD_TO_URL, $addToUrlEvent);
        $clearUrl = $addToUrlEvent->getUrl();

        $addToUrlEvent = new AddToUrlEvent(
            'clipboard-item=%id%&act=clear-clipboard&original-act=' . $inputAction
        );
        $eventDispatcher->dispatch(ContaoEvents::BACKEND_ADD_TO_URL, $addToUrlEvent);
        $clearItemUrl = $addToUrlEvent->getUrl();

        $template = new ContaoBackendViewTemplate('dcbe_general_clipboard');
        $template
            ->set('environment', $environment)
            ->set('options', $options)
            ->set('clearUrl', $clearUrl)
            ->set('clearItemUrl', $clearItemUrl);

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

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

        return parent::onDispatch( $event );
    }
277452
public function injectToolbarHtml(MvcEvent $event)
    {
        if (! $inspection = $event->getParam(ApplicationInspectorListener::PARAM_INSPECTION)) {
            return;
        }

        $response = $event->getResponse();

        if (! $response instanceof Response) {
            return;
        }

        $headers     = $response->getHeaders();
        $contentType = $headers->get('Content-Type');

        if ($contentType) {
            if (!$contentType instanceof ContentType) {
                return;
            }

            if (false === strpos(strtolower($contentType->getFieldValue()), 'html')) {
                return;
            }
        }

        $response->setContent(preg_replace(
            '/<\/body>/i',
            $this->renderer->render($this->inspectionRenderer->render($inspection)) . '</body>',
            $response->getContent(),
            1
        ));
    }
459423
public function collect(MvcEvent $mvcEvent)
    {
        $layout = $mvcEvent->getViewModel();
        $blocks = [];
        foreach ($this->layout->getBlocks() as $blockId => $block) {
            if ($parentBlock = $block->getOption('parent')) {
                $captureTo = $parentBlock . '::' . $block->captureTo();
            } else {
                $captureTo = $block->captureTo();
            }
            $blocks[$blockId] = [
                'instance' => $block,
                'template' => $this->resolveTemplate($block->getTemplate()),
                'capture_to' => $captureTo,
                'class' => get_class($block)
            ];
        }
        $data = [
            'handles' => $this->updater->getHandles(true),
            'layout_structure' => $this->updater->getLayoutStructure()->toArray(),
            'blocks' => $blocks,
            'layout_template' => $layout->getTemplate(),
            'current_area' => $this->updater->getArea()
        ];

        $this->data = $data;
        return $this;
    }
446593
public function onDispatch(MvcEvent $event)
    {
        /* @var $service \BjyAuthorize\Service\Authorize */
        $service    = $this->serviceLocator->get('BjyAuthorize\Service\Authorize');
        $match      = $event->getRouteMatch();
        $controller = $match->getParam('controller');
        $action     = $match->getParam('action');
        $request    = $event->getRequest();
        $method     = $request instanceof HttpRequest ? strtolower($request->getMethod()) : null;

        $authorized = $service->isAllowed($this->getResourceName($controller))
            || $service->isAllowed($this->getResourceName($controller, $action))
            || ($method && $service->isAllowed($this->getResourceName($controller, $method)));

        if ($authorized) {
            return;
        }

        $event->setError(static::ERROR);
        $event->setParam('identity', $service->getIdentity());
        $event->setParam('controller', $controller);
        $event->setParam('action', $action);

        $errorMessage = sprintf("You are not authorized to access %s:%s", $controller, $action);
        $event->setParam('exception', new UnAuthorizedException($errorMessage));

        /* @var $app \Zend\Mvc\ApplicationInterface */
        $app = $event->getTarget();
        $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
    }
897156
public function onDispatch( MvcEvent $event )
    {
        $store   = $this->getStore();
        $request = $event->getRequest();
        $service = $this->getServiceLocator();
        $locale  = $service->get( 'AdminLocale' );
        $parent  = $request->getQuery( 'parentId' );

        if ( empty( $store['adminLocale'] ) )
        {
            $store['adminLocale'] = $locale->getCurrent();
        }

        if ( ! empty( $parent ) )
        {
            $store['parentId'] = $parent;
        }

        return parent::onDispatch( $event );
    }