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
|
<?php
/**
* PCurl is a REST client libary for PHP.
*
* See http://github.com/purplecode/php.curl for details.
*
* This code is licensed for use, modification, and distribution
* under the terms of the MIT License (see http://en.wikipedia.org/wiki/MIT_License)
*/
namespace PurpleCode\PCurl;
use JMS\Serializer\Exception\RuntimeException;
use JMS\Serializer\SerializerInterface;
class PObjectCurl extends PCurl {
/**
* @var SerializerInterface
*/
private $serializer;
private $responseClass;
public function __construct($host, SerializerInterface $serializer) {
parent::__construct($host);
$this->serializer = $serializer;
$this->contentTypeJson();
}
public function responseClass($class) {
$this->responseClass = $class;
}
public function call($method, $url, $payload = '') {
$payload = $this->serialize($payload);
$response = parent::call($method, $url, $payload);
$response->setBody($this->deserialize($response));
return $response;
}
private function serialize($payload) {
try {
return empty($payload) ? $payload : $this->serializer->serialize($payload, 'json');
} catch (RuntimeException $e) {
throw new PCurlException(sprintf('Unable to serialize payload - %s : %s', $e->getMessage(), $payload));
}
}
private function deserialize($response) {
try {
return $this->responseClass ? $this->serializer->deserialize($response, $this->responseClass, 'json') : $response;
} catch (RuntimeException $e) {
var_dump($response);
throw new PCurlException(sprintf('Unable to deserialize response - %s : %s', $e->getMessage(), $response));
}
}
}
|