getViewModel() public method

Get the view model
public getViewModel ( ) : Zend\View\Model\ModelInterface
return Zend\View\Model\ModelInterface
示例#1
0
 /**
  * Add the ACL of this module to the global ACL
  *
  * @param MvcEvent $e 
  * @return void
  */
 public function initAcl(MvcEvent $e)
 {
     if ($e->getViewModel()->acl == null) {
         $acl = new Acl();
     } else {
         $acl = $e->getViewModel()->acl;
     }
     $aclConfig = (include __DIR__ . '/config/module.acl.php');
     $allResources = array();
     foreach ($aclConfig['roles'] as $role) {
         if (!$acl->hasRole($role)) {
             $role = new Role($role);
             $acl->addRole($role);
         } else {
             $role = $acl->getRole($role);
         }
         if (array_key_exists($role->getRoleId(), $aclConfig['permissions'])) {
             foreach ($aclConfig['permissions'][$role->getRoleId()] as $resource) {
                 if (!$acl->hasResource($resource)) {
                     $acl->addResource(new Resource($resource));
                 }
                 $acl->allow($role, $resource);
             }
         }
     }
     $e->getViewModel()->acl = $acl;
 }
 public function onBootstrap(MvcEvent $e)
 {
     $app = $e->getApplication();
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $sm = $app->getServiceManager();
     $list = $this->whitelist;
     $auth = $sm->get('AuthService');
     $e->getViewModel()->setVariable('hasIdentity', $auth->hasIdentity());
     if ($auth->hasIdentity()) {
         $e->getViewModel()->setVariable('currentUserId', $auth->getStorage()->read()->id);
     } else {
         $e->getViewModel()->setVariable('currentUserId', -1);
     }
     $eventManager->attach(MvcEvent::EVENT_ROUTE, function ($e) use($list, $auth) {
         $match = $e->getRouteMatch();
         // No route match, this is a 404
         if (!$match instanceof RouteMatch) {
             return;
         } else {
             // Route is whitelisted
             $name = $match->getMatchedRouteName();
             if (in_array($name, $list)) {
                 if ($auth->hasIdentity() && $name != 'login/process') {
                     $router = $e->getRouter();
                     $url = $router->assemble(array(), array('name' => 'home'));
                     $response = $e->getResponse();
                     $response->getHeaders()->addHeaderLine('Location', $url);
                     $response->setStatusCode(302);
                     return $response;
                 } else {
                     return;
                 }
             } else {
                 // User is authenticated
                 if ($auth->hasIdentity() && $name != 'auth/logout') {
                     // $id = $this->UserAuthentication()->getIdentity()->getId();
                     // var_dump(($auth->getIdentity()));
                     // exit;
                     // var_dump($name);exit;
                     return;
                 } else {
                     // Redirect to the user login page, as an example
                     $router = $e->getRouter();
                     $url = $router->assemble(array(), array('name' => 'login'));
                     $response = $e->getResponse();
                     $response->getHeaders()->addHeaderLine('Location', $url);
                     $response->setStatusCode(302);
                     return $response;
                 }
             }
         }
     }, -100);
 }
示例#3
0
 public function injectLayoutMenu(MvcEvent $event)
 {
     $viewModel = $event->getViewModel();
     if ($viewModel instanceof ViewModel && $viewModel->getTemplate() == 'layout/layout') {
         $access = $event->getApplication()->getServiceManager()->get(ServiceFactory::SERVICE);
         if ($access->isAuthorized()) {
             $viewModel = new ViewModel();
             $viewModel->setTemplate('spork-tools/footer');
             $event->getViewModel()->addChild($viewModel, 'sporkToolsMenu');
         }
     }
 }
