Call the terminate method on any terminable middleware.

@param  \Illuminate\Http\Request  $request
@param  \Illuminate\Http\Response  $response
@return void
343653
public function terminate($request, $response)
    {
        $middlewares = array_merge(
            $this->gatherRouteMiddlewares($request),
            $this->middleware
        );

        foreach ($middlewares as $middleware) {
            list($name, $parameters) = $this->parseMiddleware($middleware);

            $instance = $this->app->make($name);

            if (method_exists($instance, 'terminate')) {
                $instance->terminate($request, $response);
            }
        }

        //$this->app->terminate();
    }
128866
private function handleRequest(RequestInterface $request, ResponseInterface $response): void
    {
        foreach ($this->routes as $route) {
            $routeMatch = $route->matches($request);

            if ($routeMatch === null) {
                continue;
            }

            $controllerClass = $routeMatch->getControllerClassName();
            $controller = new $controllerClass();

            /** @var ControllerInterface $controller */
            $controller->processRequest($this, $request, $response, $routeMatch->getAction(), $routeMatch->getParameters());

            return;
        }

        $response->setStatusCode(new StatusCode(StatusCode::NOT_FOUND));
    }
1201172
protected function updateResponse(Request $request, Response $response)
    {
        $this->stopProfiling(ProfilingCollection::REQUEST_TIMER);

        if ($this->needToUpdateResponse($response)) {
            $data = $this->getResponseData($response);

            if ($data === false) {
                return;
            }

            $data[$this->responseKey] = $this->storage->getData();

            $this->setResponseData($response, $data);
        }
    }
405726
protected function afterDispatch($response)
    {
        if (!$response instanceof Response) {
            $response = RequestContext::getResponse()->auto($response);
        }

        // Handle Response
        $response->send();

        // Release system resources
        App::trigger(AppEvent::RESOURCE_RELEASE);

        // Trigger 'After Request' event
        App::trigger(HttpServerEvent::AFTER_REQUEST);
    }
425919
public function logoutUser(WebRequest $request, Response $response)
    {
        $this->cleanupSession($request);
        
        $request->removeSession();
    }
1143100
public function executeTerminators(Request $request, Response $response): Response
    {
        $middlewares = $this->filterMiddleware(Terminator::class);

        foreach ($middlewares as $middleware) {
            $response = $middleware->doTerminate($request, $response);
        }

        unset($middlewares);

        return $response;
    }
259015
public function next(Request $request, Response $response, $next)
    {
        if ($this->login()) {
            $next($request, $response);
        }
        // TODO: Implement next() method.
    }
1046933
public function postProcess(Request $request, Response $response)
    {
        if (empty($this->allowedOriginHosts) || !$request->hasHeader('HTTP_ORIGIN')) {
            return;
        }

        $originHost = $request->readHeader('HTTP_ORIGIN')->unsecure();
        foreach ($this->allowedOriginHosts as $allowedOriginHost) {
            if (preg_match('~' . $allowedOriginHost . '~', $originHost) === 1) {
                $response->addHeader('Access-Control-Allow-Origin', $originHost);
            }
        }
    }
