getResult() public method

Get result
public getResult ( ) : mixed
return mixed
Esempio n. 1
0
 /**
  * Boostrap
  *
  * @param MvcEvent $mvcEvent
  */
 public function onBootstrap(MvcEvent $mvcEvent)
 {
     $eventManager = $mvcEvent->getApplication()->getEventManager();
     /**
      * Disable Layout on Error
      */
     $eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function ($mvcEvent) {
         /**
          * @var MvcEvent $mvcEvent
          */
         $mvcEvent->getResult()->setTerminal(true);
     });
     $sharedEvents = $eventManager->getSharedManager();
     /**
      * Disable Layout in ViewModel
      */
     $sharedEvents->attach('Zend\\Mvc\\Controller\\AbstractActionController', 'dispatch', function ($mvcEvent) {
         /**
          * @var MvcEvent $mvcEvent
          */
         $result = $mvcEvent->getResult();
         if ($result instanceof ViewModel) {
             $result->setTerminal(true);
         }
     });
     $mvcEvent->getApplication()->getEventManager()->getSharedManager()->attach('Mp3\\Controller\\SearchController', 'Mp3Help', function ($event) use($mvcEvent) {
         /**
          * @var MvcEvent $event
          */
         echo $mvcEvent->getApplication()->getServiceManager()->get('Mp3\\Service\\Search')->help($event->getParam('help'));
     });
 }
 public function prepareViewModel(MvcEvent $event, $action)
 {
     if ($event->getTarget()->forward()->getNumNestedForwards() > 0) {
         return $event->getResult();
     }
     $result = $event->getResult();
     $response = $event->getResponse();
     $response->setStatusCode($result->getStatusCode());
     $response->getHeaders()->addHeaders($result->getHeaders());
     $controller = $event->getTarget();
     $viewModel = $controller->acceptableViewModelSelector($controller->getOptions()->getAcceptCriteria());
     if ($vars = $result->getSerializedModel()) {
         $viewModel->setVariables($vars);
     }
     //set the template
     if ($viewModel instanceof JsonModel && count($viewModel->getVariables()) == 0) {
         if ($response->getStatusCode() == 200) {
             $response->setStatusCode(204);
         }
         return $response;
     } elseif ($viewModel->getTemplate() == null) {
         $viewModel->setTemplate($controller->getOptions()->getTemplates()[$action]);
     }
     $event->setResult($viewModel);
     return $viewModel;
 }
Esempio n. 3
0
 public function disableLayouts(MvcEvent $e)
 {
     $latteResolver = $this->sm->get('Zf2Latte\\LatteResolver');
     $viewModel = $e->getResult();
     if ($latteResolver->resolve($viewModel->getTemplate())) {
         $e->getResult()->setTerminal(true);
     }
 }
