setViewModel() публичный Метод

Set the view model
public setViewModel ( Zend\View\Model\ModelInterface $viewModel ) : MvcEvent
$viewModel Zend\View\Model\ModelInterface
Результат MvcEvent
 /**
  * @param $controllerName
  * @param $action
  * @param array $params
  * @return string|\Zend\Stdlib\ResponseInterface
  * @throws \Exception
  */
 public function runControllerAction($controllerName, $action, $params = array())
 {
     $this->event->getRouteMatch()->setParam('controller', $controllerName)->setParam('action', $action);
     foreach ($params as $key => $value) {
         $this->event->getRouteMatch()->setParam($key, $value);
     }
     $serviceManager = $this->event->getApplication()->getServiceManager();
     $controllerManager = $serviceManager->get('ControllerLoader');
     /** @var AbstractActionController $controller */
     $controller = $controllerManager->get($controllerName);
     $controller->setEvent($this->event);
     $result = $controller->dispatch($this->event->getRequest());
     if ($result instanceof Response) {
         return $result;
     }
     /** @var ViewManager $viewManager */
     $viewManager = $serviceManager->get('ViewManager');
     $renderingStrategy = $viewManager->getMvcRenderingStrategy();
     $this->event->setViewModel($result);
     /** @var ViewModel $result */
     if (!$result->terminate()) {
         $layout = new ViewModel();
         $layoutTemplate = $renderingStrategy->getLayoutTemplate();
         $layout->setTemplate($layoutTemplate);
         $layout->addChild($result);
         $this->event->setViewModel($layout);
     }
     $response = $renderingStrategy->render($this->event);
     return $response;
 }
 /**
  * Set up
  */
 public function setUp()
 {
     parent::setUp();
     $this->resourceResponseListener = new ResourceResponseListener();
     // Init the MvcEvent object
     $this->response = new HttpResponse();
     $this->event = new MvcEvent();
     $this->event->setResponse($this->response);
     $this->event->setViewModel(new ResourceViewModel());
 }
Пример #3
0
 public function testCollect()
 {
     $event = new MvcEvent();
     $layoutModel = new ViewModel();
     $layoutModel->setTemplate('layout/2cols-left');
     $event->setViewModel($layoutModel);
     $testBlock = new ViewModel();
     $testBlock->setTemplate('widget1');
     $testBlock->setCaptureTo('sidebarLeft');
     $testBlock2 = new ViewModel();
     $testBlock2->setOption('parent', 'test.block');
     $testBlock2->setTemplate('widget1');
     $this->blockPool->add('test.block', $testBlock);
     $this->blockPool->add('test.block2', $testBlock2);
     $this->collector->collect($event);
     $this->assertEquals('layout/2cols-left', $this->collector->getLayoutTemplate());
     $this->assertInternalType('array', $this->collector->getHandles());
     $this->assertContainsOnlyInstancesOf(HandleInterface::class, $this->collector->getHandles());
     $this->assertInternalType('array', $this->collector->getBlocks());
     $blocks = $this->collector->getBlocks();
     $testBlockArray = current($blocks);
     $testBlock2Array = array_pop($blocks);
     $this->assertEquals('test.block::content', $testBlock2Array['capture_to']);
     $this->assertContains('_files/view/widget1.phtml', $testBlockArray['template']);
     $this->assertEquals('sidebarLeft', $testBlockArray['capture_to']);
     $this->assertEquals(ViewModel::class, $testBlockArray['class']);
     $this->assertEquals(LayoutUpdaterInterface::AREA_DEFAULT, $this->collector->getCurrentArea());
     $this->assertInternalType('array', $this->collector->getLayoutStructure());
 }
Пример #4
0
 /**
  * @param MvcEvent $event
  *
  * @return parent::onDispatch
  */
 public function onDispatch(MvcEvent $event)
 {
     $request = $event->getRequest();
     $remoteAddr = $request->getServer('REMOTE_ADDR');
     // check IP address is allowed
     $application = $event->getApplication();
     $config = $application->getConfig();
     $autoDeployConfig = $config['auto_deploy'];
     $allowedIpAddresses = $autoDeployConfig['ipAddresses'];
     // error if ip is not allowed
     if (!in_array($remoteAddr, $allowedIpAddresses, true)) {
         $baseModel = new \Zend\View\Model\ViewModel();
         $baseModel->setTemplate('layout/output');
         $model = new \Zend\View\Model\ViewModel();
         $model->setTemplate('error/403');
         $baseModel->addChild($model);
         $baseModel->setTerminal(true);
         $event->setViewModel($baseModel);
         $response = $event->getResponse();
         $response->setStatusCode(403);
         $response->sendHeaders();
         $event->setResponse($response);
         exit;
     }
     return parent::onDispatch($event);
 }