示例#4
0
 public function dispatch(MvcEvent $event)
 {
     $auth = new AuthenticationService();
     if (!$auth->hasIdentity()) {
         $router = $event->getRouteMatch();
         if (method_exists($router, 'getMatchedRouteName') && $router->getMatchedRouteName() == 'home') {
             $event->getViewModel()->setTemplate('layout/landing');
         } else {
             $event->getViewModel()->setTemplate('layout/anonymous');
         }
     }
 }
 public function checkAcl(MvcEvent $e)
 {
     $route = $e->getRouteMatch()->getMatchedRouteName();
     //you set your role
     $userRole = 'guest';
     if ($e->getViewModel()->acl->hasResource($route) && !$e->getViewModel()->acl->isAllowed($userRole, $route)) {
         $response = $e->getResponse();
         //location to page or what ever
         $response->getHeaders()->addHeaderLine('Location', $e->getRequest()->getBaseUrl() . '/404');
         $response->setStatusCode(404);
     }
 }
示例#6
0
 /**
  * Switch layout based on user's role
  *
  * @param MvcEvent $e
  */
 public function updateLayout(MvcEvent $e)
 {
     $params = $e->getRouteMatch()->getParams();
     if (isset($params['backend']) && $params['backend'] && Authentication::getInstance()->hasIdentity()) {
         $config = $e->getApplication()->getServiceManager()->get('config');
         $role = Authentication::getInstance()->getIdentity()->role;
         $layouts = $config['acl']['backend_layout'];
         if ($role && isset($layouts['roles'][$role])) {
             $e->getViewModel()->setTemplate($layouts['roles'][$role]);
         } else {
             $e->getViewModel()->setTemplate($layouts['default']);
         }
     }
 }
示例#7
0
 /**
  * @inheritdoc
  */
 public function collect(MvcEvent $mvcEvent)
 {
     $templates = array();
     $match = $mvcEvent->getRouteMatch();
     $templates[] = $mvcEvent->getViewModel()->getTemplate();
     if ($mvcEvent->getViewModel()->hasChildren()) {
         foreach ($mvcEvent->getViewModel()->getChildren() as $child) {
             $templates[] = $child->getTemplate();
         }
     }
     if (empty($templates)) {
         $templates[] = 'N/A';
     }
     $this->data = array('templates' => $templates, 'method' => $mvcEvent->getRequest()->getMethod(), 'status' => $mvcEvent->getResponse()->getStatusCode(), 'route' => $match === null ? 'N/A' : $match->getMatchedRouteName(), 'action' => $match === null ? 'N/A' : $match->getParam('action', 'N/A'), 'controller' => $match === null ? 'N/A' : $match->getParam('controller', 'N/A'));
 }
示例#8
0
 public function onBootstrap(MvcEvent $e)
 {
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $e->getViewModel()->tags = $e->getApplication()->getServiceManager()->get('TagService')->getMostPopularTags();
 }
 public function __invoke(MvcEvent $event)
 {
     if ($event->getViewModel()->terminate()) {
         /*
          * No need for navigation when it is not rendered anyway.
          */
         return;
     }
     $services = $event->getApplication()->getServiceManager();
     $navigation = $services->get('Core/Navigation');
     $settingsMenu = $navigation->findOneBy('route', 'lang/settings');
     if ($settingsMenu->hasChildren()) {
         /*
          * We already have the subnavigation.
          */
         return;
     }
     $moduleManager = $services->get('ModuleManager');
     $configPlugin = $services->get('ControllerPluginManager')->get('config');
     $modules = $moduleManager->getLoadedModules();
     $modulesWithSettings = $configPlugin("settings", array_keys($modules));
     $routeMatch = $event->getRouteMatch();
     $router = $event->getRouter();
     $activeModule = $event->getParam('__settings_active_module', false);
     $settingsMenu->setActive((bool) $activeModule);
     foreach ($modulesWithSettings as $key => $param) {
         $page = array('label' => isset($param['navigation_label']) ? $param['navigation_label'] : ucfirst($key), 'order' => isset($param['navigation_order']) ? $param['navigation_order'] : '10', 'class' => isset($param['navigation_class']) ? $param['navigation_class'] : null, 'resource' => 'route/lang/settings', 'route' => 'lang/settings', 'router' => $router, 'action' => 'index', 'controller' => 'index', 'params' => array('lang' => 'de', 'module' => $key), 'active' => $key == $activeModule);
         if ($routeMatch instanceof RouteMatch) {
             $page['routeMatch'] = $routeMatch;
         }
         $settingsMenu->addPage($page);
     }
 }
