diff options
Diffstat (limited to 'src/PurpleCode/PCurl/Object/PObjectCurl.php')
-rw-r--r-- | src/PurpleCode/PCurl/Object/PObjectCurl.php | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/src/PurpleCode/PCurl/Object/PObjectCurl.php b/src/PurpleCode/PCurl/Object/PObjectCurl.php new file mode 100644 index 0000000..e215919 --- /dev/null +++ b/src/PurpleCode/PCurl/Object/PObjectCurl.php @@ -0,0 +1,67 @@ +<?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\Object;
+
+use JMS\Serializer\Exception\RuntimeException;
+use JMS\Serializer\SerializerInterface;
+use PurpleCode\PCurl\PCurl;
+use PurpleCode\PCurl\PCurlException;
+
+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;
+ }
+
+ /**
+ * @return PObjectCurlResponse
+ */
+ public function call($method, $url, $payload = '') {
+ $payload = $this->serialize($payload);
+ $response = parent::call($method, $url, $payload);
+ $object = $this->deserialize($response->getBody());
+ return new PObjectCurlResponse($response->getHeader(), $response->getBody(), $response->getHttpCode(), $object);
+ }
+
+ 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) {
+ if (empty($this->responseClass)) {
+ return $response;
+ }
+ try {
+ return $this->responseClass ? $this->serializer->deserialize($response, $this->responseClass, 'json') : $response;
+ } catch (RuntimeException $e) {
+ throw new PCurlException(sprintf('Unable to deserialize response - %s : %s', $e->getMessage(), $response));
+ }
+ }
+
+}
|