Пример #5
0
 public function testOnDispatch()
 {
     // Create MvcEvent
     $e = new MvcEvent();
     $e->setViewModel(new ViewModel());
     $rm = new RouteMatch([]);
     $rm->setParam('controller', 'Application\\Controller\\Download');
     $e->setRouteMatch($rm);
     $e->setTarget(new DownloadController([]));
     // Create EntityManager and EntityRepository
     $moduleDetail = new ModuleList();
     $moduleDetail->setModuleDesc('Pretty description');
     $repo = $this->prophesize('Doctrine\\ORM\\EntityRepository');
     $repo->findOneBy(['moduleName' => 'Application'])->willReturn($moduleDetail);
     $em = $this->prophesize('Doctrine\\ORM\\EntityManager');
     $em->getRepository('Application\\Entity\\ModuleList')->willReturn($repo);
     $this->sm->setService('Doctrine\\ORM\\EntityManager', $em->reveal());
     // Create ViewHelperManager
     $headTitle = new HeadTitle();
     $vhm = new HelperPluginManager();
     $vhm->setService('headTitle', $headTitle);
     $this->sm->setService('ViewHelperManager', $vhm);
     $this->module->onDispatch($e);
     $fbMeta = $e->getViewModel()->getVariable('fbMeta');
     $this->assertEquals(sprintf('%s-Real Live Learn ZF2', $moduleDetail->getModuleDesc()), $fbMeta['title']);
     $this->assertEquals(sprintf('%s-', $moduleDetail->getModuleDesc()), $fbMeta['description']);
 }
 public function testInjectTagsHeader()
 {
     $tag = InjectTagsHeaderListener::OPTION_CACHE_TAGS;
     $event = new MvcEvent();
     $response = new Response();
     $event->setResponse($response);
     $layout = new ViewModel();
     $child1 = new ViewModel();
     $child1->setOption($tag, ['tag1', 'tag2']);
     $layout->addChild($child1);
     $child2 = new ViewModel();
     $child21 = new ViewModel();
     $child21->setOption($tag, ['tag3', null]);
     $child2->addChild($child21);
     $layout->addChild($child2);
     $child3 = new ViewModel();
     $child3->setOption('esi', ['ttl' => 120]);
     $child3->setOption($tag, 'tag4');
     $layout->addChild($child3);
     $event->setViewModel($layout);
     $this->listener->injectTagsHeader($event);
     $this->assertSame(['tag1', 'tag2', 'tag3'], $this->listener->getCacheTags());
     $headers = $response->getHeaders();
     $this->assertEquals('tag1,tag2,tag3', $headers->get(VarnishService::VARNISH_HEADER_TAGS)->getFieldValue());
 }
 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);
     }
 }
Пример #8
0
 /**
  * Insert the view model into the event
  *
  * Inspects the MVC result; if it's a view model, it then either (a) adds
  * it as a child to the default, composed view model, or (b) replaces it
  * if the result is marked as terminable.
  *
  * @param  MvcEvent $e
  * @return void
  */
 public function injectViewModel(MvcEvent $e)
 {
     $result = $e->getResult();
     if (!$result instanceof ViewModel) {
         return;
     }
     $model = $e->getViewModel();
     if ($result->terminate()) {
         $e->setViewModel($result);
         return;
     }
     $model->addChild($result);
 }