示例#10
0
 public function checkAuth(MvcEvent $e)
 {
     $sm = $e->getApplication()->getServiceManager();
     $auth = $sm->get('AuthService');
     $match = $e->getRouteMatch();
     if (!$match instanceof RouteMatch) {
         return;
     }
     $name = $match->getMatchedRouteName();
     if (in_array($name, $this->publicRoutes)) {
         return;
     }
     //Check identity
     if ($auth->hasIdentity()) {
         $viewModel = $e->getViewModel();
         $viewModel->current_user = $auth->getIdentity();
         return;
     }
     $router = $e->getRouter();
     $url = $router->assemble(array(), array('name' => 'auth'));
     $response = $e->getResponse();
     $response->getHeaders()->addHeaderLine('Location', $url);
     $response->setStatusCode(302);
     return $response;
 }
 /**
  * Render the view
  *
  * @param  MvcEvent $e
  * @return Response
  */
 public function render(MvcEvent $e)
 {
     $result = $e->getResult();
     if ($result instanceof Response) {
         return $result;
     }
     // Martial arguments
     $request = $e->getRequest();
     $response = $e->getResponse();
     $viewModel = $e->getViewModel();
     if (!$viewModel instanceof ViewModel) {
         return;
     }
     $view = $this->view;
     $view->setRequest($request);
     $view->setResponse($response);
     try {
         $view->render($viewModel);
     } catch (\Exception $ex) {
         if ($e->getName() === MvcEvent::EVENT_RENDER_ERROR) {
             throw $ex;
         }
         $application = $e->getApplication();
         $events = $application->getEventManager();
         $e->setError(Application::ERROR_EXCEPTION)->setParam('exception', $ex);
         $events->trigger(MvcEvent::EVENT_RENDER_ERROR, $e);
     }
     return $response;
 }
示例#12
0
 /**
  * Inject identity view model into layout
  * 
  * @param MvcEvent $event
  * @throws \Exception
  */
 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);
     }
 }
示例#13
0
 public function onDispatch(MvcEvent $e)
 {
     $sm = $e->getApplication()->getServiceManager();
     $categories = $sm->get('categories');
     $vm = $e->getViewModel();
     $vm->setVariable('categories', $categories);
 }
 public function layoutChange(MvcEvent $event)
 {
     // Change By Route Defaults
     $routeMatch = $event->getRouteMatch();
     if ($routeMatch && ($layout = $routeMatch->getParam('layout', false))) {
         $event->getTarget()->layout($layout);
         return;
     }
     /** @var \Zend\Http\PhpEnvironment\Request $request */
     $request = $event->getRequest();
     $uri = $request->getServer('REQUEST_URI');
     $config = $this->getConfig($event->getParam('application')->getConfig());
     // Change Layout by URI
     foreach ($config['uri'] as $var => $value) {
         $position = strpos($var, '*');
         if ($position !== false) {
             $uri = substr($uri, 0, $position);
             $var = substr($var, 0, $position);
         }
         if ($var == $uri) {
             if (method_exists($target = $event->getTarget(), 'layout')) {
                 $target->layout($value);
             } else {
                 $event->getViewModel()->setTemplate($value);
             }
         }
     }
 }
