Using a custom stream wrapper as test stub for PHP's http:// stream wrapper

Viewed 1441

I'm writing a custom stream wrapper to use as a stub in unit tests for an HTTP client class that uses the built-in http:// stream wrapper.

Specifically, I need control over the value returned in the 'wrapper_data' key by calls to stream_get_meta_data on streams created by the custom stream wrapper. Unfortunately, the documentation on custom stream wrappers is woeful and the API seems unintuitive.

What method in a custom wrapper controls the the meta wrapper_data response?

Using the class at the bottom I've only been able to get the following result when I var_dump(stream_get_meta_data($stream)); on streams created with the custom wrapper ...

array(10) {
  'wrapper_data' =>
  class CustomHttpStreamWrapper#5 (3) {
    public $context =>
    resource(13) of type (stream-context)
    public $position =>
    int(0)
    public $bodyData =>
    string(14) "test body data"
  }
  ...

But I need to coax the wrapper into yielding something like the following on meta data retrieval so I can test the client class's parsing of the data returned by the real http:// stream wrapper ...

array(10) {
  'wrapper_data' => Array(
       [0] => HTTP/1.1 200 OK
       [1] => Content-Length: 438
   )
   ...

Here's the code I have currently for the custom wrapper:

class CustomHttpStreamWrapper {

    public $context;
    public $position = 0;
    public $bodyData = 'test body data';

    public function stream_open($path, $mode, $options, &$opened_path) {
        return true;
    }

    public function stream_read($count) {
        $this->position += strlen($this->bodyData);
        if ($this->position > strlen($this->bodyData)) {
            return false;
        }
        return $this->bodyData;
    }

    public function stream_eof() {
        return $this->position >= strlen($this->bodyData);
    }

    public function stream_stat() {
        return array('wrapper_data' => array('test'));
    }

    public function stream_tell() {
        return $this->position;
    }
}
1 Answers
Related