Skip to content

[PHP] update API client to support default header, better accept and content-type #759

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 79 additions & 11 deletions modules/swagger-codegen/src/main/resources/php/APIClient.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ class APIClient {
public static $GET = "GET";
public static $PUT = "PUT";
public static $DELETE = "DELETE";

private static $default_header = array();

/*
* @var string timeout (second) of the HTTP request, by default set to 0, no timeout
Expand All @@ -46,24 +48,55 @@ class APIClient {
}

/**
* Set the user agent of the API client
* add default header
*
* @param string $user_agent The user agent of the API client
* @param string $header_name header name (e.g. Token)
* @param string $header_value header value (e.g. 1z8wp3)
*/
public function addDefaultHeader($header_name, $header_value) {
if (!is_string($header_name))
throw new \InvalidArgumentException('Header name must be a string.');

self::$default_header[$header_name] = $header_value;
}

/**
* get the default header
*
* @return array default header
*/
public function getDefaultHeader() {
return self::$default_header;
}

/**
* delete the default header based on header name
*
* @param string $header_name header name (e.g. Token)
*/
public function deleteDefaultHeader($header_name) {
unset(self::$default_header[$header_name]);
}

/**
* set the user agent of the api client
*
* @param string $user_agent the user agent of the api client
*/
public function setUserAgent($user_agent) {
if (!is_string($user_agent)) {
throw new Exception('User-agent must be a string.');
}
if (!is_string($user_agent))
throw new \InvalidArgumentException('User-agent must be a string.');

$this->user_agent= $user_agent;
}

/**
* @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
*/
*/
public function setTimeout($seconds) {
if (!is_numeric($seconds)) {
throw new Exception('Timeout variable must be numeric.');
}
if (!is_numeric($seconds))
throw new \InvalidArgumentException('Timeout variable must be numeric.');

$this->curl_timeout = $seconds;
}

Expand All @@ -83,6 +116,9 @@ class APIClient {
# Allow API key from $headerParams to override default
$added_api_key = False;
if ($headerParams != null) {
# add default header
$headerParams = array_merge((array)self::$default_header, $headerParams);

foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val";
if ($key == $this->headerName) {
Expand Down Expand Up @@ -111,6 +147,7 @@ class APIClient {
}
// return the result on success, rather than just TRUE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

if (! empty($queryParams)) {
Expand All @@ -130,7 +167,7 @@ class APIClient {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method != self::$GET) {
throw new Exception('Method ' . $method . ' is not recognized.');
throw new APIClientException('Method ' . $method . ' is not recognized.');
}
curl_setopt($curl, CURLOPT_URL, $url);

Expand Down Expand Up @@ -261,7 +298,6 @@ class APIClient {
* @param string $class class name is passed as a string
* @return object an instance of $class
*/

public static function deserialize($data, $class)
{
if (null === $data) {
Expand Down Expand Up @@ -304,5 +340,37 @@ class APIClient {
return $deserialized;
}

/*
* return the header 'Accept' based on an array of Accept provided
*
* @param array[string] $accept Array of header
* @return string Accept (e.g. application/json)
*/
public static function selectHeaderAccept($accept) {
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
return NULL;
} elseif (preg_grep("/application\/json/i", $accept)) {
return 'application/json';
} else {
return implode(',', $accept);
}
}

/*
* return the content type based on an array of content-type provided
*
* @param array[string] content_type_array Array fo content-type
* @return string Content-Type (e.g. application/json)
*/
public static function selectHeaderContentType($content_type) {
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
return 'application/json';
} elseif (preg_grep("/application\/json/i", $content_type)) {
return 'application/json';
} else {
return implode(',', $content_type);
}
}

}

9 changes: 4 additions & 5 deletions modules/swagger-codegen/src/main/resources/php/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class {{classname}} {
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if (${{paramName}} === null) {
throw new \Exception("Missing the required parameter ${{paramName}} when calling {{nickname}}");
throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}');
}
{{/required}}{{/allParams}}

Expand All @@ -54,12 +54,11 @@ class {{classname}} {
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = '{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}';
if ($_header_accept !== '') {
$_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$_header_content_type = array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}});
$headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json';
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}));

{{#queryParams}}// query params
if(${{paramName}} !== null) {
Expand Down
101 changes: 85 additions & 16 deletions samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ class APIClient {
public static $GET = "GET";
public static $PUT = "PUT";
public static $DELETE = "DELETE";

private static $default_header = array();

/*
* @var string timeout (second) of the HTTP request, by default set to 0, no timeout
Expand All @@ -46,24 +48,55 @@ function __construct($host, $headerName = null, $headerValue = null) {
}

/**
* Set the user agent of the API client
* add default header
*
* @param string $user_agent The user agent of the API client
* @param string $header_name header name (e.g. Token)
* @param string $header_value header value (e.g. 1z8wp3)
*/
public function addDefaultHeader($header_name, $header_value) {
if (!is_string($header_name))
throw new \InvalidArgumentException('Header name must be a string.');

self::$default_header[$header_name] = $header_value;
}

/**
* get the default header
*
* @return array default header
*/
public function getDefaultHeader() {
return self::$default_header;
}

/**
* delete the default header based on header name
*
* @param string $header_name header name (e.g. Token)
*/
public function deleteDefaultHeader($header_name) {
unset(self::$default_header[$header_name]);
}

/**
* set the user agent of the api client
*
* @param string $user_agent the user agent of the api client
*/
public function setUserAgent($user_agent) {
if (!is_string($user_agent)) {
throw new Exception('User-agent must be a string.');
}
if (!is_string($user_agent))
throw new \InvalidArgumentException('User-agent must be a string.');

$this->user_agent= $user_agent;
}

/**
* @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
*/
*/
public function setTimeout($seconds) {
if (!is_numeric($seconds)) {
throw new Exception('Timeout variable must be numeric.');
}
if (!is_numeric($seconds))
throw new \InvalidArgumentException('Timeout variable must be numeric.');

$this->curl_timeout = $seconds;
}

Expand All @@ -83,6 +116,9 @@ public function callAPI($resourcePath, $method, $queryParams, $postData,
# Allow API key from $headerParams to override default
$added_api_key = False;
if ($headerParams != null) {
# add default header
$headerParams = array_merge((array)self::$default_header, $headerParams);

foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val";
if ($key == $this->headerName) {
Expand Down Expand Up @@ -111,6 +147,7 @@ public function callAPI($resourcePath, $method, $queryParams, $postData,
}
// return the result on success, rather than just TRUE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

if (! empty($queryParams)) {
Expand All @@ -130,7 +167,7 @@ public function callAPI($resourcePath, $method, $queryParams, $postData,
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method != self::$GET) {
throw new Exception('Method ' . $method . ' is not recognized.');
throw new APIClientException('Method ' . $method . ' is not recognized.');
}
curl_setopt($curl, CURLOPT_URL, $url);

Expand All @@ -142,20 +179,21 @@ public function callAPI($resourcePath, $method, $queryParams, $postData,
$response_info = curl_getinfo($curl);

// Handle the response
if ($response === false) { // error, likely in the client side
throw new APIClientException("API Error ($url): ".curl_error($curl), 0, $response_info, $response);
if ($response_info['http_code'] == 0) {
throw new APIClientException("TIMEOUT: api call to " . $url .
" took more than 5s to return", 0, $response_info, $response);
} else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
$data = json_decode($response);
if (json_last_error() > 0) { // if response is a string
$data = $response;
}
} else if ($response_info['http_code'] == 401) { // server returns 401
} else if ($response_info['http_code'] == 401) {
throw new APIClientException("Unauthorized API request to " . $url .
": " . serialize($response), 0, $response_info, $response);
} else if ($response_info['http_code'] == 404) { // server returns 404
} else if ($response_info['http_code'] == 404) {
$data = null;
} else {
throw new APIClientException("Can't connect to the API: " . $url .
throw new APIClientException("Can't connect to the api: " . $url .
" response code: " .
$response_info['http_code'], 0, $response_info, $response);
}
Expand Down Expand Up @@ -260,7 +298,6 @@ public static function toString($value) {
* @param string $class class name is passed as a string
* @return object an instance of $class
*/

public static function deserialize($data, $class)
{
if (null === $data) {
Expand Down Expand Up @@ -303,5 +340,37 @@ public static function deserialize($data, $class)
return $deserialized;
}

/*
* return the header 'Accept' based on an array of Accept provided
*
* @param array[string] $accept Array of header
* @return string Accept (e.g. application/json)
*/
public static function selectHeaderAccept($accept) {
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
return NULL;
} elseif (preg_grep("/application\/json/i", $accept)) {
return 'application/json';
} else {
return implode(',', $accept);
}
}

/*
* return the content type based on an array of content-type provided
*
* @param array[string] content_type_array Array fo content-type
* @return string Content-Type (e.g. application/json)
*/
public static function selectHeaderContentType($content_type) {
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
return 'application/json';
} elseif (preg_grep("/application\/json/i", $content_type)) {
return 'application/json';
} else {
return implode(',', $content_type);
}
}

}

Loading