示例#15
0
 public function onBootstrap(MvcEvent $e)
 {
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     // Show flashmessages in the view
     $eventManager->attach(MvcEvent::EVENT_RENDER, function ($e) {
         $flashMessenger = new FlashMessenger();
         $messages = array();
         $flashMessenger->setNamespace('success');
         if ($flashMessenger->hasMessages()) {
             $messages['success'] = $flashMessenger->getMessages();
         }
         $flashMessenger->clearMessages();
         $flashMessenger->setNamespace('warning');
         if ($flashMessenger->hasMessages()) {
             $messages['warning'] = $flashMessenger->getMessages();
         }
         $flashMessenger->clearMessages();
         $flashMessenger->setNamespace('danger');
         if ($flashMessenger->hasMessages()) {
             $messages['danger'] = $flashMessenger->getMessages();
         }
         $flashMessenger->clearMessages();
         $e->getViewModel()->setVariable('flashMessages', $messages);
     });
 }
示例#16
0
 public function onDispatchError(MvcEvent $e, $controllerName)
 {
     $app = $e->getApplication();
     $sm = $app->getServiceManager();
     $viewModel = $e->getViewModel();
     $viewModel->setTemplate('error/403');
 }
示例#17
0
 /**
  * Handle layout titles onDispatch.
  *
  * @param MvcEvent $event
  */
 public function setTitleAndTranslation(MvcEvent $event)
 {
     $route = $event->getRouteMatch();
     $title = $this->service->get('ControllerPluginManager')->get('systemsettings');
     $viewHelper = $this->service->get('ViewHelperManager');
     $lang = new Container('translations');
     $translator = $this->service->get('translator');
     /*
      * Load translations.
      */
     $renderer = $this->service->get('ViewManager')->getRenderer();
     $renderer->plugin('formRow')->setTranslator($translator, 'SD_Translations');
     $renderer->plugin('formCollection')->setTranslator($translator, 'SD_Translations');
     $renderer->plugin('formLabel')->setTranslator($translator, 'SD_Translations');
     $renderer->plugin('formSelect')->setTranslator($translator, 'SD_Translations');
     $renderer->plugin('formSubmit')->setTranslator($translator, 'SD_Translations');
     AbstractValidator::setDefaultTranslator($translator, 'formandtitle');
     $translator->setLocale($lang->offsetGet('languageName'))->setFallbackLocale('en');
     $viewModel = $event->getViewModel();
     $viewModel->setVariable('lang', $translator->getLocale());
     /*
      * Custom flash messenger.
      */
     $msg = $lang->offsetGet('flashMessages');
     $viewModel->setVariable('flashMessages', $msg);
     /*
      * Load page title
      */
     $action = $route->getParam('post') ? ' - ' . $route->getParam('post') : ucfirst($route->getParam('__CONTROLLER__'));
     $headTitleHelper = $viewHelper->get('headTitle');
     $headTitleHelper->append($title->__invoke('general', 'site_name') . ' ' . $action);
 }
 public function onPreBootstrap(MvcEvent $e)
 {
     $application = $e->getApplication();
     $services = $application->getServiceManager();
     $events = $application->getEventManager();
     $config = $services->has('Config') ? $services->get('Config') : [];
     // Check Database connectivity
     if ($services->has('Zend\\Db\\Adapter\\Adapter')) {
         $adapter = $services->get('Zend\\Db\\Adapter\\Adapter');
         try {
             $adapter->getDriver()->getConnection()->connect();
         } catch (\Exception $ex) {
             $viewManagerConfig = $config['view_manager'] ? $config['view_manager'] : [];
             $response = $e->getResponse();
             $viewModel = $e->getViewModel();
             $template = isset($viewManagerConfig['service_unavailable_template']) ? $viewManagerConfig['service_unavailable_template'] : '503';
             $viewModel->setTemplate($template);
             if ($response instanceof HttpResponse) {
                 $response->setStatusCode(503);
             } elseif ($response instanceof ConsoleModel) {
                 $response->setErrorLevel(1);
             } else {
                 echo "Service Unavailable.";
                 exit(1);
             }
             $event = $e;
             $event->setResponse($response);
             $event->setTarget($application);
             $events->trigger(MvcEvent::EVENT_RENDER, $event);
             $events->trigger(MvcEvent::EVENT_FINISH, $event);
             $e->stopPropagation(true);
             exit(1);
         }
     }
     // Maintenance mode
     // Session Management
     if (!$services->has('Zend\\Session\\Config\\ConfigInterface')) {
         if (isset($config['session_config'])) {
             $services->setFactory('Zend\\Session\\ConfigInterface', 'Zend\\Session\\Service\\SessionConfigFactory');
         }
     }
     if (!$services->has('Zend\\Session\\Storage\\StorageInterface')) {
         if (isset($config['session_storage'])) {
             $services->setFactory('Zend\\Session\\StorageInterface', 'Zend\\Session\\Service\\StorageFactory');
         }
     }
     if (!$services->has('Zend\\Session\\SaveHandler\\SaveHandlerInterface')) {
         if ($services->has('Zend\\Db\\Adapter\\Adapter')) {
             $adapter = $services->get('Zend\\Db\\Adapter\\Adapter');
             $tableGateway = new TableGateway('sessions', $adapter);
             $options = new DbTableGatewayOptions();
             $sessionHandler = new DbTableGateway($tableGateway, $options);
             $services->setService('Zend\\Session\\SaveHandler\\SaveHandlerInterface', $sessionHandler);
         }
     }
     if (!$services->has('Zend\\Session\\ManagerInterface')) {
         $services->setFactory('Zend\\Session\\ManagerInterface', 'Zend\\Session\\Service\\SessionManagerFactory');
     }
 }
 public function injectView(MvcEvent $event)
 {
     $viewModel = $event->getViewModel();
     $this->viewModel = $viewModel;
     if ($event->getApplication()->getServiceManager()->has('viewHelperManager')) {
         $this->viewHelperManager = $event->getApplication()->getServiceManager()->get('ViewHelperManager');
     }
 }
