|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the dingtalk. |
|
4
|
|
|
* User: Ilham Tahir <[email protected]> |
|
5
|
|
|
* This source file is subject to the MIT license that is bundled |
|
6
|
|
|
* with this source code in the file LICENSE. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Aplisin\DingTalk\Kernel\Http; |
|
10
|
|
|
|
|
11
|
|
|
use GuzzleHttp\Psr7\Response as GuzzleResponse; |
|
12
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
13
|
|
|
use Aplisin\DingTalk\Kernel\Support\XML; |
|
14
|
|
|
use Aplisin\DingTalk\Kernel\Support\Collection; |
|
15
|
|
|
|
|
16
|
|
|
class Response extends GuzzleResponse |
|
17
|
|
|
{ |
|
18
|
|
|
public function getBodyContents() |
|
19
|
|
|
{ |
|
20
|
|
|
$this->getBody()->rewind(); |
|
21
|
|
|
$contents = $this->getBody()->getContents(); |
|
22
|
|
|
$this->getBody()->rewind(); |
|
23
|
|
|
|
|
24
|
|
|
return $contents; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public static function buildFromPsrResponse(ResponseInterface $response) |
|
28
|
|
|
{ |
|
29
|
|
|
return new static( |
|
30
|
|
|
$response->getStatusCode(), |
|
31
|
|
|
$response->getHeaders(), |
|
32
|
|
|
$response->getBody(), |
|
33
|
|
|
$response->getProtocolVersion(), |
|
34
|
|
|
$response->getReasonPhrase() |
|
35
|
|
|
); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function toJson() |
|
39
|
|
|
{ |
|
40
|
|
|
return json_encode($this->toArray()); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function toArray() |
|
44
|
|
|
{ |
|
45
|
|
|
$content = $this->removeControlCharacters($this->getBodyContents()); |
|
46
|
|
|
|
|
47
|
|
|
if (false !== stripos($this->getHeaderLine('Content-Type'), 'xml') || 0 === stripos($content, '<xml')) { |
|
48
|
|
|
return XML::parse($content); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$array = json_decode($content, true); |
|
52
|
|
|
|
|
53
|
|
|
if (JSON_ERROR_NONE === json_last_error()) { |
|
54
|
|
|
return (array) $array; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
return []; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
public function toCollection() |
|
61
|
|
|
{ |
|
62
|
|
|
return new Collection($this->toArray()); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
public function toObject() |
|
66
|
|
|
{ |
|
67
|
|
|
return json_decode($this->toJson()); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
public function __toString() |
|
71
|
|
|
{ |
|
72
|
|
|
return $this->getBodyContents(); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
protected function removeControlCharacters(string $content) |
|
76
|
|
|
{ |
|
77
|
|
|
return \preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', $content); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|