Esempio n. 4
0
 /**
  * Renders ZF1 response into a ZF2 response
  *
  * @param \Zend\Mvc\MvcEvent $e
  * @return \Zend\Stdlib\ResponseInterface|null
  */
 public function onRender(MvcEvent $e)
 {
     if (!$e->getResult() instanceof \Zend_Controller_Response_Abstract) {
         return;
     }
     $response = $e->getResponse();
     $this->renderIntoResponse($response, $e->getResult());
     $e->setResult($response);
     return $response;
 }
 protected function addLocationHeader(MvcEvent $event)
 {
     $options = $event->getTarget()->getOptions();
     if ($property = $options->getProperty()) {
         $result = $event->getResult();
         $createdDocument = $result->getModel();
         $result->addHeader(Location::fromString('Location: ' . $event->getRequest()->getUri()->getPath() . '/' . $options->getModelManager()->getClassMetadata(get_class($createdDocument))->getFieldValue($createdDocument, $property)));
     }
     return $event->getResult();
 }
 public function flush(MvcEvent $event)
 {
     if ($event->getTarget()->forward()->getNumNestedForwards() > 0) {
         return $event->getResult();
     }
     $options = $event->getTarget()->getOptions();
     $options->getModelManager()->flush();
     if (!($flushExceptions = $options->getExceptionSubscriber()->getFlushExceptions())) {
         return $event->getResult();
     } else {
         return $this->prepareExceptions($flushExceptions, $options->getExceptionSerializer());
     }
 }
 public function testPopulateResponse()
 {
     $exception = new Exception\Client\BadRequestException('Validation errors', ['email' => 'invalid']);
     $this->event->setParam('exception', $exception);
     $this->httpExceptionListener->onDispatchError($this->event);
     $response = $this->event->getResponse();
     $expectedContent = ['status_code' => 400, 'message' => 'Validation errors', 'errors' => ['email' => 'invalid']];
     $this->assertNotSame($this->response, $response, 'Assert response is replaced');
     $this->assertInstanceOf(Response::class, $this->event->getResponse());
     $this->assertInstanceOf(Response::class, $this->event->getResult());
     $this->assertEquals($expectedContent, json_decode($this->event->getResponse()->getContent(), true));
     $this->assertTrue($this->event->propagationIsStopped());
 }
 public function unserializeSingle(MvcEvent $event, $mode)
 {
     if (count($event->getParam('deeperResource')) > 0 || ($result = $event->getResult())) {
         return $event->getResult();
     }
     $data = $event->getParam('data');
     $id = $event->getParam('id');
     $options = $event->getTarget()->getOptions();
     if ($property = $options->getProperty()) {
         $data[$property] = $id;
     }
     $result = new Result($event->getTarget()->getOptions()->getManifest()->getServiceManager()->get('unserializer')->fromArray($data, $event->getTarget()->getOptions()->getClass(), $event->getParam('document'), $mode));
     $event->setResult($result);
     return $result;
 }
 protected function onInvokation(MvcEvent $e, $error = false)
 {
     $viewModel = $e->getResult();
     $isJsonModel = $viewModel instanceof JsonModel;
     $routeMatch = $e->getRouteMatch();
     if ($routeMatch && $routeMatch->getParam('forceJson', false) || $isJsonModel || "json" == $e->getRequest()->getQuery('format') || "json" == $e->getRequest()->getPost('format')) {
         if (!$isJsonModel) {
             $model = new JsonModel();
             if ($error) {
                 $model->status = 'error';
                 $model->message = $viewModel->message;
                 if ($viewModel->display_exceptions) {
                     if (isset($viewModel->exception)) {
                         $model->exception = $viewModel->exception->getMessage();
                     }
                 }
             } else {
                 $model->setVariables($viewModel->getVariables());
             }
             $viewModel = $model;
             $e->setResult($model);
             $e->setViewModel($model);
         }
         $viewModel->setTerminal(true);
         $strategy = new \Zend\View\Strategy\JsonStrategy(new \Zend\View\Renderer\JsonRenderer());
         $view = $e->getApplication()->getServiceManager()->get('ViewManager')->getView();
         $view->addRenderingStrategy(array($strategy, 'selectRenderer'), 10);
         $view->addResponseStrategy(array($strategy, 'injectResponse'), 10);
     }
 }
Esempio n. 10
0
 /**
  * Create and return a 403 view model
  *
  * @param  MvcEvent $event
  * @return void
  */
 public function prepareForbiddenViewModel(MvcEvent $event)
 {
     if ($event->getRequest() instanceof \Zend\Console\Request) {
         // CLI mode
         return;
     }
     $vars = $event->getResult();
     if ($vars instanceof Response) {
         // Already have a response as the result
         return;
     }
     $response = $event->getResponse();
     if ($response->getStatusCode() != 403) {
         // Only handle 403 responses
         return;
     }
     if (!$vars instanceof ViewModel) {
         $model = new ViewModel();
         if (is_string($vars)) {
             $model->setVariable('message', $vars);
         } else {
             $model->setVariable('message', 'Page is forbidden.');
         }
     } else {
         $model = $vars;
         if ($model->getVariable('message') === null) {
             $model->setVariable('message', 'Page is forbidden.');
         }
     }
     $model->setTemplate($this->getForbiddenTemplate());
     $event->setResult($model);
 }