示例#20
0
 /**
  * load layout if result ist not terminated
  *
  * @param MvcEvent $e
  */
 public function loadLayout(MvcEvent $e)
 {
     /* @var $result ModelInterface */
     $result = $e->getViewModel();
     if (!$result->terminate()) {
         $this->layout->load();
     }
 }
示例#21
0
文件: Module.php 项目: veniva/zcms
 public function addMenu(MvcEvent $event)
 {
     $viewModel = $event->getViewModel();
     $serviceManager = $event->getApplication()->getServiceManager();
     $menuView = new ViewModel(['categories' => $this->getTopCategories($serviceManager)]);
     $menuView->setTemplate('menu/layout');
     $viewModel->addChild($menuView, 'mainMenu');
 }
示例#22
0
文件: Module.php 项目: veniva/zcms
 public function addLanguages(MvcEvent $event)
 {
     $serviceManager = $event->getApplication()->getServiceManager();
     $viewModel = $event->getViewModel();
     $languagesView = new ViewModel(['languages' => $serviceManager->get('language')]);
     $languagesView->setTemplate('languages/layout');
     $viewModel->addChild($languagesView, 'activeLanguages');
 }
示例#23
0
文件: Module.php 项目: 06romix/store
 /**
  * @param MvcEvent $e
  */
 public function setLayout($e)
 {
     $matches = $e->getRouteMatch();
     $action = $matches->getParam('action');
     $controller = $matches->getParam('controller');
     // Blank page for JS
     if (in_array($action, array('delete', 'products', 'users', 'updateBasket'), 0)) {
         $viewModel = $e->getViewModel();
         $viewModel->setTemplate('layout/blank');
         return;
     }
     if (in_array($controller, array('test', 'Api\\Controller\\Index'), 0)) {
         // Set the layout template
         $viewModel = $e->getViewModel();
         $viewModel->setTemplate('layout/layout');
         return;
     }
 }
 /**
  * Configures the MvcEvent view model to ensure it has the template injected
  *
  * @return \Zend\View\Model\ModelInterface
  */
 public function getViewModel()
 {
     if ($this->viewModel) {
         return $this->viewModel;
     }
     $this->viewModel = $model = $this->event->getViewModel();
     $model->setTemplate($this->getLayoutTemplate());
     return $this->viewModel;
 }
