Close response stream and terminate output buffering

@param int $level
@param null|\Psr\Http\Message\ResponseInterface $response
@return array
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;
    }
633583
public function delete(OutputInterface $output, array $response)
    {
        $this->printBoolean($output, 'OK', $response['success'], true === $response['success']);
    }
478399
protected function finish(Response $response)
    {
        if ($this->requestedResultsLocale !== '') {
            $this->getLocalization()->popActiveContext();
        }
        if (!$response->headers->has('X-Frame-Options')) {
            $response->headers->set('X-Frame-Options', 'DENY');
        }
        if (!$response->headers->has('Access-Control-Allow-Origin')) {
            $config = $this->app->make('community_translation/config');
            $response->headers->set('Access-Control-Allow-Origin', (string) $config->get('options.api.accessControlAllowOrigin'));
        }

        return $response;
    }
587179
protected function generateResponse(ResponseInterface $response): array
    {
        $json = $this->validateJson($response);

        $output = [];
        if (!isset($json['LocationList'])) {
            return $output;
        }

        foreach ($json['LocationList'] as $type => $stops) {
            if ($type === 'noNamespaceSchemaLocation') {
                continue;
            }

            $stops = self::checkForSingle($stops, 'name');
            foreach ($stops as $stop) {
                $this->setAllowed($stop, $output);
            }
        }

        return $output;
    }
1298696
public function shutdown($request, $response)
    {
        $routeMiddlewares = $this->router->getMiddlewares();

        $middlewares = array_merge(array_filter([$routeMiddlewares]), $this->getMiddleware());

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

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

            if (method_exists($instance, 'shutdown')) {
                $instance->shutdown($request, $response);
            }
        }
    }
621298
public function finishRequestProcess(RequestProcess $process, ResponseInterface $response = null)
    {
        if ($response) {
            $process->setResponse($response);
        }
        $this->requestStack[] = $process;
    }
351119
private function processThrottleData(ResponseInterface $response)
    {
        if (empty($rateLimit = $response->getHeader('X-RateLimit-Limit'))) {
            return;
        }

        if (empty($remaining = $response->getHeader('X-RateLimit-Remaining'))) {
            return;
        }

        if (!empty($reset = $response->getHeader('X-RateLimit-Reset'))) {
            $this->rateLimit->setEndOfThrottle(intval($reset[0]));
        } else {
            $this->rateLimit->setEndOfThrottle(null);
        }

        $this->rateLimit->setMaxPerMinute(intval($rateLimit[0]))->setRemaining(intval($remaining[0]));
    }
2593
public function terminate(SymfonyRequest $request, SymfonyResponse $response)
	{
		$this->callFinishCallbacks($request, $response);

		$this->shutdown();
	}
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);
        };
    }
406937
public function shutdown($response = null)
    {

        $this->collectGarbage();
        $applicationEvent = $this->getApplicationEvent();
        $applicationEvent->setResponse($response);
        $applicationEvent->setName(self::EVENT_SYSTEM_SHUTDOWN);
        $this->emit($applicationEvent, $this->terminateOutputBuffering(1, $response));
    }
383575
protected function terminateMiddleware(RequestContract $request, ResponseContract $response)
    {
        $middlewares = array_merge(
            $this->middleware,
            $request->matcher()->getCallerMiddleware()
        );

        foreach ($middlewares as $middleware) {
            if (! is_string($middleware)) {
                continue;
            }

            list($name) = $this->parseMiddleware($middleware);

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

            if (method_exists($instance, 'terminate')) {
                $instance->terminate($request, $response);
            }
        }
    }
1016934
public function terminate($sig = null)
    {
        // Terminates application without reading anything more.
        foreach ($this->pipes as $key => $res) {
            $this->close($key);
        }
        $this->debug('process terminated');
        proc_terminate($this->process, $sig);
    }
1313206
public function terminate(Request $request, $response)
    {
        if ($this->isLaravel()) {
            $this->getKernel()->terminate($request, $response);

            return;
        }

        $app = $this->getApplication();
        $reflection = new \ReflectionObject($app);

        $middleware = $reflection->getProperty('middleware');
        $middleware->setAccessible(true);

        $callTerminableMiddleware = $reflection->getMethod('callTerminableMiddleware');
        $callTerminableMiddleware->setAccessible(true);

        if (count($middleware->getValue($app)) > 0) {
            $callTerminableMiddleware->invoke($app, $response);
        }
    }
264295
public function terminate($request, $response)
    {
        if ($this->sessionHandled && $this->sessionConfigured() && ! $this->usingCookieSessions()) {
            $this->manager->driver()->save();
        }
    }
395232
private function finalizeOutputBuffer()
    {
        // Clean out the output buffer to the response, and send the built-up response to the client
        if ($this->isBuffering) {
            $this->response->appendBody(ob_get_contents());
            $this->isBuffering = false;

            ob_end_clean();
        }
    }
362625
static function captureBuffers(?int $targetLevel = null, bool $catchExceptions = false): string
    {
        $output = '';
        $stopLevel = $targetLevel ?? 0;

        foreach (self::iterateBufferLevels(PHP_OUTPUT_HANDLER_CLEANABLE) as $level) {
            if ($level <= $stopLevel) {
                break;
            }

            try {
                $output = ob_get_clean() . $output;
            } catch (\Throwable $e) {
                if (!$catchExceptions) {
                    throw $e;
                }
            }
        }

        return $output;
    }
897507
protected function handleResponse(ResponseInterface $response)
    {
        $status = $response->getStatusCode();

        $data = (string) $response->getBody();
        $jsonResponseData = json_decode($data, false);
        $body = $data && $jsonResponseData === null ? $data : $jsonResponseData;

        return ['status_code' => $status, 'body' => $body];
    }