Esempio n. 11
0
 /**
  * Inject a template into the view model, if none present
  *
  * Template is derived from the controller found in the route match, and,
  * optionally, the action, if present.
  *
  * @param  MvcEvent $e
  * @return void
  */
 public function injectTemplate(MvcEvent $e)
 {
     $model = $e->getResult();
     if (!$model instanceof ViewModel) {
         return;
     }
     $template = $model->getTemplate();
     if (!empty($template)) {
         return;
     }
     $routeMatch = $e->getRouteMatch();
     $controller = $e->getTarget();
     if (is_object($controller)) {
         $controller = get_class($controller);
     }
     if (!$controller) {
         $controller = $routeMatch->getParam('controller', '');
     }
     $module = $this->deriveModuleNamespace($controller);
     $controller = $this->deriveControllerClass($controller);
     $template = $this->inflectName($module);
     if (!empty($template)) {
         $template .= '/';
     }
     $template .= $this->inflectName($controller);
     $action = $routeMatch->getParam('action');
     if (null !== $action) {
         $template .= '/' . $this->inflectName($action);
     }
     $model->setTemplate($template);
 }
Esempio n. 12
0
 /**
  * @private
  * @param  MvcEvent $event
  * @return void
  */
 public function onError(MvcEvent $event)
 {
     // Do nothing if no error or if response is not HTTP response
     if (!$event->getParam('exception') instanceof UnauthorizedExceptionInterface || $event->getResult() instanceof HttpResponse || !$event->getResponse() instanceof HttpResponse) {
         return;
     }
     $router = $event->getRouter();
     if ($this->authenticationService->hasIdentity()) {
         if (!$this->options->getRedirectWhenConnected()) {
             return;
         }
         $redirectRoute = $this->options->getRedirectToRouteConnected();
     } else {
         $redirectRoute = $this->options->getRedirectToRouteDisconnected();
     }
     $uri = $router->assemble([], ['name' => $redirectRoute]);
     if ($this->options->getAppendPreviousUri()) {
         $redirectKey = $this->options->getPreviousUriQueryKey();
         $previousUri = $event->getRequest()->getUriString();
         $uri = $router->assemble([], ['name' => $redirectRoute, 'query' => [$redirectKey => $previousUri]]);
     }
     $response = $event->getResponse() ?: new HttpResponse();
     $response->getHeaders()->addHeaderLine('Location', $uri);
     $response->setStatusCode(302);
     $event->setResponse($response);
     $event->setResult($response);
 }
Esempio n. 13
0
 /**
  * Get the exception and optionally set status code, reason message and additional errors
  *
  * @internal
  * @param  MvcEvent $event
  * @return void
  */
 public function onDispatchError(MvcEvent $event)
 {
     $exception = $event->getParam('exception');
     if (isset($this->exceptionMap[get_class($exception)])) {
         $exception = $this->createHttpException($exception);
     }
     // We just deal with our Http error codes here !
     if (!$exception instanceof HttpExceptionInterface || $event->getResult() instanceof HttpResponse) {
         return;
     }
     // We clear the response for security purpose
     $response = new HttpResponse();
     $response->getHeaders()->addHeaderLine('Content-Type', 'application/json');
     $exception->prepareResponse($response);
     // NOTE: I'd like to return a JsonModel instead, and let ZF handle the request, but I couldn't make
     // it work because for unknown reasons, the Response get replaced "somewhere" in the MVC workflow,
     // so the simplest is simply to do that
     $content = ['status_code' => $response->getStatusCode(), 'message' => $response->getReasonPhrase()];
     if ($errors = $exception->getErrors()) {
         $content['errors'] = $errors;
     }
     $response->setContent(json_encode($content));
     $event->setResponse($response);
     $event->setResult($response);
     $event->stopPropagation(true);
 }
