Send response to the application server.

@param ResponseInterface $response
194062
public function respond(ResponseInterface $response)
    {
        $this->httpClient->respond(
            $response->getStatusCode(),
            $response->getBody()->__toString(),
            $response->getHeaders()
        );
    }
154943
private function emit(ResponseInterface $response){
        $params = [
            "start"     => null,
            "finish"    => null,
            "error"     => null,
        ];

        try{
            $params["start"]    = microtime(true);

            $this->emitter->emit($response);
        }catch(\Throwable $e){
            $params["error"]    = $e;
            $this->error        = $e;
        }finally{
            $params["finish"]   = microtime(true);
        }

        $this->event(new Event("response.emit.after", $params));
    }
791872
private function emitHeaders(ResponseInterface $response): void
    {
        /*
        if (headers_sent($file, $line)) {
            throw new \RuntimeException(sprintf('Failed to send headers, because headers have already been sent by "%s" at line %d.', $file, $line));
        }*/
        // headers have already been sent by the developer
        if (headers_sent()) {
            return;
        }

        $statusCode = $response->getStatusCode();

        // TODO : regarder ici pour voir comment on emet les cookies !!!!! https://github.com/zendframework/zend-diactoros/blob/master/src/Response/SapiEmitterTrait.php#L78
        // TODO : regarder ici, car un header peut avoir un tableau de valeurs, dans le cas ou on a mergé 2 headers identiques !!!!   https://github.com/slimphp/Slim/blob/3.x/Slim/App.php#L393
        // headers
        foreach ($response->getHeaders() as $name => $values) {
            $first = stripos($name, 'Set-Cookie') === 0 ? false : true;
            foreach ($values as $value) {
                header(sprintf('%s: %s', $name, $value), $first, $statusCode);
                $first = false;
            }
        }

        // TODO : gérer le cas ou il n'y a pas de ReasonPhrase et mettre une chaine vide : https://github.com/zendframework/zend-diactoros/blob/master/src/Response/SapiEmitterTrait.php#L55
        // Set proper protocol, status code (and reason phrase) header
        /*
        if ($response->getReasonPhrase()) {
            header(sprintf(
                'HTTP/%s %d %s',
                $response->getProtocolVersion(),
                $response->getStatusCode(),
                $response->getReasonPhrase()
            ));
        } else {
            header(sprintf(
                'HTTP/%s %d',
                $response->getProtocolVersion(),
                $response->getStatusCode()
            ));
        }*/

        // It is important to mention that this method should be called after the headers are sent, in order to prevent PHP from changing the status code of the emitted response.
        header(sprintf('HTTP/%s %d %s', $response->getProtocolVersion(), $statusCode, $response->getReasonPhrase()), true, $statusCode);

        // cookies
//TODO : utiliser les cookies comme des "headers" classiques ('Set-Cookies:xxxxxxx')
//https://github.com/paragonie/PHP-Cookie/blob/master/src/Cookie.php#L358

//        foreach ($response->getCookies() as $cookie) {
//          setrawcookie($cookie['name'], $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
//        }

//        flush();
//      }

      // cookies
      /*
      foreach ($this->headers->getCookies() as $cookie) {
          if ($cookie->isRaw()) {
              setrawcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
          } else {
              setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
          }
      }*/
    }
120663
public function sendResponseHttpHeaders(ResponseInterface $response):void
    {
        // checking
        if (headers_sent()) {
            throw new ResponseSenderException("A response has already been sent to the web browser",
                $this);
        }

        // removing PHP native HTTP headers (if enabled)
        if ($this->removePhpHttpHeaders) {
            foreach (headers_list() as $header) {
                header_remove(explode(":", $header)[0]);
            }
        }

        // sending response HTTP headers
        $this->sendHttpVersionHeader(
            $response->getProtocolVersion(),
            $response->getStatusCode(),
            $response->getReasonPhrase()
        );
        $this->sendHttpHeaders($this->listResponseHeaders($response));
    }
1074326
public function send(RequestInterface $request, MessageInterface $response)
    {
        $cacheKey = $this->generateCacheKeyForRequest($request);

        if ($this->cache->contains($cacheKey)) {
            $this->hits++;

            $cachedResponse = unserialize($this->cache->fetch($cacheKey));
            /* @var $cachedResponse \Buzz\Message\Response */

            $response->setContent($cachedResponse->getContent());
            $response->setHeaders($cachedResponse->getHeaders());

            return;
        }

        $this->misses++;

        $this->client->send($request, $response);

        $this->cache->save($cacheKey, serialize($response), $this->lifetime);
    }
697066
public function send(Response $response = null)
    {
        if ($response) {
            $this->response = $response;
        }
        $this->response->prepare($this->request);
        $this->response->send();

        // If a cacheWrite callback exists execute
        // it now to write the image to the cache
        if (is_callable($this->cacheWrite)) {
            call_user_func_array(
                $this->cacheWrite,
                array($this->cache, $this->getCachePath())
            );
        }
    }
336647
public function sendResponse($response)
    {
        // clean any previous output from buffer. Not effective in some cases
        while (ob_get_level() > 0) {
            ob_end_clean();
        }

        // console //

        if ($response instanceof ConsoleResponse) {
            echo $response->getContent();
            $errorLevel = (int) $response->getErrorLevel();
            exit($errorLevel);
        }


        // http //

        // send headers
        foreach ($response->getHeaders() as $header) {
            header($header->toString());
        }

        // send status
        $status = $response->renderStatusLine();
        header($status);

        // send content
        echo $response->getContent();
        exit(1);
    }
