/** * @param MvcEvent $e * @return mixed|void */ public function onDispatch(MvcEvent $e) { $viewModel = new ViewModel(); $valid = $this->collageData->isValid(); $data = $this->authenticationService->getAuthData(); $viewModel->setVariable('validInputs', $this->collageData->getValidInput()); $viewModel->setVariable('user', $data->user); if (!$valid) { $viewModel->setTemplate('frontend/gallery/error'); $viewModel->setVariable('messages', $this->collageData->getMessages()); return $e->setResult($viewModel); } $uniqueId = md5(serialize($this->collageData->getValues())); if ($this->sessionContainer->valuesHash != $uniqueId) { $collectionService = $this->collectionFactory->createCollection($this->collageData); $images = $collectionService->getImages($this->collageData); } else { $images = $this->sessionContainer->images; } $collageHttpPath = $this->collageService->create($images, $uniqueId, $this->collageData->getWidth(), $this->collageData->getHeight(), $this->collageData->getLimit()); if ($collageHttpPath !== false) { $viewModel->setVariable('collageHttpPath', $collageHttpPath); } $viewModel->setTemplate('frontend/gallery/index'); return $e->setResult($viewModel); }
/** * @return mixed */ public function notFoundByRequestedCriteria($criteriaErrors) { $zendResponse = $this->mvcEvent->getResponse(); $zendResponse->setStatusCode(404); $this->viewModel->setVariable('message', 'The requested resource was not found by requested criteria'); $this->viewModel->setTemplate('error/404'); $this->mvcEvent->setResult($this->viewModel); return $this->viewModel; }
protected function displayError($template, $status = 403) { $model = new ViewModel(); $model->setTerminal(false); $model->setTemplate($template); /** @var $response \Zend\Http\PhpEnvironment\Response */ $response = $this->_event->getResponse(); $response->setStatusCode($status); $this->_event->setResponse($response); $this->_event->setResult($model); return; }
/** * @param MvcEvent $e * @return mixed|void */ public function onDispatch(MvcEvent $e) { $viewModel = new ViewModel(); $viewModel->setVariable('loginUri', $this->instagramWrapper->getLoginUrl()); $viewModel->setTemplate('frontend/index'); $e->setResult($viewModel); }
/** * @param MvcEvent $event * @return mixed * @throws \Exception */ public function onDispatch(MvcEvent $event) { $routeMatch = $event->getRouteMatch(); if (!$routeMatch) { throw new \DomainException('Missing route matches.'); } $handler = $this->getExceptionHandler(); $action = $routeMatch->getParam('action', 'not-found'); if ($this instanceof InitializableInterface) { try { $this->init(); } catch (\Exception $e) { return $handler->tryHandle($e); } } $method = static::getMethodFromAction($action); if (!method_exists($this, $method)) { $method = 'notFoundAction'; } try { if ($this->protectRequestMethodByPrefix) { $this->protectRequestMethod($method); } $actionResponse = $this->{$method}($this->getRequest(), $this->getResponse()); $event->setResult($actionResponse); return $actionResponse; } catch (\Exception $e) { return $handler->tryHandle($e); } }
/** * 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); }
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; }
/** * @param MvcEvent $e */ protected function handleError(MvcEvent $e) { $router = $e->getRouter(); if ($this->authenticationService->hasIdentity()) { if (!$this->options->getRedirectWhenConnected()) { return; } $redirectRoute = $this->options->getRedirectToRouteConnected(); } else { $redirectRoute = $this->options->getRedirectToRouteDisconnected(); } $params = array(); $options = array('name' => $redirectRoute); if ($this->options->getAppendPreviousUri()) { $redirectKey = $this->options->getPreviousUriRouteKey(); $previousUri = $e->getRequest()->getUriString(); $params = array($redirectKey => $previousUri); } $uri = $router->assemble($params, $options); $response = $e->getResponse() ?: new HttpResponse(); $response->getHeaders()->addHeaderLine('Location', $uri); $response->setStatusCode(302); $e->setResponse($response); $e->setResult($response); }
/** * @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); }
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); } }
public function onDispatch(MvcEvent $e) { $routeMatch = $e->getRouteMatch(); $contentNegotiationParams = $e->getParam('ZFContentNegotiationParameterData'); if ($contentNegotiationParams) { $routeParameters = $contentNegotiationParams->getRouteParams(); } else { $routeParameters = $routeMatch->getParams(); } $parameterMatcher = new ParameterMatcher($e); // match route params to dispatchable parameters if ($this->wrappedCallable instanceof \Closure) { $callable = $this->wrappedCallable; } elseif (is_array($this->wrappedCallable) && is_callable($this->wrappedCallable)) { $callable = $this->wrappedCallable; } elseif (is_object($this->wrappedCallable) || is_null($this->wrappedCallable)) { $action = $routeMatch->getParam('action', 'not-found'); $method = static::getMethodFromAction($action); $callable = is_null($this->wrappedCallable) && get_class($this) != __CLASS__ ? $this : $this->wrappedCallable; if (!method_exists($callable, $method)) { $method = 'notFoundAction'; } $callable = [$callable, $method]; } else { throw new \Exception('RPC Controller Not Understood'); } $dispatchParameters = $parameterMatcher->getMatchedParameters($callable, $routeParameters); $result = call_user_func_array($callable, $dispatchParameters); $e->setParam('ZFContentNegotiationFallback', ['Zend\\View\\Model\\JsonModel' => ['application/json']]); $e->setResult($result); }
public function testDoNotSetTemplateIfNotResourceViewModel() { $model = $this->getMock(ModelInterface::class); $model->expects($this->never())->method('setTemplate'); $mvcEvent = new MvcEvent(); $mvcEvent->setResult($model); $this->resourceStrategy->setTemplate($mvcEvent); }
public function onDispatch(MvcEvent $e) { if (!$e->getRequest() instanceof ConsoleRequest) { throw new RuntimeException('You can only use this action from a console!'); } $version = $e->getRequest()->getParam('version'); $force = $e->getRequest()->getParam('force'); $down = $e->getRequest()->getParam('down'); if (is_null($version) && $force) { $response = "Can't force migration apply without migration version explicitly set.\n"; $e->setResult($response); return $response; } $this->migration->migrate($version, $force, $down); $response = "Migrations applied!\n"; $e->setResult($response); return $response; }
/** * @param MvcEvent $e * @return mixed|void */ public function onDispatch(MvcEvent $e) { $viewModel = new ViewModel(); $data = $this->authenticationService->getAuthData(); $viewModel->setVariable('user', $data->user); $viewModel->setVariable('configure', true); $viewModel->setTemplate('frontend/gallery/index'); $e->setResult($viewModel); }
public function onDispatch(MvcEvent $e) { if (!$e->getRequest() instanceof ConsoleRequest) { throw new RuntimeException('You can only use this action from a console!'); } $response = sprintf("Current version %s\n", $this->table->getCurrentVersion()); $e->setResult($response); return $response; }
/** * Inspect the result, and cast it to a ViewModel if an assoc array is detected * * @param MvcEvent $e * @return void */ public function createViewModelFromArray(MvcEvent $e) { $result = $e->getResult(); if (!IsAssocArray::test($result, true)) { return; } $model = new ViewModel($result); $e->setResult($model); }
public function options(MvcEvent $event) { if (!($result = $event->getResult())) { $result = new Result(); $event->setResult($result); } $result->setStatusCode(405); return $result; }
/** * @param MvcEvent $event * @return ApiProblemResponse */ public function __invoke(MvcEvent $event) { if (!$this->BasicAuthenticationService->authenticate()) { $event->getResponse()->setStatusCode(401); $model = new JsonModel(array("code" => "InvalidCredentials", "message" => "Invalid Client Credentials.")); $event->setResult($model); return $model; } }
/** * Inspect the result, and cast it to a ViewModel if null is detected * * @param MvcEvent $e * @return void */ public function createViewModelFromNull(MvcEvent $e) { $result = $e->getResult(); if (null !== $result) { return; } $model = new ViewModel(); $e->setResult($model); }
/** * @param MvcEvent $e */ public function handleError(MvcEvent $e) { $model = new ViewModel(); $model->setTemplate($this->options->getTemplate()); $response = $e->getResponse() ?: new HttpResponse(); $response->setStatusCode(403); $e->setResponse($response); $e->setResult($model); }
/** * @param MvcEvent $e * @return mixed|void */ public function onDispatch(MvcEvent $e) { $adapter = new QueryPaginator($this->entityManager->getRepository($this->options->getImageEntityClass())->createQueryBuilder('img')); $paginator = new Paginator($adapter, $this->getRequest()->getHeaders(), $this->getResponse()->getHeaders()); $imageExtractor = new ImageExtractor(new DoctrineObject($this->entityManager, $this->options->getImageEntityClass())); $result = new JsonModel($imageExtractor); $result->setPaginator($paginator); $e->setResult($result); }
public function onDispatch(MvcEvent $e) { if (!$e->getRequest() instanceof ConsoleRequest) { throw new RuntimeException('You can only use this action from a console!'); } $classPath = $this->generator->generate(); $response = sprintf("Generated skeleton class @ %s\n", realpath($classPath)); $e->setResult($response); return $response; }
/** * Execute the request * * @param MvcEvent $e * @return ReadViewModelInterface */ public function onDispatch(MvcEvent $e) { $entity = $this->repository->find($this->criteria); if (!$entity) { return $this->notFoundAction(); } $this->viewModel->setEntity($entity); $e->setResult($this->viewModel); return $this->viewModel; }
/** * @param MvcEvent $e * @return mixed | void */ public function onDispatch(MvcEvent $e) { $removeModel = new RemoveModel(); if (!$this->remover->remove($this->getResource())) { $removeModel->fail(); } else { $removeModel->success(); } $e->setResult($removeModel); }
/** * Display messages on console * * @param MvcEvent $e * @param string $validationMessages * @return void */ private function displayMessages(MvcEvent $e, $validationMessages) { /** @var \Zend\Console\Adapter\AdapterInterface $console */ $console = $e->getApplication()->getServiceManager()->get('console'); $validationMessages = $console->colorize($validationMessages, ColorInterface::RED); $model = new ConsoleModel(); $model->setErrorLevel(1); $model->setResult($validationMessages); $e->setResult($model); }
public function onDispatch(MvcEvent $e) { /** @var \BedRest\Rest\Dispatcher $dispatcher */ $dispatcher = $this->getServiceLocator()->get('BedRest.Dispatcher'); $data = $dispatcher->dispatch($this->restRequest); $result = new ViewModel($data); $result->setAccept($this->restRequest->getAccept()); $e->setResult($result); return $result; }
public function onError(MvcEvent $event) { // Do nothing if no error or if response is not HTTP response if (!($exception = $event->getParam('exception') instanceof UnauthorizedExceptionInterface) || !($response = $event->getResponse() instanceof HttpResponse)) { return; } $response = $event->getResponse() ?: new HttpResponse(); $event->setResponse($response); $event->setResult($response); }
/** * @inheritdoc */ public function onDispatch(MvcEvent $e) { $viewModel = new ViewModel(); if (!$this->params('method', false)) { $this->dispatchObject($viewModel); } else { $this->dispatchMethod($viewModel); } $e->setResult($viewModel); }
/** * @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); }
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; }