How to mock response from file using Guzzle 6?

1k Views Asked by At

Here is the content of response.txt:

HTTP/1.1 200 OK
Server: nginx
Date: Fri, 15 Feb 2016 18:25:28 GMT
Content-Type: application/json;charset=utf-8

{
  "field1": "a",
  "field2": "b",
}

I tried:

$stream = Psr7\stream_for(file_get_contents('response.txt'));
$response = new Response(200, ['Content-Type' => 'application/json'], $stream);
dd($response->getBody());

Which output:

object(GuzzleHttp\Psr7\Stream)#3 (7) {
  ["stream":"GuzzleHttp\Psr7\Stream":private]=>
  resource(26) of type (stream)
  ["size":"GuzzleHttp\Psr7\Stream":private]=>
  NULL
  ["seekable":"GuzzleHttp\Psr7\Stream":private]=>
  bool(true)
  ["readable":"GuzzleHttp\Psr7\Stream":private]=>
  bool(true)
  ["writable":"GuzzleHttp\Psr7\Stream":private]=>
  bool(true)
  ["uri":"GuzzleHttp\Psr7\Stream":private]=>
  string(10) "php://temp"
  ["customMetadata":"GuzzleHttp\Psr7\Stream":private]=>
  array(0) {
  }
}

So I can not get the JSON content in response.txt, how to do that? What I want to get is something like:

array('field1'=>'a','field2'=>'b');
1

There are 1 best solutions below

2
On

The third parameter to the Response class constructor should be the body string. See the documentation for the Guzzle Response class: http://docs.guzzlephp.org/en/latest/psr7.html#guzzle-and-psr-7.

The following code should work:

$stream = file_get_contents('response.txt');
$response = new Response(200, ['Content-Type' => 'application/json'], $stream);
dd($response->getBody());