Пример #9
0
 private function controlarAcces(MvcEvent $e)
 {
     if (get_class($e->getTarget()) != 'LlistaCompra\\Controller\\SeguretatController') {
         if (!UsuariConnectat::estaConnectat()) {
             $res = [];
             $res[0] = new RespostaTO();
             $res[0]->resultat = "NC";
             $model = new JsonModel($res);
             $e->setViewModel($model);
             $e->stopPropagation();
             return $model;
         }
     }
 }
 /**
  * Method executed when the render event is triggered
  *
  * @param MvcEvent $e 
  * @return void
  */
 public static function onRender(MvcEvent $e)
 {
     if ($e->getRequest() instanceof \Zend\Console\Request || $e->getResponse()->isOk() || $e->getResponse()->getStatusCode() == Response::STATUS_CODE_401) {
         return;
     }
     $httpCode = $e->getResponse()->getStatusCode();
     $sm = $e->getApplication()->getServiceManager();
     $viewModel = $e->getResult();
     $exception = $viewModel->getVariable('exception');
     $model = new JsonModel(array('errorCode' => !empty($exception) ? $exception->getCode() : $httpCode, 'errorMsg' => !empty($exception) ? $exception->getMessage() : NULL));
     $model->setTerminal(true);
     $e->setResult($model);
     $e->setViewModel($model);
     $e->getResponse()->setStatusCode($httpCode);
 }
Пример #11
0
 /**
  * 
  * @param MvcEvent $event
  */
 protected function triggerForbiddenEvent(MvcEvent $event)
 {
     $event->setError('route-forbidden');
     $event->setParam('exception', new UnauthorizedException('You are forbidden!', 403));
     $event->stopPropagation(true);
     if ($this->hasErrorViewModel()) {
         $event->setViewModel($this->errorView);
     }
     $response = $event->getResponse();
     $response->setStatusCode(403);
     $event->setResponse($response);
     $application = $event->getApplication();
     $eventManager = $application->getEventManager();
     $eventManager->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
 }
Пример #12
0
 /**
  * Insert the view model into the event
  *
  * Inspects the MVC result; if it's a view model, it then either (a) adds
  * it as a child to the default, composed view model, or (b) replaces it
  * if the result is marked as terminable.
  *
  * @param  MvcEvent $e
  * @return void
  */
 public function injectViewModel(MvcEvent $e)
 {
     $result = $e->getResult();
     if (!$result instanceof ViewModel) {
         return;
     }
     $model = $e->getViewModel();
     if ($result->terminate()) {
         $e->setViewModel($result);
         return;
     }
     if ($e->getError() && $model instanceof ClearableModelInterface) {
         $model->clearChildren();
     }
     $model->addChild($result);
 }
Пример #13
0
 public function injectLayout(MvcEvent $e)
 {
     $request = $e->getRequest();
     if (!$request instanceof HttpRequest) {
         return;
     }
     $result = $e->getResult();
     if (!$result instanceof ZendViewModel) {
         return;
     }
     $response = $e->getResponse();
     if ($response->getStatusCode() != 200) {
         return;
     }
     $matchedRoute = $e->getRouteMatch();
     if (!$matchedRoute) {
         return;
     }
     $matchedRouteName = $matchedRoute->getMatchedRouteName();
     $serviceLocator = $e->getApplication()->getServiceManager();
     $config = $serviceLocator->get('config');
     $options = $config['sebaks-view'];
     if (!isset($options['contents'][$matchedRouteName])) {
         return;
     }
     $viewConfig = $options['contents'][$matchedRouteName];
     $config = new Config(array_merge($options['layouts'], $options['contents'], $options['blocks']));
     $viewConfig = $config->applyInheritance($viewConfig);
     $viewBuilder = new ViewBuilder($config, $serviceLocator);
     $data = $result->getVariables()->getArrayCopy();
     if (isset($viewConfig['layout'])) {
         $viewComponentLayout = $viewConfig['layout'];
         if (!isset($options['layouts'][$viewComponentLayout])) {
             throw new \Exception("Layout '{$viewComponentLayout}' not found for view component '{$matchedRouteName}'");
         }
         $options['layouts'][$viewComponentLayout]['children']['content'] = $viewConfig;
         $viewComponent = $viewBuilder->build($options['layouts'][$viewComponentLayout], $data);
     } else {
         $viewComponent = $viewBuilder->build($viewConfig, $data);
     }
     $viewComponent->setTerminal(true);
     $e->setViewModel($viewComponent);
     $e->setResult($viewComponent);
 }
