Johnny Mnemonick
Johnny Mnemonick

Reputation: 41

Writing to stream is successful. But stream_get_contents() returns empty string

I investigate opportunity to create my own microframework using PSR7 (don't ask my why!).So I created simple httpfoundation and templating components. Now I'm testing this part of my work and have next problem. I create Response object:

public function __construct($statusCode = 200, $headers = null, $body = null)
    {
        $this->statusCode = $statusCode ? $statusCode : $this->checkedStatusCode($statusCode);
        $this->headers = $headers ? $headers : new Headers();
        $this->body = $body ? $body : new Stream(fopen('php://temp', 'w+'));
    }

The view is successfully generated. Then I try to write it in my Response object. The code for this in my templating class

public function render(ResponseInterface $response, $template, array $data)
    {
        $output = $this->retrieve($template, $data);
        $response->getBody()->write($output);
        return $response;
    }

...and in Stream class

public function write($string)
    {
        if (!$this->isWritable()) {
            throw new \RuntimeException('Could not write to stream');
        }

        $result = fwrite($this->stream, $string);
        if ($result === false) {
            throw new \RuntimeException('Could not write to stream');
        }

        return $result;
    }

I think the result is successful because $result contains the number of bytes written! After that I try to retrive contents from my Response object with method dispatch() from Response class

public function dispatch()
    {
        return $this->getBody()->getContents();
    }

...and method getContents() from Stream class

public function getContents()
    {
        if (!$this->stream) {
            throw new \RuntimeException("Stream is not readable");
        }

        $result = stream_get_contents($this->stream);
        if ($result === false) {
            throw new \RuntimeException("Error reading of stream");
        }

        return $result;
    }

I get empty string! Please help me understand where I lose written body! And why I get empty string! Thank U!

Upvotes: 1

Views: 2094

Answers (1)

Julian
Julian

Reputation: 4676

Pointer not set to the beginning of the stream

When writing to Stream is successful but stream_get_contents($this->stream); gives you an empty string may be caused by the pointer that wasn't set to the beginning of the stream. Setting the pointer to the beginning of the stream is possible in a couple of ways.

Possibility #1

// supply a maxlength, and offset
$contents = stream_get_contents($this->stream, -1, 0); 

Possibility #2

rewind($this->stream);
$contents = stream_get_contents($this->stream); 

Possibility #3

fseek($this->stream, 0);
$contents = stream_get_contents($this->stream); 

Upvotes: 4

Related Questions