Emit the response using the PHP SAPI.

@param \Psr\Http\Message\ResponseInterface $response The response to emit
@param \Zend\Diactoros\Response\EmitterInterface|null $emitter The emitter to use.
When null, a SAPI Stream Emitter will be used.
@return void
2886
public function emit(ResponseInterface $response, EmitterInterface $emitter = null)
    {
        if (!$emitter) {
            $emitter = new ResponseEmitter();
        }
        $emitter->emit($response);
    }
1081840
protected function _sendResponse($response)
    {
        if (is_string($response)) {
            echo $response;

            return;
        }

        $emitter = new ResponseEmitter();
        $emitter->emit($response);
    }
503471
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        $this->assertHeadersNotEmitted();
        $this->assertBodyNotEmitted();
        $this->emitStatusLine($response);
        $this->emitHeaders($response);
        $this->emitBody($response);
        $this->closeConnection();

        return $response;
    }
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;
	}
415281
public function runTransient(InputInterface $input=null,
        OutputInterface $output=null
    ) {
        foreach ($this->getEnvironmentMessages() as $message => $style) {
            $this->printLn($message, $style);
        }
    }
1299768
protected function checkResponse(ResponseInterface $response, $data)
    {
        $exception = null;

        if (isset($data['errors'])) {
            foreach ($data['errors'] as $error) {
                $exception = new YextException($error['message'], $error['errorCode'], $exception);
            }
        }

        if ($exception != null) {
            throw $exception;
        }
    }
67382
public function processResponse(ResponseInterface $response)
    {
        if (!$response instanceof Response
            || !$this->getRequest()
        ) {
            return;
        }

        $response = $this->handleResponse($response);
        $this->renderResponse($response);
        $this->terminateApp();
    }
328712
public function sendResponse(ResponseInterface $response): void
    {
        // Send all the headers
        \http_response_code($response->getStatusCode());
        foreach ($response->getHeaders() as $headerName => $headerValues) {
            /** @var string[] $headerValues */
            foreach ($headerValues as $headerValue) {
                \header("$headerName: $headerValue", false);
            }
        }

        // Get the body, rewind it if possible
        $body = $response->getBody();
        if ($body->isSeekable()) {
            $body->rewind();
        }

        // If the body is not readable do not send any body to the client
        if (!$body->isReadable()) {
            return;
        }

        // Send the body (by chunk if specified in the container using streamReadLength value)
        if (null === $this->streamReadLength) {
            echo $body->__toString();

            return;
        }

        while (!$body->eof()) {
            echo $body->read($this->streamReadLength);
        }
    }
121093
public function run(ServerRequestInterface $request, ResponseEmitter $emitter)
    {
        return $emitter->emit($this->handle($request));
    }
56389
public function setEmitter($entityClass, EmitterInterface $emitter)
    {
        $this->emitters->set($entityClass, $emitter);
        return $this;
    }
727032
protected function emitStatusLine(ResponseInterface $response)
    {
        $reasonPhrase = $response->getReasonPhrase();
        header(sprintf(
            'HTTP/%s %d%s',
            $response->getProtocolVersion(),
            $response->getStatusCode(),
            ($reasonPhrase ? ' ' . $reasonPhrase : '')
        ));

        return $this;
    }
290774
protected function emitHeaders(ResponseInterface $response)
    {
        $normalize = function ($headerName) {
            $name     = str_replace('-', ' ', $headerName);
            $filtered = str_replace(' ', '-', ucwords($name));

            return $filtered;
        };
        foreach ($response->getHeaders() as $headerName => $values) {
            $name  = $normalize($headerName);
            $first = true;
            foreach ($values as $value) {
                header(sprintf(
                    '%s: %s',
                    $name,
                    $value
                ), $first);
                $first = false;
            }
        }

        return $this;
    }
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());
          }
      }*/
    }
914224
protected function emitHeaders(ResponseInterface $response){
        foreach($response->getHeaders() as $name => $values){
            if(strtolower($name) === "set-cookie"){
                foreach($values as $value){
                    header(sprintf("Set-Cookie: %s", $value), false);
                }
            }else{
                header(sprintf("%s: %s", $name, implode(", ", $values)));
            }
        }
    }
950680
protected function emitResponse(ResponseInterface $response) {
        $this->logger->flush();
        (new \Zend\HttpHandlerRunner\Emitter\SapiEmitter())->emit($response);
    }
886165
protected function send(
        ResponseInterface $response,
        string $body): ResponseInterface
    {
        if (!$body) {
            $response = $this->sendErrorDocument($response);
        }
        unset($this->errorDocument);
        $response = $response->withHeader(
            Response::HEADER_CONTENT_LENGTH,
            (string) strlen($body));
        header(Response::PROTOCOL
             . $response->getProtocolVersion() . " "
             . $response->getStatusCode() . " "
             . $response->getReasonPhrase());
        foreach ($response->getHeaders() as $key => $value) {
            header($key . ": " . implode("; ", $value));
        }
        $response->getBody()->write($body);
        return $response;
    }