121867
public function sendHeaders(ResponseInterface $response): self
    {
        // headers have already been sent by the developer
        if (headers_sent()) {
            return $this;
        }

        $headers = $response->getHeaders();
        if (!isset($headers['date'])) {
            $date = new DateTime();
            $date->setTimezone(new \DateTimeZone('UTC'));
            $headers['date'][] = $date->format('D, d M Y H:i:s').' GMT';
        }
        $statusCode = $response->getStatusCode();

        // headers
        foreach ($headers as $name => $values) {
            foreach ($values as $value) {
                header($name.': '.$value, false, $statusCode);
            }
        }

        // status
        header(sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $statusCode, $response->getReasonPhrase()), true, $statusCode);

        // todo: cookies

        return $this;
    }
212017
public function respond($response)
	{
		if (
			$this->logger !== null &&
			$this->logger->isHandling(Logger::DEBUG)
		) {
			$this->logger->addDebug(
				'Send response',
				array(
					 'content-type' => $this->contentType,
					 'response'     => ctype_print($response) ? $response : 'base64:' . base64_encode($response)
				)
			);
		}

		ob_start();
		while (ob_end_clean()) {
		}
		header('Content-Type: ' . $this->contentType);
		echo $response;
	}
1030008
public function handle(
        ServerRequestInterface $request, ResponseInterface $response
    )
    {
        $this->request = $request;
        $render = $this->request->getAttribute('render', true);
        if ($render) {
            $response = $this->render($response);
        }
        return $this->executeNext($request, $response);
    }
593041
protected function handleResponse(ResponseInterface $response)
    {
        $responseWrapper = new Response($response);
        $statusCode = (int) floor($response->getStatusCode() / 100);

        if ($statusCode === 4) {
            throw new ClientException($responseWrapper);
        } elseif ($statusCode === 5) {
            throw new ServerException($responseWrapper);
        }

        return $responseWrapper;
    }
892227
protected function handle(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $cors = $this->cors->getCors();
        $cors->setRequest('psr-7', $request);
        $cors->setResponse('psr-7', $response);
        $cors->handle();

        return $cors->getResponse();
    }
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();
    }
850042
protected function handleResponse(ResponseInterface $response)
    {
        $this->rateLimit = new RateLimit;
        $this->rateLimit->dailyLimit = (integer) $response->getHeaderLine('RateLimit-DailyLimit');
        $this->rateLimit->remaining = (integer) $response->getHeaderLine('RateLimit-Remaining');
        $this->rateLimit->resetTime = $response->getHeaderLine('RateLimit-ResetTime');

        return $response;
    }
998967
public function send(DispatcherResponseInterface $response)
    {
        $request  = $response->getRequest();

        if($response->isStreamable())
        {
            //Explicitly set the Accept Ranges header to bytes to inform client we accept range requests
            $response->headers->set('Accept-Ranges', 'bytes');

            if($request->isStreaming())
            {
                if($response->isSuccess())
                {
                    if(ini_get('zlib.output_compression')) {
                        @ini_set('zlib.output_compression', 'Off');
                    }

                    //Fix for IE7/8
                    if(function_exists('apache_setenv')) {
                        @apache_setenv('no-gzip', '1');
                    }

                    //Remove PHP time limit
                    if(!ini_get('safe_mode')) {
                        @set_time_limit(0);
                    }

                    //Default Content-Type Header
                    if(!$response->headers->has('Content-Type')) {
                        $response->headers->set('Content-Type', 'application/octet-stream');
                    }

                    //Content Range Headers
                    $offset = $this->getOffset($response);
                    $range  = $this->getRange($response);
                    $size   = $this->getFileSize($response);

                    $response->setStatus(HttpResponse::PARTIAL_CONTENT);
                    $response->headers->set('Content-Length', $range - $offset + 1);
                    $response->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $offset, $range, $size));
                }

                if($response->isError())
                {
                    /**
                     * A server sending a response with status code 416 (Requested range not satisfiable) SHOULD include a
                     * Content-Range field with a byte-range- resp-spec of "*". The instance-length specifies the current
                     * length of the selected resource.
                     *
                     * @see : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
                     */
                    if($response->getStatusCode() == HttpResponse::REQUESTED_RANGE_NOT_SATISFIED)
                    {
                        $size = $this->getFileSize($response);
                        $response->headers->set('Content-Range', sprintf('bytes */%s', $size));
                    }
                }
            }
        }

        return parent::send($response);
    }
874298
private function sendResponse(int $requestId, ResponseInterface $response): void
    {
        $statusCode   = $response->getStatusCode();
        $reasonPhrase = $response->getReasonPhrase();

        $headerData = "Status: {$statusCode} {$reasonPhrase}\r\n";

        foreach ($response->getHeaders() as $name => $values) {
            $headerData .= $name.': '.implode(', ', $values)."\r\n";
        }

        $headerData .= "\r\n";

        $this->writeResponse($requestId, $headerData, $response->getBody()->detach());
    }
580572
protected function handleErrors(ResponseInterface $response)
    {
        $statusCode = $response->getStatusCode();
        switch ($statusCode) {
            case 400:
                throw HttpClientException::badRequest($response);
            case 401:
                throw HttpClientException::unauthorized($response);
            case 402:
                throw HttpClientException::requestFailed($response);
            case 404:
                throw HttpClientException::notFound($response);
            case 413:
                throw HttpClientException::payloadTooLarge($response);
            case 500 <= $statusCode:
                throw HttpServerException::serverError($statusCode);
            default:
                throw new UnknownErrorException();
        }
    }