Dispatches a Request & Response

@param \Cake\Http\ServerRequest $request The request to dispatch.
@param \Cake\Http\Response $response The response to dispatch.
@return \Cake\Http\Response A modified/replaced response.
@throws \ReflectionException
197391
public function dispatch(ServerRequest $request, Response $response)
    {
        if (Router::getRequest(true) !== $request) {
            Router::pushRequest($request);
        }
        $beforeEvent = $this->dispatchEvent('Dispatcher.beforeDispatch', compact('request', 'response'));

        $request = $beforeEvent->getData('request');
        if ($beforeEvent->getResult() instanceof Response) {
            return $beforeEvent->getResult();
        }

        // Use the controller built by an beforeDispatch
        // event handler if there is one.
        if ($beforeEvent->getData('controller') instanceof Controller) {
            $controller = $beforeEvent->getData('controller');
        } else {
            $controller = $this->factory->create($request, $response);
        }

        $response = $this->_invoke($controller);
        if ($request->getParam('return')) {
            return $response;
        }

        $afterEvent = $this->dispatchEvent('Dispatcher.afterDispatch', compact('request', 'response'));

        return $afterEvent->getData('response');
    }
132083
public function handleRequest(ServerRequestInterface $request) : ResponseInterface
    {
        list($callback, $params) = $this->internalRequestHandle($request);

        return call_user_func($callback, $params);
    }
297246
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);
        if ($this->onlyPreflight) {
            if ($this->cors->isPreflightRequest('psr-7', $request)) {
                return $this
                    ->handle($request, $response)
                    ->withStatus(204);
            }

            return $response;
        }

        return $this->handle($request, $response);
    }
93745
public function respond(ServerRequest $request)
    {
        try
        {
            $response = $this->request($request)
                ->finalize()
                ->getResponse();
        }
        catch(\Exception $e)
        {
            if($failRoute = $this->failRoute)
            {
                $response = $this->execute($failRoute, array('exception' => $e, 'request' => $request), $request)
                    ->finalize()
                    ->getResponse();

                $this->failRoute = null;
            }
            else if($this->map->hasFailRoute())
            {
                $response = $this->execute($this->map->getFailRoute(), array('exception' => $e, 'request' => $request), $request)
                    ->finalize()
                    ->getResponse();
            }
            else
            {
                $message = '<pre><h2>['.get_class($e).'] '.$e->getMessage().'</h2>'.PHP_EOL;
                $message .= $e->getTraceAsString();

                $response = Response::createEmptyResponse()
                    ->setStatus(404)
                    ->setBody($message);
            }
        }

        return $response;
    }
1148396
public function response(ServerRequestInterface $request, ResponseInterface $response)
    {
        // Throw Not Found
        //$this->response->exception(404);

        // Demo contents
        $contents = 'It works!';

        // PSR-7 JSON response
        return $this->response->dispatch($response, 200, $contents); // 202
    }
442851
protected function _redirect(ServerRequest $request, Response $response) {
		$message = $request->getSession()->consume($this->_config['flashKey']);
		$url = $response->getHeader('Location')[0];
		$status = $response->getStatusCode();

		$json = JsonEncoder::encode([
			// Error and content are here to make the output the same as previously
			// with the component, so existing unit tests don't break.
			'error' => null,
			'content' => null,
			'_message' => $message,
			'_redirect' => compact('url', 'status'),
		], $this->_config['jsonOptions']);

		$response = $response->withStatus(200)
			->withoutHeader('Location')
			->withHeader('Content-Type', 'application/json; charset=' . $response->getCharset())
			->withStringBody($json);

		return $response;
	}
74158
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $route = $this->routerDispatcher->dispatch($request);
        if (count($route->getAttributes())) {
            foreach ($route->getAttributes() as $key => $value) {
               $request = $request->withAttribute($key, $value);
            }
        }
        $request = $request->withAttribute('route', $route);

        return $handler->handle($request);
    }
292091
public function dispatch(ServerRequestInterface $request)
    {
        if ($this->routeMatched) {
            if (!is_subclass_of($this->actionNamespace, 'App\Action\AppAction')) {
                throw new BaseException(
                    sprintf('Action "%s" does not extend App\Action\AppAction', $this->actionNamespace)
                );
            }

            $actionInstance = new $this->actionNamespace();

            $beforeDispatchEvent = $this->dispatchEvent(
                self::EVENT_BEFORE_DISPATCH,
                $this,
                ['request' => $request, 'action' => $actionInstance]
            );

            if ($beforeDispatchEvent->getResult() instanceof Response) {
                return $beforeDispatchEvent->getResult();
            }

            $response = call_user_func_array([$actionInstance, 'invoker'], $this->params);
            $this->dispatchEvent(self::EVENT_AFTER_DISPATCH, $this, ['request' => $request, 'response' => $response]);

            return $response;
        } else {
            throw new NotFoundException(
                sprintf('Route "%s" does not found', $request->getServerParams()['REQUEST_URI'])
            );
        }
    }