1357678
private function finalizeResponse(ResponseInterface $response, ServerRequestInterface $request): ResponseInterface
    {
        /*
                if ($this->hasHeader('Location') && $this->_status === 200) {
                    $this->statusCode(302);
                }
        */

        /*
                if (!isset($this->headers['cache-control'])) {
                    $this->set('Cache-Control', '');
                }
        */

        //TODO : pas sur que cela serve car apache semble ajouter automatiquement la date du jour et on ne peut pas la modifier... :(
        /* RFC2616 - 14.18 says all Responses need to have a Date */
        if (! $response->hasHeader('Date')) {
            $response = $response->withHeader('Date', $this->initDate());
        }

        // add default header text/html
        //if (! $response->hasHeader('Content-Type')) {
        //  $response = $response->withHeader('Content-Type', 'text/html');
        //}

        /*
              $container = $this->getContainer();
              // Fix Content-Type
              $charset = $container['charset'] ? $container['charset'] : 'UTF-8';
        */
        // Fix Content-Type
        $charset = 'UTF-8';
        if (! $response->hasHeader('Content-Type')) {
            $response = $response->withHeader('Content-Type', 'text/html; charset=' . $charset);
        } elseif (0 === stripos($response->getHeaderLine('Content-Type'), 'text/') && false === stripos($response->getHeaderLine('Content-Type'), 'charset')) {
            // add the charset
            $response = $response->withHeader('Content-Type', $response->getHeaderLine('Content-Type') . '; charset=' . $charset);
        }

        if (! $response->hasHeader('Content-Length')) {
            $response = $response->withHeader('Content-Length', (string) $response->getBody()->getSize());
        }

        // check if the response can have a body or not
        // TODO : externaliser ce test "if" dans l'objet Response et faire une méthode "isEmpty()" qui vérifie si le code = 204/205 ou 304
        // TODO : on doit faire la même chose (virer contenttype et contententlength et vider le body) si la réponse est "informational" cad avec un code entre
        if (($response->getStatusCode() >= 100 && $response->getStatusCode() < 200)
        || in_array($response->getStatusCode(), [204, 304])) {
            // TODO : faire un helper pour vider le body d'une response.
            $response = $response->withoutHeader('Content-Type')->withoutHeader('Content-Length')->withBody(new Stream(fopen('php://temp', 'r+')));
            //return;
        }

        // Fix protocol (response will use the same value as the request)
        // TODO : pourquoi on fait pas simplement un $response->setProcotolVersion($request->getProtocolVersion()) ?????
        /*
        preg_match('~^HTTP/([1-9]\.[0-9])$~', $request->server->get('SERVER_PROTOCOL'), $versionMatches);
        if ($versionMatches) {
          $response->setProtocolVersion($versionMatches[1]);
        }*/

        // empty the body if the http method is HEAD (same response as GET but with an empty body) https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
        if ($request->isMethod('HEAD')) {
            // cf. RFC2616 14.13
            $length = $response->getHeaderLine('Content-Length');
            // TODO : regarder si on peut mettre un body à null (cad que cela fasse la même chose qu'une chaine vide '')
            $response->setBody('');
            if ($length) {
                $response = $response->withHeader('Content-Length', $length);
            }
        }

        /* According to RFC2616 section 4.4, we MUST ignore
             Content-Length: headers if we are now receiving data
             using chunked Transfer-Encoding.
          */
        //if ($headers->has('Transfer-Encoding')) {
        //    $headers->remove('Content-Length');
        //}

        /*
                     As Lukas alludet to, HTTP 1.1 prohibits Content-Length if there's a Transfer-Encoding set.

        Quoting http://www.ietf.org/rfc/rfc2616.txt:

           3.If a Content-Length header field (section 14.13) is present, its
             decimal value in OCTETs represents both the entity-length and the
             transfer-length. The Content-Length header field MUST NOT be sent
             if these two lengths are different (i.e., if a Transfer-Encoding
             header field is present). If a message is received with both a
             Transfer-Encoding header field and a Content-Length header field,
             the latter MUST be ignored.
             */

        // TODO : regarder pourquoi cakephp ajout le contenttype uniquement si on a du plain-text !!!!!
        //https://github.com/cakephp/cakephp/blob/master/src/Http/Response.php#L587

        return $response;
    }
335354
public function terminateOutputBuffering($level = 0, $response = null)
    {

        // close response stream before terminating output buffer
        // and only if response is an instance of
        // \Psr\Http\ResponseInterface
        if ($response instanceof ResponseInterface) {
            $body = $response->getBody();
            if ($body->isReadable()) {
                $body->close();
            }
        }

        // Command line output buffering is disabled in cli by default
        if ($this->isCli()) {
            return [];
        }

        // $level needs to be a numeric value
        if (!is_numeric($level)) {
            $level = 0;
        }

        // force type casting to an integer value
        if (!is_int($level)) {
            $level = (int)$level;
        }

        // avoid infinite loop on clearing
        // output buffer by set level to 0
        // if $level is smaller
        if (-1 > $level) {
            $level = 0;
        }

        // terminate all output buffers until $level is 0 or desired level
        // collect all contents and return
        $content = [];
        while (ob_get_level() > $level) {
            $content[] = ob_get_clean();
        }
        return $content;
    }
