1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wabel\CertainAPI\Response; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* CertainResponse to clean client Response |
9
|
|
|
* |
10
|
|
|
* @author rbergina |
11
|
|
|
*/ |
12
|
|
|
class CertainResponse |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* |
17
|
|
|
* @var ResponseInterface|null |
18
|
|
|
*/ |
19
|
|
|
private $response; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* |
23
|
|
|
* @param ResponseInterface|null $response |
24
|
|
|
*/ |
25
|
|
|
public function __construct($response) |
26
|
|
|
{ |
27
|
|
|
$this->response = $response; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Decode a string to json. If a jsonp we convert ton json string before deconding. |
32
|
|
|
* @param string $jsonp |
33
|
|
|
* @param boolean $assoc |
34
|
|
|
* @return \stdClass|array |
35
|
|
|
*/ |
36
|
|
|
public function jsonp_decode($jsonp, $assoc = false) |
37
|
|
|
{ |
38
|
|
|
// Test we have a JSONP |
39
|
|
|
if ($jsonp[0] !== '[' && $jsonp[0] !== '{') { |
40
|
|
|
$jsonp = substr($jsonp, strpos($jsonp, '(')); |
41
|
|
|
} |
42
|
|
|
return json_decode(trim($jsonp, '();'), $assoc); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Response about results |
47
|
|
|
* @param string $contentType |
48
|
|
|
* @param boolean $assoc |
49
|
|
|
* @return array |
50
|
|
|
*/ |
51
|
|
|
public function getResponse($contentType='json',$assoc = false) |
52
|
|
|
{ |
53
|
|
|
$response = array( |
54
|
|
|
'statusCode' => $this->response?$this->response->getStatusCode():null, |
55
|
|
|
'success' => false, |
56
|
|
|
'results' => null, |
57
|
|
|
'message' => $this->response?$this->response->getReasonPhrase():null |
58
|
|
|
); |
59
|
|
|
if ($this->response && in_array($this->response->getStatusCode(), array(200, 201))) { |
60
|
|
|
$streamBody = $this->response->getBody(); |
61
|
|
|
$bodyString = $streamBody->getContents(); |
62
|
|
|
|
63
|
|
|
if($contentType === 'json'){ |
64
|
|
|
$response['results'] = $this->jsonp_decode($bodyString, $assoc); |
65
|
|
|
}else{ |
66
|
|
|
$response['results']=$bodyString; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$response['success'] = true; |
70
|
|
|
} |
71
|
|
|
return $response; |
72
|
|
|
} |
73
|
|
|
} |