Esempio n. 14
0
 public function onBootstrap(MvcEvent $e)
 {
     $sm = $e->getApplication()->getServiceManager();
     $app_config = $sm->get('config');
     $app_options = $app_config['app_options'];
     if (array_key_exists('recover_from_fatal', $app_options) && $app_options['recover_from_fatal']) {
         $redirect_url = $app_options['redirect_url'];
         $callback = null;
         if (array_key_exists('fatal_errors_callback', $app_options) && $app_options['fatal_errors_callback']) {
             $callback = $app_options['fatal_errors_callback'];
         }
         register_shutdown_function(array('Application\\Module', 'handleFatalPHPErrors'), $redirect_url, $callback);
     }
     set_error_handler(array('Application\\Module', 'handlePHPErrors'));
     foreach ($app_options['php_settings'] as $key => $value) {
         ini_set($key, $value);
     }
     $eventManager = $e->getApplication()->getEventManager();
     $moduleRouteListener = new ModuleRouteListener();
     $moduleRouteListener->attach($eventManager);
     $logger = $sm->get('Logger');
     $eventManager->attach(MvcEvent::EVENT_RENDER_ERROR, function (MvcEvent $e) use($logger) {
         $logger->info('An Exception has occurred. ' . $e->getResult()->exception->getMessage());
     }, -200);
 }
Esempio n. 15
0
 public function setTemplate(MvcEvent $e)
 {
     $result = $e->getResult();
     $router = $e->getRouteMatch();
     $params = $router->getParams();
     if (isset($params['__NAMESPACE__']) && isset($params['__CONTROLLER__']) && isset($params['action'])) {
         $controllerClass = $params['__NAMESPACE__'];
         $moduleNamespace = substr($controllerClass, strpos($controllerClass, '\\'));
         $moduleNamespace = substr($moduleNamespace, 1);
         $moduleNamespace = substr($moduleNamespace, 0, strpos($moduleNamespace, '\\Controller'));
         $templatePath = __DIR__;
         $config = $e->getApplication()->getServiceManager()->get('config');
         if (isset($config['view_manager']['template_map'])) {
             $moduleNamespace = strtolower($moduleNamespace . '/' . $params['__CONTROLLER__']);
             $templatePath = $templatePath . '/view/' . $moduleNamespace . '/' . $params['action'] . '.phtml';
             $moduleNamespace = str_replace('\\', '/', $moduleNamespace);
             $template = $moduleNamespace . '/' . $params['action'];
             $config['view_manager']['template_map'][$template] = $templatePath;
             $result->setTemplate($template);
         }
         //set Title;
         if (isset($config['view_manager']['siteName'])) {
             $siteName = $config['view_manager']['siteName'];
         } else {
             $siteName = $moduleNamespace;
         }
         $viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
         $headTitle = $viewHelperManager->get('headTitle');
         $headTitle->setSeparator(' - ');
         $headTitle->append($params['action']);
         $headTitle->append($siteName);
     }
 }
 /**
  * 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;
 }
Esempio n. 17
0
 /**
  * @param MvcEvent $e
  * @return void
  */
 public function onError(MvcEvent $e)
 {
     if (!$e->getParam('exception') instanceof UnauthorizedException || $e->getResult() instanceof HttpResponse || !$e->getResponse() instanceof HttpResponse) {
         return;
     }
     $this->handleError($e);
 }
Esempio n. 18
0
 public function prepareNotFoundViewModel(MvcEvent $e)
 {
     $vars = $e->getResult();
     if ($vars instanceof Response) {
         // Already have a response as the result
         return;
     }
     $response = $e->getResponse();
     if ($response->getStatusCode() != 404) {
         // Only handle 404 responses
         return;
     }
     if (!$vars instanceof ViewModel) {
         $model = new ViewModel();
         if (is_string($vars)) {
             $model->setVariable('message', $vars);
         } else {
             $model->setVariable('message', 'Page not found.');
         }
     } else {
         $model = $vars;
         if ($model->getVariable('message') === null) {
             $model->setVariable('message', 'Page not found.');
         }
     }
     // If displaying reasons, inject the reason
     $this->injectNotFoundReason($model, $e);
     // If displaying exceptions, inject
     $this->injectException($model, $e);
     // Inject controller if we're displaying either the reason or the exception
     $this->injectController($model, $e);
     ob_clean();
     throw new \Exception($model->getVariable('message') . ' ' . $model->getVariable('reason'));
 }
