public function setBody(ResponseInterface $response, $data, $writerType = null)
    {
        if ($data instanceof HttpResponseInterface) {
            $statusCode = $data->getStatusCode();
            if (!empty($statusCode)) {
                $response->setStatus($statusCode);
            }

            $headers = $data->getHeaders();
            if (!empty($headers)) {
                $response->setHeaders($headers);
            }

            $body = $data->getBody();
        } else {
            $body = $data;
        }

        if (!GraphTraverser::isEmpty($body)) {
            if ($writerType instanceof WriterOptions) {
                $options = $writerType;
            } elseif ($writerType instanceof RequestInterface) {
                $options = $this->getWriterOptions($writerType);
            } elseif (is_string($writerType)) {
                $options = new WriterOptions();
                $options->setWriterType($writerType);
            } else {
                $options = new WriterOptions();
                $options->setWriterType(WriterInterface::JSON);
            }

            $writer = null;
            if ($body instanceof HttpWriter\WriterInterface) {
                $writer = $body;
            } elseif ($body instanceof \DOMDocument) {
                $writer = new HttpWriter\Xml($body);
            } elseif ($body instanceof \SimpleXMLElement) {
                $writer = new HttpWriter\Xml($body);
            } elseif ($body instanceof StreamInterface) {
                $writer = new HttpWriter\Stream($body);
            } elseif (is_string($body)) {
                $writer = new HttpWriter\Writer($body);
            }

            // set new response body since we want to discard every data which
            // was written before because this could corrupt our output format
            $response->setBody(new StringStream());

            if ($writer instanceof HttpWriter\WriterInterface) {
                $writer->writeTo($response);
            } else {
                $this->setResponse($response, $body, $options ?? new WriterOptions());
            }
        } else {
            $response->setStatus(204);
            $response->setBody(new StringStream(''));
        }
    }