Пример #14
0
 public function onRender(MvcEvent $e)
 {
     if ($e->getResponse()->isOk()) {
         return;
     }
     $httpCode = $e->getResponse()->getStatusCode();
     $sm = $e->getApplication()->getServiceManager();
     $viewModel = $e->getViewModel();
     $exception = $viewModel->getVariable('exception');
     $model = new JsonModel();
     if ($exception) {
         $model->setVariables(['errorCode' => $exception->getCode, 'errorMessage' => $exception->getMessage()]);
     } else {
         $model->setVariables(['errorCode' => $httpCode, 'errorMessage' => 'error has been trigger']);
     }
     $e->setResult($model);
     $e->setViewModel($model);
     $e->getResponse()->setStatusCode($httpCode);
 }
Пример #15
0
 public function testCollect()
 {
     $event = new MvcEvent();
     $layoutModel = new ViewModel();
     $layoutModel->setTemplate('layout/2cols-left');
     $event->setViewModel($layoutModel);
     $testBlock = new ViewModel();
     $testBlock->setTemplate('test/block');
     $testBlock->setCaptureTo('sidebarLeft');
     $this->layout->addBlock('test.block', $testBlock);
     $this->collector->collect($event);
     $this->assertEquals('layout/2cols-left', $this->collector->getLayoutTemplate());
     $this->assertInternalType('array', $this->collector->getHandles());
     $this->assertContainsOnlyInstancesOf('ConLayout\\Handle\\HandleInterface', $this->collector->getHandles());
     $this->assertInternalType('array', $this->collector->getBlocks());
     $testBlockArray = current($this->collector->getBlocks());
     $this->assertEquals('test/block', $testBlockArray['template']);
     $this->assertEquals('sidebarLeft', $testBlockArray['capture_to']);
     $this->assertEquals('Zend\\View\\Model\\ViewModel', $testBlockArray['class']);
     $this->assertInternalType('array', $this->collector->getLayoutStructure());
 }
Пример #16
0
 public function forbidden(MvcEvent $e)
 {
     $error = $e->getError();
     if (empty($error) || $error != "ACL_ACCESS_DENIED") {
         return;
     }
     $result = $e->getResult();
     if ($result instanceof StdResponse) {
         return;
     }
     $baseModel = new ViewModel();
     $baseModel->setTemplate('layout/layout');
     $model = new ViewModel();
     $model->setTemplate('error/403');
     $baseModel->addChild($model);
     $baseModel->setTerminal(true);
     $e->setViewModel($baseModel);
     $response = $e->getResponse();
     $response->setStatusCode(403);
     $e->setResponse($response);
     $e->setResult($baseModel);
     return false;
 }
Пример #17
0
 public function handleError(MvcEvent $e)
 {
     if ($e->getError() == Application::ERROR_ROUTER_NO_MATCH) {
         return;
     }
     if ($e->getError() == Application::ERROR_EXCEPTION) {
         $translator = $e->getApplication()->getServiceManager()->get('translator');
         $exception = $e->getParam('exception');
         if ($exception instanceof BusinessException) {
             // translate
             $status = intval($exception->getCode());
             $messsage = $translator->translate($exception->getMessage());
         } else {
             $status = 999;
             if (isset($_SERVER['APPLICATION_ENV']) && $_SERVER['APPLICATION_ENV'] == 'development') {
                 $messsage = $exception->getMessage();
             } else {
                 $messsage = '对不起, 系统出错了...';
             }
         }
         /* @var $request \Zend\Http\Request */
         $request = $e->getRequest();
         $response = $e->getResponse();
         if ($request->isXmlHttpRequest()) {
             // change status code from 500 to 200
             $response->setStatusCode(200);
             $response->getHeaders()->addHeaders(array('Content-type' => 'application/json; charset=utf8'));
             $json = new JsonModel();
             $json->setVariables(array('status' => $status, 'message' => $messsage, 'content' => array()));
             $json->setTerminal(false);
             $e->setViewModel($json);
             // mute other default exception handler
             $e->setError(false);
         }
     }
 }
Пример #18
0
 /**
  * @codeCoverageIgnore
  * display
  *
  * @param string             $content
  * @param \Zend\Mvc\MvcEvent $event
  *
  * @return void
  */
 public function display($content, \Zend\Mvc\MvcEvent $event)
 {
     $view = new JsonModel();
     $view->setTerminal(true);
     $event->setViewModel($view);
     /** @var Response $response */
     $response = $event->getResponse();
     $response->getHeaders()->clearHeaders();
     $this->setResponseHeaders();
     $response->setStatusCode(Response::STATUS_CODE_500);
     $response->getHeaders()->addHeaders(['Content-Type' => 'application/json']);
     $response->setContent('');
     $response->getContent();
     $this->setResponseHeaders();
     echo $content;
     exit(0);
 }
