protected function documentToStream(AbstractDocument $document): StreamInterface
    {
        $encoded = json_encode($document->toArray());

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \RuntimeException('Encoding error: "' . json_last_error_msg() . '""');
        }

        $stream = fopen('php://memory', 'r+');

        fwrite($stream, $encoded);
        fseek($stream, 0);

        return new Stream($stream);
    }