如何使用Guzzle 6模拟文件响应?

时间:2017-01-07 13:22:19

标签: php guzzle guzzle6 guzzlehttp

以下是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",
}

我试过了:

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

哪个输出:

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) {
  }
}

所以我无法在response.txt中获取JSON内容,该怎么做?我想得到的是:

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

1 个答案:

答案 0 :(得分:1)

Response类构造函数的第三个参数应该是正文字符串。请参阅Guzzle Response类的文档:http://docs.guzzlephp.org/en/latest/psr7.html#guzzle-and-psr-7

以下代码应该有效:

pool.getConnection().then(function(connection) {
  let skuCount = connection.query('select count(sku) "cnt" from products_per_store where store_id = ' + sID + ' group by store_id');
  let assetCount = connection.query('SELECT count(*) "cnt" FROM external_crawl_settings WHERE store_id = ' + sID + ' group by store_id');
  return Promise.all([
     skuCount,
     assetCount
  ]).then((results)=> {
     let skuCount = parseInt(results[0][0].cnt);
     let assetCount = parseInt(results[1][0].cnt);
  if (skuCount * assetCount > 50000) {
     console.log('Too many inputs to run without permission');
}
console.log(skuCount*assetCount);
}).catch((err) => {
    console.log('DATABASE ERROR:', err.stack);
});
}).catch(function(err) {
console.log(err);
});