protected static function splitStream(StreamInterface $stream)
    {
        $headers       = [];
        $currentHeader = false;

        while ($line = self::getLine($stream)) {
            if (preg_match(';^(?P<name>[!#$%&\'*+.^_`\|~0-9a-zA-Z-]+):(?P<value>.*)$;', $line, $matches)) {
                $currentHeader = $matches['name'];
                if (! isset($headers[$currentHeader])) {
                    $headers[$currentHeader] = [];
                }
                $headers[$currentHeader][] = ltrim($matches['value']);
                continue;
            }

            if (! $currentHeader) {
                throw new UnexpectedValueException('Invalid header detected');
            }

            if (! preg_match('#^[ \t]#', $line)) {
                throw new UnexpectedValueException('Invalid header continuation');
            }

            // Append continuation to last header value found
            $value = array_pop($headers[$currentHeader]);
            $headers[$currentHeader][] = $value . ltrim($line);
        }

        $body = new Stream('php://temp', 'wb+');
        if (! $stream->eof()) {
            while ($data = $stream->read(4096)) {
                $body->write($data);
            }
            $body->rewind();
        }

        return [$headers, $body];
    }