Пример #19
0
 /**
  * Test Get Admin Panel No Panel Returned
  *
  * @return void
  *
  * @covers \RcmAdmin\EventListener\DispatchListener::getAdminPanel
  */
 public function testGetAdminPanelReturnsNoView()
 {
     $layoutViewMock = new ViewModel();
     $event = new MvcEvent();
     $routeMatch = new RouteMatch([]);
     $event->setRouteMatch($routeMatch);
     $event->setViewModel($layoutViewMock);
     $this->mockController->expects($this->once())->method('getAdminWrapperAction')->will($this->returnValue(null));
     $this->listener->getAdminPanel($event);
     /** @var \Zend\View\Model\ViewModel $panelView */
     $children = $layoutViewMock->getChildrenByCaptureTo('rcmAdminPanel');
     $this->assertEmpty($children);
 }
 public function it_dispatches_ajax_errors_properly(MvcEvent $event)
 {
     $_SERVER['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest';
     $event->getParams()->willReturn(['a' => 1]);
     $event->getResponse()->willReturn(null);
     $event->getError()->willReturn(AccessService::ACCESS_DENIED);
     $event->setResponse(Argument::type(Response::class))->shouldBeCalled();
     $event->setViewModel(Argument::type(JsonModel::class))->shouldBeCalled();
     $this->onDispatchError($event);
 }
Пример #21
0
 public function testInjectLayoutNegative()
 {
     $listener = new AccessListener();
     $viewModel = new ViewModel();
     $viewModel->setTemplate('layout/layout');
     $access = new DenyAccess();
     $event = new MvcEvent();
     $event->setApplication($this->getMockApplication(true, $access));
     $event->setViewModel($viewModel);
     $listener->injectLayoutMenu($event);
     $this->assertCount(0, $viewModel->getChildrenByCaptureTo('sporkToolsMenu'));
 }
 /**
  * Listen to the render event
  *
  * @param MvcEvent $e
  */
 public static function onRender(MvcEvent $e)
 {
     // only worried about error pages
     if (!$e->isError()) {
         return;
     }
     // and then, only if we have an Accept header...
     $request = $e->getRequest();
     if (!$request instanceof HttpRequest) {
         return;
     }
     $headers = $request->getHeaders();
     if (!$headers->has('Accept')) {
         return;
     }
     // ... that matches certain criteria
     $accept = $headers->get('Accept');
     $match = $accept->match(self::$acceptFilter);
     if (!$match || $match->getTypeString() == '*/*') {
         return;
     }
     // Next, do we have a view model in the result?
     // If not, nothing more to do.
     $model = $e->getResult();
     if (!$model instanceof ModelInterface) {
         return;
     }
     // Marshall the information we need for the API-Problem response
     $httpStatus = $e->getResponse()->getStatusCode();
     $exception = $model->getVariable('exception');
     if ($exception instanceof \Exception) {
         $apiProblem = new ApiProblem($httpStatus, $exception);
     } else {
         $apiProblem = new ApiProblem($httpStatus, $model->getVariable('message'));
     }
     // Create a new model with the API-Problem payload, and reset
     // the result and view model in the event using it.
     $model = new RestfulJsonModel(array('payload' => $apiProblem));
     $model->setTerminal(true);
     $e->setResult($model);
     $e->setViewModel($model);
 }
Пример #23
0
 /**
  * Render JSON response on Error
  *
  * @param MvcEvent $e
  */
 public function onRenderError(MvcEvent $e)
 {
     // must be an error
     if (!$e->isError()) {
         return;
     }
     // if we have a JsonModel in the result, then do nothing
     $currentModel = $e->getResult();
     if ($currentModel instanceof JsonModel) {
         return;
     }
     // create a new JsonModel - use application/api-problem+json fields.
     /**
      *
      * @var Response $response
      */
     $response = $e->getResponse();
     /** @var \Exception $exception */
     $exception = $e->getParam('exception');
     // Create a new ViewModel
     $model = new JsonModel(array("httpStatus" => $exception ? $exception->getCode() : ($response instanceof Response ? $response->getStatusCode() : 500), "title" => $e->getError()));
     if ($exception && $exception instanceof ValidationException) {
         $model->httpStatus = $exception->getCode();
         if ($response instanceof Response) {
             $response->setStatusCode($model->httpStatus);
         }
         $model->title = 'validation-exception';
         //We can have many validation errors
         $model->validationMessages = $exception instanceof ValidationException ? $exception->getMessages() : $exception->getMessage();
     }
     // Add a detailed info about the error, if it exists
     if (isset($_SERVER['APPLICATION_ENV']) && $_SERVER['APPLICATION_ENV'] === 'development' && $e->getError()) {
         switch ($e->getError()) {
             case 'error-controller-cannot-dispatch':
                 $model->detail = 'The requested controller was unable to dispatch the request.';
                 break;
             case 'error-controller-not-found':
                 $model->detail = 'The requested controller could not be mapped to an existing controller class.';
                 break;
             case 'error-controller-invalid':
                 $model->detail = 'The requested controller was not dispatchable.';
                 break;
             case 'error-router-no-match':
                 $model->detail = 'The requested URL could not be matched by routing.';
                 break;
             default:
                 $model->title = get_class($exception);
                 $model->detail = ['message' => $exception instanceof ValidationException ? $exception->getMessages() : $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()];
                 break;
         }
     }
     // set our new view model
     $model->setTerminal(true);
     $e->setResult($model);
     $e->setViewModel($model);
 }
Пример #24
0
 public function renderError(MvcEvent $e)
 {
     // must be an error
     if (!$e->isError()) {
         return;
     }
     $request = $e->getRequest();
     if (!$request instanceof HttpRequest) {
         return;
     }
     // We ought to check for a JSON accept header here, except that we
     // don't need to as we only ever send back JSON.
     // If we have a JsonModel in the result, then do nothing
     $currentModel = $e->getResult();
     if ($currentModel instanceof JsonModel) {
         return;
     }
     // Create a new JsonModel and populate with default error information
     $model = new JsonModel();
     // Override with information from actual ViewModel
     $displayExceptions = true;
     if ($currentModel instanceof ModelInterface) {
         $model->setVariables($currentModel->getVariables());
         if ($model->display_exceptions) {
             $displayExceptions = (bool) $data['display_exceptions'];
         }
     }
     // Check for exception
     $exception = $currentModel->getVariable('exception');
     if ($exception && $displayExceptions) {
         // If a code was set in the Exception, then assume that it's the
         // HTTP Status code to be sent back to the client
         if ($exception->getCode()) {
             $e->getResponse()->setStatusCode($exception->getCode());
         }
         // Should probably only render a backtrace this if in development mode!
         $model->backtrace = explode("\n", $exception->getTraceAsString());
         // Assign the message & any previous ones
         $model->message = $exception->getMessage();
         $previousMessages = array();
         while ($exception = $exception->getPrevious()) {
             $previousMessages[] = "* " . $exception->getMessage();
         }
         if (count($previousMessages)) {
             $exceptionString = implode("\n", $previousMessages);
             $model->previous_messages = $exceptionString;
         }
     }
     // Set the result and view model to our new JsonModel
     $model->setTerminal(true);
     $e->setResult($model);
     $e->setViewModel($model);
 }
Пример #25
0
 /**
  * Inspect the result for erroneous action of JSON/AJAX/Feed
  *
  * @param  MvcEvent $e
  * @return void
  */
 public function canonizeErrorResult(MvcEvent $e)
 {
     $result = $e->getResult();
     if ($result instanceof Response) {
         return;
     }
     if (!$this->type) {
         return;
     }
     $response = $e->getResponse();
     $statusCode = $response->getStatusCode();
     if ($statusCode < 400) {
         return;
     }
     // Cast controller view model to result ViewModel
     switch ($this->type) {
         // For Feed
         case 'feed':
             if ($result instanceof FeedModel) {
                 $model = $result;
                 $model->setTemplate('');
                 $model->clearChildren();
             } else {
                 $variables = array();
                 $options = array();
                 if ($result instanceof ViewModel) {
                     $variables = $result->getVariables();
                     $options = $result->getOptions();
                     $variables = (array) new FeedDataModel($variables);
                 } elseif ($result instanceof FeedDataModel) {
                     $variables = (array) $result;
                     $options = array('feed_type' => $result->getType());
                 }
                 $model = new FeedModel($variables, $options);
             }
             break;
             // For Json
         // For Json
         case 'json':
             if ($result instanceof JsonModel) {
                 $model = $result;
                 $model->setTemplate('');
                 $model->clearChildren();
             } else {
                 $variables = array();
                 $options = array();
                 if ($result instanceof ViewModel) {
                     $variables = $result->getVariables();
                     $options = $result->getOptions();
                 }
                 $model = new JsonModel($variables, $options);
             }
             break;
             // For AJAX/Flash
         // For AJAX/Flash
         case 'ajax':
             // MISC
         // MISC
         default:
             if ($result instanceof ViewModel) {
                 $model = $result;
                 $model->setTemplate('');
                 $model->clearChildren();
                 $result = null;
             } else {
                 $model = new ViewModel();
             }
             $model->terminate(true);
             break;
     }
     $e->setViewModel($model);
 }
Пример #26
0
 /**
  * Listen to the render event
  *
  * @param MvcEvent $e
  */
 public static function onRender(MvcEvent $e)
 {
     if (!$e->isError()) {
         return;
     }
     if (self::$acceptFilter != '*') {
         $headers = $e->getRequest()->getHeaders();
         if (!$headers->has('Accept')) {
             return;
         }
         $match = $headers->get('Accept')->match(self::$acceptFilter);
         if (!$match || $match->getTypeString() == '*/*') {
             return;
         }
     }
     $model = $e->getResult();
     if (!$model instanceof ModelInterface) {
         return;
     }
     $exception = $model->getVariable('exception');
     if (!$exception instanceof Exception) {
         return;
     }
     $jsonModel = new JsonModel(array('api-problem' => new ApiProblem($exception->getCode(), $exception)));
     $e->setResult($jsonModel);
     $e->setViewModel($jsonModel);
 }
Пример #27
0
 public function preDispatch(MvcEvent $event)
 {
     /** @var SessionManager $session */
     $session = $event->getTarget()->getServiceLocator()->get('Zend\\Session\\SessionManager');
     $oldSessionId = $this->getSessionIdFromRequest($event->getRequest());
     if ($oldSessionId) {
         $session->setId($oldSessionId);
     }
     $container = new Container('initialized');
     if ($container->offsetGet('init') === null) {
         $session->regenerateId();
         $container->offsetSet('init', 1);
     }
     $auth = $this->getAuthPlugin();
     $acl = $this->getAcl();
     if ($auth->hasIdentity()) {
         $acl->setUserId($auth->getIdentity());
     }
     /** @var AbstractActionController|SecureControllerInterface $controller */
     $controller = $event->getTarget();
     if ($controller instanceof SecureControllerInterface && !$acl->isAllowed($controller->getPrivileges())) {
         /** @var \Zend\Http\PhpEnvironment\Response $response */
         $response = $controller->getResponse();
         $response->setStatusCode(403);
         $response->setReasonPhrase("Permission denied");
         $model = new ApiModel($response);
         $model->setSessionId($this->getSessionId());
         $event->setViewModel($model);
         $event->stopPropagation(true);
     }
 }
Пример #28
0
 /**
  * Creates an MvcEvent object.
  *
  * @param null $lang
  *
  * @return MvcEvent
  */
 protected function createMvcEvent($lang = null)
 {
     $e = new MvcEvent();
     $e->setApplication($this->app);
     $e->setViewModel(new ViewModel());
     $request = new Http\Request();
     if (isset($lang)) {
         $request->setQuery(new Parameters(['lang' => $lang]));
     }
     $e->setRequest($request);
     return $e;
 }
 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;
 }
Пример #30
-1
 public function onDispatchError(MvcEvent $event)
 {
     switch ($event->getError()) {
         case AccessService::ACCESS_DENIED:
             $statusCode = 403;
             break;
         case AccessService::ACCESS_UNAUTHORIZED:
             $statusCode = 401;
             break;
         default:
             // do nothing if this is a different kind of error we should not trap
             return;
     }
     if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
         $viewModel = new JsonModel();
     } else {
         $viewModel = new ViewModel();
         $viewModel->setTemplate('user/' . $statusCode);
     }
     $viewModel->setVariables($event->getParams());
     $response = $event->getResponse() ?: new Response();
     $response->setStatusCode($statusCode);
     $event->setViewModel($viewModel);
     $event->setResponse($response);
 }