示例#25
-1
文件: Module.php 项目: neuweb/idauth
 public function processUnAuth(MvcEvent $e)
 {
     //$d = new \Zend\Debug\Debug(); $d->dump($e->getError());
     $error = $e->getError();
     if ($e->getError() === 'error-route-unauthorized') {
         $sm = $e->getApplication()->getServiceManager();
         $conf = $sm->get('IdAuth\\Config');
         if ($conf['settings']['useDifferentLayoutForUnAuth']) {
             $user = new Forms\Login();
             $builder = new \Zend\Form\Annotation\AnnotationBuilder();
             $loginForm = $builder->createForm($user);
             $view = $e->getViewModel();
             $view->loginForm = $loginForm;
             $view->setTemplate('idauth/locked');
             $view->error = $error;
             $auth = $sm->get('IdAuthService');
             $hasIdentity = $auth->hasIdentity();
             if ($hasIdentity) {
                 $view->gravatarEmail = $auth->getIdentity()->getEmail();
             } else {
                 $view->gravatarEmail = null;
             }
             $view->hasIdentity = $auth->hasIdentity();
             $view->identity = $auth->getIdentity();
             $view->route = $e->getRouteMatch()->getMatchedRouteName();
         }
     }
 }
 public function prepareViewModel(MvcEvent $e)
 {
     // Do nothing if the result is a response object
     $result = $e->getResult();
     if ($result instanceof Response) {
         return;
     }
     // Common view variables
     $viewVariables = array('error' => $e->getParam('error'), 'identity' => $e->getParam('identity'));
     $error = $e->getError();
     switch ($error) {
         case 'error-unauthorized-controller':
             $viewVariables['controller'] = $e->getParam('controller');
             $viewVariables['action'] = $e->getParam('action');
             break;
         case 'error-unauthorized-route':
             $viewVariables['route'] = $e->getParam('route');
             break;
         default:
             // Do nothing if no error in the event
             return;
     }
     $model = new ViewModel($viewVariables);
     $model->setTemplate($this->getTemplate());
     $e->getViewModel()->addChild($model);
     $response = $e->getResponse();
     if (!$response) {
         $response = new HttpResponse();
         $e->setResponse($response);
     }
     $response->setStatusCode(403);
 }
示例#27
-1
 public function onDispatchError(MvcEvent $event)
 {
     $result = $event->getResult();
     $response = $event->getResponse();
     if ($result instanceof Response || $response && !$response instanceof HttpResponse) {
         return;
     }
     $viewVariables = array('error' => $event->getParam('error'), 'identity' => $event->getParam('identity'));
     switch ($event->getError()) {
         case Application::ERROR_EXCEPTION:
             if (!$event->getParam('exception') instanceof NotFoundException) {
                 return;
             }
             $viewVariables['reason'] = $event->getParam('exception')->getMessage();
             $viewVariables['error'] = 'error-unauthorized';
             break;
         default:
             return;
     }
     $model = new ViewModel($viewVariables);
     $response = $response ?: new HttpResponse();
     $model->setTemplate($this->getTemplate());
     $event->getViewModel()->addChild($model);
     $response->setStatusCode(404);
     $event->setResponse($response);
 }
