Permalink
Browse files

Added encoding based on content type for cUrl requests

Signed-off-by: Tom Densham <tom.densham@studiobonito.co.uk>
  • Loading branch information...
1 parent b69de8d commit 88d76b41964ae4e05ca27e2623be0d9546f2becf Tom Densham committed Dec 5, 2011
Showing with 49 additions and 4 deletions.
  1. +49 −4 classes/request/curl.php
@@ -213,8 +213,7 @@ protected function method_get()
*/
protected function method_post()
{
- // TODO this should encode based on content type
- $params = is_array($this->params) ? http_build_query($this->params, null, '&') : $this->params;
+ $params = is_array($this->params) ? $this->encode($this->params) : $this->params;
$this->set_option(CURLOPT_POST, true);
$this->set_option(CURLOPT_POSTFIELDS, $params);
@@ -228,7 +227,7 @@ protected function method_post()
*/
protected function method_put()
{
- $params = http_build_query($this->params, null, '&');
+ $params = is_array($this->params) ? $this->encode($this->params) : $this->params;
$this->set_option(CURLOPT_POSTFIELDS, $params);
@@ -244,11 +243,57 @@ protected function method_put()
*/
protected function method_delete()
{
- $params = http_build_query($this->params, null, '&');
+ $params = is_array($this->params) ? $this->encode($this->params) : $this->params;
$this->set_option(CURLOPT_POSTFIELDS, $params);
// Override method, I think this makes $_POST DELETE data but... we'll see eh?
$this->set_header('X-HTTP-Method-Override', 'DELETE');
}
+
+ /**
+ * Function to encode input array depending on the content type
+ *
+ * @param array $input
+ * @return mixed encoded output
+ */
+ protected function encode(array $input)
+ {
+ // Detect the request content type, default to 'text/plain'
+ $content_type = isset($this->headers['Content-Type']) ? $this->headers['Content-Type'] : $this->response_info('content_type', 'text/plain');
+
+ switch($content_type)
+ {
+ // Format as XML
+ case static::$supported_formats['xml']:
+ $base_node = key($this->params);
+ return \Format::forge($this->params[$base_node])->to_xml(null, null, $base_node);
+ break;
+
+ // Format as JSON
+ case static::$supported_formats['json']:
+ return \Format::forge($this->params)->to_json();
+ break;
+
+ // Format as PHP Serialized Array
+ case static::$supported_formats['serialize']:
+ return \Format::forge($this->params)->to_serialize();
+ break;
+
+ // Format as PHP Array
+ case static::$supported_formats['php']:
+ return \Format::forge($this->params)->to_php();
+ break;
+
+ // Format as CSV
+ case static::$supported_formats['csv']:
+ return \Format::forge($this->params)->to_csv();
+ break;
+
+ // Format as Query String
+ default:
+ return http_build_query($this->params, null, '&');
+ break;
+ }
+ }
}

0 comments on commit 88d76b4

Please sign in to comment.