249343
public function handle(ServerRequestInterface $request, Response $response)
    {
        $server = $request->getServerParams();
        $server['REQUEST_METHOD'] = $request->getMethod();
        $server['REQUEST_URI'] = $request->getUri()->getPath();
        $globals = [
            '_GET' => $request->getQueryParams(),
            '_POST' => $request->getParsedBody()
        ];
        $req = $this->router->match($globals, $server);
        $resourceObject = $this->resource->{$req->method}->uri($req->path)->withQuery($req->query)->eager->request();
        $response = $this->toPsr7Response($response, $resourceObject);

        return $response;
    }
1135138
public function afterSend($request, $response)
    {
        $event = new RequestEvent();
        $event->request = $request;
        $event->response = $response;
        $this->trigger(self::EVENT_AFTER_SEND, $event);
    }
469071
public function run(Request $request, Response $response) : Response {

		$strict = $this->getParam('STRICT_ROUTING');
		$case = $this->getParam('CASE_SENSITIVE');
		$method = $request->getMethod();
		$url = $request->getUri()->getPath();

		//Matching
		foreach($this->routes as $route) {
			if($route->match($url, $strict, $case) && $method == $route->getMethod()) {
				return $route->call($request, $response);
			} elseif($route->match($url, $strict, $case) && $method == 'HEAD') {
				$body = $response->getBody();
				$body->close();
				$response = $response->withBody($body);
				return $response;
			}
		}

		//Error
		$methods = array();
		foreach($this->routes as $route) {
			array_push($methods, $route->getMethod());
			if($route->match($url, $strict, $case) && $method != $route->getMethod() && in_array($method, self::$_METHODS))
				return call_user_func($this->httpErrors['405'], $request, $response);

			elseif($route->match($url, $strict, $case) && $method != $route->getMethod() && !in_array($method, self::$_METHODS))
				return call_user_func($this->httpErrors['400'], $request, $response);
		}

		if(!in_array($method, $methods) && !in_array($method, self::$_METHODS))
			return call_user_func($this->httpErrors['400'], $request, $response);
		else
			return call_user_func($this->httpErrors['404'], $request, $response);
		
	}
1327286
public function execute(\Owl\Http\Request $request, \Owl\Http\Response $response)
    {
        $exception_handler = $this->getExceptionHandler();
        $method = $request->getMethod();
        try {
            if (!in_array($method, ['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH'])) {
                throw \Owl\Http\Exception::factory(501);
            }

            $this->middleware->execute([$request, $response]);
        } catch (\Exception $exception) {
            call_user_func($exception_handler, $exception, $request, $response);
        } catch (\Throwable $error) {
            call_user_func($exception_handler, $error, $request, $response);
        }

        if (!TEST) {
            $response->end();
        }

        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }
    }
1362466
public function log(Request $request, Response $response): void
    {
        $host = $request->url();
        $method = $request->method();
        $agent = $request->userAgent();
        $date = $this->date($response->getDate());
        $status = $response->status();
        $style = $this->style($status);

        $this->output->writeln(
            sprintf("%s %s %s <$style>%d</$style> %s", $host, $date, $method, $status, $agent)
        );
    }
745383
protected function shutdownHandlerCallback(
        ServerRequestInterface $request,
        ResponseInterface $response
    ) : callable {
        /**
         * Shutdown Handler
         */
        return function () use($request, $response) {
            if ($this->haltShutDown === true) {
                return;
            }
            $lastError = error_get_last();
            if (empty($lastError['type'])
                // check if error type is valid error
                || ! in_array($lastError['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR])
            ) {
                return;
            }
            // serve the end of response
            $this->serveResponse(
                $this->getErrorHandler()(
                $request,
                $response,
                new \Error($lastError['message'], $lastError['type'])
            ));
            // exit with 255 code
            exit(255);
        };
    }
984926
public function shutdown(ServerRequestInterface $request, $response)
    {
        $this->offsetUnset('request');
        $this->offsetUnset('response');

        unset($request, $response);

        return 0;
    }