Esempio n. 19
0
 public function saveActionCache(MvcEvent $event)
 {
     $match = $event->getRouteMatch();
     if (!$match) {
         return;
     }
     if ($match->getParam('actioncache')) {
         $viewManager = $event->getApplication()->getServiceManager()->get('viewmanager');
         $result = $event->getResult();
         if ($result instanceof ViewModel) {
             $cache = $event->getApplication()->getServiceManager()->get('text-cache');
             // Warning: the line below needs improvement.
             // It will work for all PHP templates, but would have
             // to be made more flexible if you had planned to use
             // other template systems.
             $renderer = $viewManager->getRenderer();
             $content = $renderer->render($result);
             $cacheKey = $this->actionCacheKey($match);
             $cache->setItem($cacheKey, $content);
             $tags = $match->getParam('tags');
             if ($tags) {
                 $cache->setTags($cacheKey, $tags);
             }
         }
     }
 }
 public function __invoke(MvcEvent $event)
 {
     $model = $event->getResult();
     if (!$model instanceof ViewModel) {
         return;
     }
     if (strpos($model->getTemplate(), 'error') === false) {
         return;
     }
     $result = $event->getResult();
     $error = $event->getError();
     $layout = new ViewModel();
     $layout->setTemplate('layout/layout');
     $content = new ViewModel();
     if ($error == 'error-exception') {
         $content->setVariable('reason', 'The site seems to be experiencing problems, please try again later');
         $content->setTemplate('error/knc-exception');
     } else {
         $content->setVariable('reason', 'The site cannot find the url in the address bar');
         $content->setTemplate('error/knc-error');
     }
     $layout->addChild($content);
     $layout->setTerminal(true);
     $event->setViewModel($layout);
     $event->setResult($layout);
     return false;
 }
Esempio n. 21
-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);
 }
 public function prepareExceptionViewModel(MvcEvent $event)
 {
     // Do nothing if no error in the event
     $error = $event->getError();
     if (empty($error)) {
         return;
     }
     // Do nothing if the result is a response object
     $result = $event->getResult();
     if ($result instanceof Response) {
         return;
     }
     switch ($error) {
         case Application::ERROR_CONTROLLER_NOT_FOUND:
         case Application::ERROR_CONTROLLER_INVALID:
         case Application::ERROR_ROUTER_NO_MATCH:
             // Specifically not handling these
             return;
         case Application::ERROR_EXCEPTION:
         default:
             $exception = $event->getParam('exception');
             if ($exception) {
                 $response = $event->getResponse();
                 if (!$response || $response->getStatusCode() === 200) {
                     header('HTTP/1.0 500 Internal Server Error', true, 500);
                 }
                 ob_clean();
                 $this->run->handleException($event->getParam('exception'));
             }
             break;
     }
 }
 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);
 }
Esempio n. 24
-1
 /**
  * Whoops handle exceptions
  * @param MvcEvent $e
  */
 public function prepareException(MvcEvent $e)
 {
     $error = $e->getError();
     if (!empty($error) && !$e->getResult() instanceof Response) {
         switch ($error) {
             case Application::ERROR_CONTROLLER_NOT_FOUND:
             case Application::ERROR_CONTROLLER_INVALID:
             case Application::ERROR_ROUTER_NO_MATCH:
                 // Specifically not handling these
                 return;
             case Application::ERROR_EXCEPTION:
             default:
                 if (in_array(get_class($e->getParam('exception')), $this->noCatchExceptions)) {
                     // No catch this exception
                     return;
                 }
                 $response = $e->getResponse();
                 if (!$response || $response->getStatusCode() === 200) {
                     header('HTTP/1.0 500 Internal Server Error', true, 500);
                 }
                 ob_clean();
                 $this->run->handleException($e->getParam('exception'));
                 break;
         }
     }
 }
 /**
  * @see \Zend\Mvc\View\Http\ExceptionStrategy::prepareExceptionViewModel()
  */
 public function prepareExceptionViewModel(MvcEvent $event)
 {
     // do nothing if no error in the event
     $error = $event->getError();
     if (empty($error)) {
         return;
     }
     // do nothing if the result is a response object
     $result = $event->getResult();
     if ($result instanceof Response) {
         return;
     }
     // do nothing if there is no exception or the exception is not an UserDeactivatedException
     $exception = $event->getParam('exception');
     if (!$exception instanceof UserDeactivatedException) {
         return;
     }
     $auth = $event->getApplication()->getServiceManager()->get('AuthenticationService');
     // do nothing if no user is logged in or is active one
     if (!$auth->hasIdentity() || $auth->getUser()->isActive()) {
         return;
     }
     $response = $event->getResponse();
     if (!$response) {
         $response = new Response();
         $event->setResponse($response);
     }
     $response->setStatusCode(Response::STATUS_CODE_403);
     $model = new ViewModel(['message' => 'This user account has been disabled. Please contact the system adminstrator.', 'exception' => $exception, 'display_exceptions' => $this->displayExceptions()]);
     $model->setTemplate($this->getExceptionTemplate());
     $event->setResult($model);
 }