958907
public function handle(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $type = 'psr-7';
        $this->cors->setRequest($type, $request);
        $this->cors->setResponse($type, $response);
        $this->cors->handle();

        return $this->cors->getResponse();
    }
318357
public function dispatch(ServerRequestInterface $request)
    {
        $this->finalize();

        $dispatcher = new GroupCountBasedDispatcher($this->getData());
        $uri = '/'.ltrim($request->getUri()->getPath(), '/');

        return $dispatcher->dispatch($request->getMethod(), $uri);
    }
625803
public function register(
        ServerRequestInterface $request, ResponseInterface $response
    ) {
        $this->request = $request;
        $this->response = $response;
        return $this;
    }
890708
private function responseView(ServerRequestInterface $request, ResponseInterface $response)
    {
        $ctx   = Context::mustGet();
        $views = ViewRegister::getViews();

        // the info of view model
        $controllerClass  = $ctx->get('controllerClass');
        $controllerAction = $ctx->get('controllerAction');

        $actionId = $controllerClass . '@' . $controllerAction;
        if (!isset($views[$actionId])) {
            return $response;
        }

        // Get layout and template
        [$layout, $template] = $views[$actionId];

        // accept and the of response
        $accepts       = $request->getHeader('accept');
        $currentAccept = \current($accepts);

        /* @var \Swoft\Http\Message\Response $response */
        $responseAttribute = AttributeEnum::RESPONSE_ATTRIBUTE;

        $data = $response->getAttribute($responseAttribute);

        // the condition of view
        $isTextHtml = !empty($currentAccept) && $response->isMatchAccept($currentAccept, 'text/html');
        $isTemplate = $controllerClass && $response->isArrayable($data) && $template;

        // show view
        if ($isTextHtml && $isTemplate) {
            if ($data instanceof Arrayable) {
                $data = $data->toArray();
            }

            /* @var \Swoft\View\Renderer $view */
            $view     = \Swoft::getBean('view');
            $content  = $view->render($template, $data, $layout);
            $response = $response
                ->withContent($content)
                ->withAttribute($responseAttribute, null)
                ->withoutHeader('Content-Type')->withAddedHeader('Content-Type', 'text/html');
        }

        return $response;
    }
338544
public function handle(
        ServerRequestInterface $request, ResponseInterface $response
    )
    {
        $path = array_key_exists(self::QUERY_PARAM, $request->getQueryParams())
            ? $request->getQueryParams()[self::QUERY_PARAM]
            : '';
        $uri = Uri::create($request->getUri());
        $queryString = ltrim(
            str_replace(
                self::QUERY_PARAM."={$path}",
                '',
                $uri->getQuery()
            ),
            '&'
        );
        $uri = $uri->withPath(str_replace('//', '/', "/$path"))
            ->withQuery($queryString);
        /** @var ServerRequestInterface $request */
        $request = $request->withUri($uri);
        return $this->executeNext($request, $response);
    }
1247287
public function execute(ServerRequestInterface $request, ResponseInterface $response)
    {
        try {
            return $this->router->start($request, $response);
        } catch (\Exception $e) {
            $this->logger->warning('Unexpected exception: ' . $e->getMessage());
            $this->logger->debug($e->__toString());

            return $response->withStatus(500)
                ->withBody(new StringStream($e->getMessage()));
        }
    }
1108111
protected function errorResponse(ServerRequestInterface $request, ResponseInterface $response)
    {
        if (
            interface_exists(GlobalEnvironmentInterface::class, false) &&
            $response instanceof GlobalEnvironmentInterface &&
            $response->isStale()
        ) {
            $response = $response->revive();
        }

        $errorResponse = $response->withProtocolVersion($request->getProtocolVersion())->withStatus(500);
        $errorResponse->getBody()->write('An unexpected error occured');

        return $errorResponse;
    }
111229
public function modifyResponse(Request $request, ResponseInterface $response)
    {
        if (!$this->isEnabled() || $response instanceof JsonResponse) {
            return $response;
        }

        return $this->injectDebugBar($response);
    }
970046
public function run(
        ServerRequestInterface $request,
        ResponseInterface $response
    )
    {

        if ($this->running)
            throw new \RuntimeException(
                "Failed to run middleware queue: Queue is already running"
            );

        $this->running = true;
        $this->save();

        $next = function (
            ServerRequestInterface $request,
            ResponseInterface $response
        ) use (&$next) {

            if (count($this->middleware) > 0) {

                $middleware = array_shift($this->middleware);
                $response = call_user_func($middleware, $request, $response, $next);

                if (!($response instanceof ResponseInterface))
                    throw new \RuntimeException(
                        "Failed to run middleware: Middleware didn't return ".
                        "a valid ".ResponseInterface::class." object"
                    );
            }

            $this->running = false;
            $this->restore();
            return $response;
        };

        return $next($request, $response);
    }