示例#28
-1
 /**
  * Listen for specific thrown exceptions and display the proper error page
  * and code for each.
  *
  * @param MvcEvent $e
  */
 public function handleException(MvcEvent $e)
 {
     $result = $e->getResult();
     // Don't interfere with a complete response.
     if ($result instanceof ResponseInterface) {
         return;
     }
     // Only handle exceptions.
     if ($e->getError() !== ZendApplication::ERROR_EXCEPTION) {
         return;
     }
     $exception = $e->getParam('exception');
     $this->getServiceLocator()->get('Omeka\\Logger')->err((string) $exception);
     if ($exception instanceof AclException\PermissionDeniedException) {
         $template = 'error/403';
         $status = 403;
     } else {
         if ($exception instanceof ApiException\NotFoundException || $exception instanceof MvcException\NotFoundException) {
             $template = 'error/404';
             $status = 404;
         } else {
             return;
         }
     }
     $model = new ViewModel(['exception' => $exception]);
     $model->setTemplate($template);
     $response = $e->getResponse();
     if (!$response) {
         $response = new Response();
     }
     $response->setStatusCode($status);
     $e->setResponse($response);
     $e->getViewModel()->addChild($model);
 }
示例#29
-1
文件: Module.php 项目: jbarentsen/drb
    /**
     * @param MvcEvent $e
     * @return void|ViewModel
     */
    public function handleDispatchErrors(MvcEvent $e)
    {
        $exception = $e->getParam('exception');
        $routeMatch = $e->getRouteMatch();
        if (!$routeMatch || $exception instanceof UnauthorizedException) {
            // We don't handle permissions errors or unmatched routes
            return;
        }

        // We will do the final handling here
        $e->stopPropagation();

        if (Console::isConsole()) {
            return;
        }
        $error = $e->getError();
        $model = new ViewModel(
            [
                'message' => 'An error occurred. Good luck!<br/><br/><pre>' . $exception->getMessage() . '</pre>',
                'reason' => $error,
                'exception' => $exception,
            ]
        );
        $model->setTemplate('error/404');
        $e->getViewModel()->addChild($model);

        $response = $e->getResponse();
        $response->setStatusCode(404);

        return $model;
    }
示例#30
-1
 public function onDispatchError(MvcEvent $e)
 {
     $result = $e->getResult();
     $response = $e->getResponse();
     if ($result instanceof Response || $response && !$response instanceof HttpResponse) {
         return;
     }
     $viewVariables = array('error' => $e->getParam('error'), 'identity' => $e->getParam('identity'));
     switch ($e->getError()) {
         case Controller::ERROR:
             $viewVariables['controller'] = $e->getParam('controller');
             $viewVariables['action'] = $e->getParam('action');
             $router = $e->getRouter();
             if ($e->getParam('exception') instanceof UnAuthorizedException && !$e->getApplication()->getServiceManager()->get('Zend\\Authentication\\AuthenticationService')->hasIdentity()) {
                 $session = new Container('location');
                 $session->location = $e->getRequest()->getUri();
                 // get url to the login route
                 $options['name'] = 'login';
                 $url = $router->assemble(array(), $options);
                 if (!$response) {
                     $response = new HttpResponse();
                     $e->setResponse($response);
                 }
                 if ($e->getRequest()->isXmlHttpRequest()) {
                     $response->setStatusCode(204);
                     $response->getHeaders()->addHeaderLine('Fury-Redirect', $url);
                 } else {
                     $response->setStatusCode(302);
                     $response->getHeaders()->addHeaderLine('Location', $url);
                 }
                 return;
             }
             break;
         case Route::ERROR:
             $viewVariables['route'] = $e->getParam('route');
             break;
         case Application::ERROR_EXCEPTION:
             if (!$e->getParam('exception') instanceof UnAuthorizedException) {
                 return;
             }
             $viewVariables['reason'] = $e->getParam('exception')->getMessage();
             $viewVariables['error'] = 'error-unauthorized';
             break;
         default:
             /*
              * do nothing if there is no error in the event or the error
              * does not match one of our predefined errors (we don't want
              * our 403 template to handle other types of errors)
              */
             return;
     }
     $model = new ViewModel($viewVariables);
     $response = $response ?: new HttpResponse();
     $model->setTemplate($this->getTemplate());
     $e->getViewModel()->addChild($model);
     $response->setStatusCode(403);
     $e->setResponse($response);
 }