Esempio n. 26
-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);
 }
 /**
  * Callback used when a dispatch error occurs. Modifies the
  * response object with an according error if the application
  * event contains an exception related with authorization.
  *
  * @param MvcEvent $event
  *
  * @return void
  */
 public function onDispatchError(MvcEvent $event)
 {
     // Do nothing if the result is a response object
     $result = $event->getResult();
     $response = $event->getResponse();
     if ($result instanceof Response || $response && !$response instanceof HttpResponse) {
         return;
     }
     // Common view variables
     $viewVariables = array('error' => $event->getParam('error'), 'identity' => $event->getParam('identity'));
     switch ($event->getError()) {
         case Application::ERROR_EXCEPTION:
             if (!$event->getParam('exception') instanceof UnAuthorizedException) {
                 return;
             }
             $viewVariables['reason'] = $event->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());
     $event->getViewModel()->addChild($model);
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
 public function onDispatchError(MvcEvent $e)
 {
     // Do nothing if the result is a response object
     $result = $e->getResult();
     $type = $e->getError();
     if ($result instanceof Response || strpos($type, 'unauthorized') === false) {
         return;
     }
     $router = $e->getRouter();
     $match = $e->getRouteMatch();
     // get url to the zfcuser/login route
     $options['name'] = 'zfcuser/login';
     $url = $router->assemble(array(), $options);
     // Work out where were we trying to get to
     $options['name'] = $match->getMatchedRouteName();
     $redirect = $router->assemble($match->getParams(), $options);
     // set up response to redirect to login page
     $response = $e->getResponse();
     if (!$response) {
         $response = new HttpResponse();
         $e->setResponse($response);
     }
     $response->getHeaders()->addHeaderLine('Location', $url . '?redirect=' . $redirect);
     $response->setStatusCode(302);
 }
 /**
  * Create an unauthorized view model, and set the HTTP status code
  *
  * @param  MvcEvent $e
  * @return void
  */
 public function prepareUnauthorizedViewModel(MvcEvent $e)
 {
     // Do nothing if no error in the event
     $error = $e->getError();
     if (empty($error)) {
         return;
     }
     // Do nothing if the result is a response object
     $result = $e->getResult();
     if ($result instanceof Response) {
         return;
     }
     switch ($error) {
         case Security::ERROR_CONTROLLER_UNAUTHORIZED:
             $model = new ViewModel(array('error' => $e->getParam('error'), 'controller' => $e->getParam('controller'), 'action' => $e->getParam('action'), 'identity' => $e->getParam('identity')));
             break;
         case Security::ERROR_ROUTE_UNAUTHORIZED:
             $model = new ViewModel(array('error' => $e->getParam('error'), 'route' => $e->getParam('route'), 'identity' => $e->getParam('identity')));
             break;
         default:
             return;
             break;
     }
     $model->setTemplate($this->getUnauthorizedTemplate());
     $e->setResult($model);
     $response = $e->getResponse();
     if (!$response) {
         $response = new HttpResponse();
         $e->setResponse($response);
     }
     $response->setStatusCode(403);
 }
Esempio n. 30
-1
 /**
  * Handles redirects in case of dispatch errors caused by unauthorized access
  *
  * @param \Zend\Mvc\MvcEvent $event
  */
 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 application needs install
     if (AppGuard::ERROR === $error && $event->getParam('exception') instanceof NeedsInstallException) {
         die('died here');
         $this->redirectRoute = 'zfmuscle/install';
     }
     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);
 }