Response.php
2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace PgServiceSdk\Kernel\Http;
use Psr\Http\Message\ResponseInterface;
use PgServiceSdk\Kernel\Support\Collection;
use GuzzleHttp\Psr7\Response as GuzzleResponse;
/**
* Class Response
* @package PgServiceSdk\Kernel\Http
*/
class Response extends GuzzleResponse
{
/**
* 将 ResponseInterface 类型实例 new 自身,这样就可使用父类(\GuzzleHttp\Psr7\Response)的方法
*
* @param ResponseInterface $response
*
* @return \PgServiceSdk\Kernel\Http\Response
*/
public static function buildFromPsrResponse(ResponseInterface $response)
{
return new static(
$response->getStatusCode(),
$response->getHeaders(),
$response->getBody(),
$response->getReasonPhrase()
);
}
/**
* 将响应正文转化为JSON
*
* @return string
*/
public function toJson()
{
return json_encode($this->toArray());
}
/**
* 将响应正文转化为数组
*
* @return array
*/
public function toArray()
{
$array = json_decode($this->getBodyContents(), true);
if (JSON_ERROR_NONE === json_last_error()) {
return (array)$array;
}
return [];
}
/**
* 将响应正文转化为集合
*
* @return Collection
*/
public function toCollection()
{
return new Collection($this->toArray());
}
/**
* 将响应正文转化为对象
*
* @return object
*/
public function toObject()
{
return (object)json_decode($this->getBodyContents());
}
/**
* 获取响应的正文内容
*
* @return string
*/
public function getBodyContents()
{
$this->getBody()->rewind();
$contents = $this->getBody()->getContents();
$this->getBody()->rewind();
return $contents;
}
/**
* 直接输出响应正文
*
* @return string
*/
public function __toString()
{
return $this->getBodyContents();
}
}