remove static fields in Configuration and make variable case more consistent

This commit is contained in:
nmonterroso 2015-06-22 08:28:22 -07:00
parent caa1b7f411
commit b9ca19168a
4 changed files with 221 additions and 86 deletions

View File

@ -29,40 +29,46 @@ class ApiClient {
public static $PUT = "PUT"; public static $PUT = "PUT";
public static $DELETE = "DELETE"; public static $DELETE = "DELETE";
private static $default_header = array(); protected $defaultHeaders = array();
/* /*
* @var string timeout (second) of the HTTP request, by default set to 0, no timeout * @var string timeout (second) of the HTTP request, by default set to 0, no timeout
*/ */
protected $curl_timeout = 0; protected $curlTimeout = 0;
/* /*
* @var string user agent of the HTTP request, set to "PHP-Swagger" by default * @var string user agent of the HTTP request, set to "PHP-Swagger" by default
*/ */
protected $user_agent = "PHP-Swagger"; protected $userAgent = "PHP-Swagger";
/** /**
* @param string $host Base url of the API server (optional) * @var ApiConfiguration
*/ */
function __construct($host = null) { protected $config;
if ($host === null) {
$this->host = '{{basePath}}'; /**
} else { * @param ApiConfiguration $config config for this ApiClient
$this->host = $host; */
function __construct(ApiConfiguration $config = null) {
if ($config == null) {
$config = ApiConfiguration::getDefaultConfiguration();
} }
$this->config = $config;
} }
/** /**
* add default header * add default header
* *
* @param string $header_name header name (e.g. Token) * @param string $headerName header name (e.g. Token)
* @param string $header_value header value (e.g. 1z8wp3) * @param string $headerValue header value (e.g. 1z8wp3)
*/ */
public function addDefaultHeader($header_name, $header_value) { public function addDefaultHeader($headerName, $headerValue) {
if (!is_string($header_name)) if (!is_string($headerName)) {
throw new \InvalidArgumentException('Header name must be a string.'); throw new \InvalidArgumentException('Header name must be a string.');
}
self::$default_header[$header_name] = $header_value; $this->defaultHeaders[$headerName] = $headerValue;
} }
/** /**
@ -70,29 +76,29 @@ class ApiClient {
* *
* @return array default header * @return array default header
*/ */
public function getDefaultHeader() { public function getDefaultHeaders() {
return self::$default_header; return $this->defaultHeaders;
} }
/** /**
* delete the default header based on header name * delete the default header based on header name
* *
* @param string $header_name header name (e.g. Token) * @param string $headerName header name (e.g. Token)
*/ */
public function deleteDefaultHeader($header_name) { public function deleteDefaultHeader($headerName) {
unset(self::$default_header[$header_name]); unset($this->defaultHeaders[$headerName]);
} }
/** /**
* set the user agent of the api client * set the user agent of the api client
* *
* @param string $user_agent the user agent of the api client * @param string $userAgent the user agent of the api client
*/ */
public function setUserAgent($user_agent) { public function setUserAgent($userAgent) {
if (!is_string($user_agent)) if (!is_string($userAgent))
throw new \InvalidArgumentException('User-agent must be a string.'); throw new \InvalidArgumentException('User-agent must be a string.');
$this->user_agent= $user_agent; $this->userAgent = $userAgent;
} }
/** /**
@ -100,8 +106,8 @@ class ApiClient {
* *
* @return string user agent * @return string user agent
*/ */
public function getUserAgent($user_agent) { public function getUserAgent() {
return $this->user_agent; return $this->userAgent;
} }
/** /**
@ -113,7 +119,7 @@ class ApiClient {
if (!is_numeric($seconds) || $seconds < 0) if (!is_numeric($seconds) || $seconds < 0)
throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.');
$this->curl_timeout = $seconds; $this->curlTimeout = $seconds;
} }
/** /**
@ -122,27 +128,34 @@ class ApiClient {
* @return string HTTP timeout value * @return string HTTP timeout value
*/ */
public function getTimeout() { public function getTimeout() {
return $this->curl_timeout; return $this->curlTimeout;
} }
/** /**
* Get API key (with prefix if set) * Get API key (with prefix if set)
* @param string key name * @param string $apiKey name of apikey
* @return string API key with the prefix * @return string API key with the prefix
*/ */
public function getApiKeyWithPrefix($apiKey) { public function getApiKeyWithPrefix($apiKey) {
if (isset(Configuration::$apiKeyPrefix[$apiKey])) { $prefix = $this->config->getApiKeyPrefix($apiKey);
return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; $apiKey = $this->config->getApiKey($apiKey);
} else if (isset(Configuration::$apiKey[$apiKey])) {
return Configuration::$apiKey[$apiKey]; if (!isset($apiKey)) {
} else { return null;
return;
} }
if (isset($prefix)) {
$keyWithPrefix = $prefix." ".$apiKey;
} else {
$keyWithPrefix = $apiKey;
}
return $keyWithPrefix;
} }
/** /**
* update hearder and query param based on authentication setting * update header and query param based on authentication setting
* *
* @param array $headerParams header parameters (by ref) * @param array $headerParams header parameters (by ref)
* @param array $queryParams query parameters (by ref) * @param array $queryParams query parameters (by ref)
@ -159,7 +172,7 @@ class ApiClient {
switch($auth) { switch($auth) {
{{#authMethods}} {{#authMethods}}
case '{{name}}': case '{{name}}':
{{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode(Configuration::$username.":".Configuration::$password);{{/isBasic}} {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->config->getUsername().":".$this->config->getPassword());{{/isBasic}}
{{#isOAuth}}//TODO support oauth{{/isOAuth}} {{#isOAuth}}//TODO support oauth{{/isOAuth}}
break; break;
{{/authMethods}} {{/authMethods}}
@ -175,6 +188,8 @@ class ApiClient {
* @param array $queryParams parameters to be place in query URL * @param array $queryParams parameters to be place in query URL
* @param array $postData parameters to be placed in POST body * @param array $postData parameters to be placed in POST body
* @param array $headerParams parameters to be place in request header * @param array $headerParams parameters to be place in request header
* @param array $authSettings parameters for authentication
* @throws \{{invokerNamespace}}\ApiException on a non 2xx response
* @return mixed * @return mixed
*/ */
public function callApi($resourcePath, $method, $queryParams, $postData, public function callApi($resourcePath, $method, $queryParams, $postData,
@ -186,7 +201,7 @@ class ApiClient {
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings); $this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
# construct the http header # construct the http header
$headerParams = array_merge((array)self::$default_header, (array)$headerParams); $headerParams = array_merge((array)$this->defaultHeaders, (array)$headerParams);
foreach ($headerParams as $key => $val) { foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val"; $headers[] = "$key: $val";
@ -200,12 +215,12 @@ class ApiClient {
$postData = json_encode($this->sanitizeForSerialization($postData)); $postData = json_encode($this->sanitizeForSerialization($postData));
} }
$url = $this->host . $resourcePath; $url = $this->config->getHost() . $resourcePath;
$curl = curl_init(); $curl = curl_init();
// set timeout, if needed // set timeout, if needed
if ($this->curl_timeout != 0) { if ($this->curlTimeout != 0) {
curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); curl_setopt($curl, CURLOPT_TIMEOUT, $this->curlTimeout);
} }
// return the result on success, rather than just TRUE // return the result on success, rather than just TRUE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
@ -234,14 +249,14 @@ class ApiClient {
curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_URL, $url);
// Set user agent // Set user agent
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); curl_setopt($curl, CURLOPT_USERAGENT, $this->userAgent);
// debugging for curl // debugging for curl
if (Configuration::$debug) { if ($this->config->getDebug()) {
error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile());
curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a'));
} else { } else {
curl_setopt($curl, CURLOPT_VERBOSE, 0); curl_setopt($curl, CURLOPT_VERBOSE, 0);
} }
@ -257,8 +272,8 @@ class ApiClient {
$response_info = curl_getinfo($curl); $response_info = curl_getinfo($curl);
// debug HTTP response body // debug HTTP response body
if (Configuration::$debug) { if ($this->config->getDebug()) {
error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile());
} }
// Handle the response // Handle the response
@ -278,9 +293,10 @@ class ApiClient {
/** /**
* Build a JSON POST object * Build a JSON POST object
* @param mixed $data the data to serialize
* @return string serialized form of $data
*/ */
protected function sanitizeForSerialization($data) protected function sanitizeForSerialization($data) {
{
if (is_scalar($data) || null === $data) { if (is_scalar($data) || null === $data) {
$sanitized = $data; $sanitized = $data;
} else if ($data instanceof \DateTime) { } else if ($data instanceof \DateTime) {
@ -372,7 +388,7 @@ class ApiClient {
/** /**
* Deserialize a JSON string into an object * Deserialize a JSON string into an object
* *
* @param object $object object or primitive to be deserialized * @param object $data object or primitive to be deserialized
* @param string $class class name is passed as a string * @param string $class class name is passed as a string
* @return object an instance of $class * @return object an instance of $class
*/ */
@ -419,7 +435,7 @@ class ApiClient {
/* /*
* return the header 'Accept' based on an array of Accept provided * return the header 'Accept' based on an array of Accept provided
* *
* @param array[string] $accept Array of header * @param string[] $accept Array of header
* @return string Accept (e.g. application/json) * @return string Accept (e.g. application/json)
*/ */
public static function selectHeaderAccept($accept) { public static function selectHeaderAccept($accept) {

View File

@ -37,16 +37,11 @@ class {{classname}} {
private $apiClient; private $apiClient;
function __construct($apiClient = null) { function __construct($apiClient = null) {
if (null === $apiClient) { if ($apiClient == null) {
if (Configuration::$apiClient === null) { $apiClient = new ApiClient();
Configuration::$apiClient = new ApiClient(); // create a new API client if not present
$this->apiClient = Configuration::$apiClient;
}
else
$this->apiClient = Configuration::$apiClient; // use the default one
} else {
$this->apiClient = $apiClient; // use the one provided by the user
} }
$this->apiClient = $apiClient;
} }
/** /**
@ -88,28 +83,29 @@ class {{classname}} {
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); $_header_accept = ApiClient::selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}));
{{#queryParams}}// query params {{#queryParams}}// query params
if(${{paramName}} !== null) { if(${{paramName}} !== null) {
$queryParams['{{baseName}}'] = $this->apiClient->toQueryValue(${{paramName}}); $queryParams['{{baseName}}'] = ApiClient::toQueryValue(${{paramName}});
}{{/queryParams}} }{{/queryParams}}
{{#headerParams}}// header params {{#headerParams}}// header params
if(${{paramName}} !== null) { if(${{paramName}} !== null) {
$headerParams['{{baseName}}'] = $this->apiClient->toHeaderValue(${{paramName}}); $headerParams['{{baseName}}'] = ApiClient::toHeaderValue(${{paramName}});
}{{/headerParams}} }{{/headerParams}}
{{#pathParams}}// path params {{#pathParams}}// path params
if(${{paramName}} !== null) { if(${{paramName}} !== null) {
$resourcePath = str_replace("{" . "{{baseName}}" . "}", $resourcePath = str_replace("{" . "{{baseName}}" . "}",
$this->apiClient->toPathValue(${{paramName}}), $resourcePath); ApiClient::toPathValue(${{paramName}}),
$resourcePath);
}{{/pathParams}} }{{/pathParams}}
{{#formParams}}// form params {{#formParams}}// form params
if (${{paramName}} !== null) { if (${{paramName}} !== null) {
$formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->toFormValue(${{paramName}}); $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}ApiClient::toFormValue(${{paramName}});
}{{/formParams}} }{{/formParams}}
{{#bodyParams}}// body params {{#bodyParams}}// body params
$_tempBody = null; $_tempBody = null;
@ -138,7 +134,7 @@ class {{classname}} {
switch ($e->getCode()) { {{#responses}}{{#dataType}} switch ($e->getCode()) { {{#responses}}{{#dataType}}
case {{code}}: case {{code}}:
$data = $this->apiClient->deserialize($e->getResponseBody(), '{{dataType}}'); $data = ApiClient::deserialize($e->getResponseBody(), '{{dataType}}');
$throw = new ApiException("{{message}}", $e->getCode(), $e->getResponseHeaders(), $data); $throw = new ApiException("{{message}}", $e->getCode(), $e->getResponseHeaders(), $data);
break;{{/dataType}}{{/responses}} break;{{/dataType}}{{/responses}}
} }
@ -150,7 +146,7 @@ class {{classname}} {
return null; return null;
} }
$responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); $responseObject = ApiClient::deserialize($response,'{{returnType}}');
return $responseObject; return $responseObject;
{{/returnType}} {{/returnType}}
} }

View File

@ -17,50 +17,173 @@
namespace {{invokerNamespace}}; namespace {{invokerNamespace}};
class Configuration { class ApiConfiguration {
private static $defaultConfiguration = null;
/**
* The host (from basePath)
*/
protected $host = '{{basePath}}';
/** /**
* Associate array to store API key(s) * Associate array to store API key(s)
*/ */
public static $apiKey = array(); protected $apiKeys = array();
/** /**
* Associate array to store API prefix (e.g. Bearer) * Associate array to store API prefix (e.g. Bearer)
*/ */
public static $apiKeyPrefix = array(); protected $apiKeyPrefixes = array();
/** /**
* Username for HTTP basic authentication * Username for HTTP basic authentication
*/ */
public static $username = ''; protected $username = '';
/** /**
* Password for HTTP basic authentication * Password for HTTP basic authentication
*/ */
public static $password = ''; protected $password = '';
/**
* The default instance of ApiClient
*/
public static $apiClient;
/** /**
* Debug switch (default set to false) * Debug switch (default set to false)
*/ */
public static $debug = false; protected $debug = false;
/** /**
* Debug file location (log to STDOUT by default) * Debug file location (log to STDOUT by default)
*/ */
public static $debug_file = 'php://output'; protected $debugFile = 'php://output';
/* /**
* manually initalize ApiClient * @param string $host
* @return ApiConfiguration
*/ */
public static function init() { public function setHost($host) {
if (self::$apiClient === null) $this->host = $host;
self::$apiClient = new ApiClient(); return $this;
} }
/**
* @return string
*/
public function getHost() {
return $this->host;
} }
/**
* @param string $key
* @param string $value
* @return ApiConfiguration
*/
public function setApiKey($key, $value) {
$this->apiKeys[$key] = $value;
return $this;
}
/**
* @param $key
* @return string
*/
public function getApiKey($key) {
return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null;
}
/**
* @param string $key
* @param string $value
* @return ApiConfiguration
*/
public function setApiKeyPrefix($key, $value) {
$this->apiKeyPrefixes[$key] = $value;
return $this;
}
/**
* @param $key
* @return string
*/
public function getApiKeyPrefix($key) {
return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null;
}
/**
* @param string $username
* @return ApiConfiguration
*/
public function setUsername($username) {
$this->username = $username;
return $this;
}
/**
* @return string
*/
public function getUsername() {
return $this->username;
}
/**
* @param string $password
* @return ApiConfiguration
*/
public function setPassword($password) {
$this->password = $password;
return $this;
}
/**
* @return string
*/
public function getPassword() {
return $this->password;
}
/**
* @param bool $debug
* @return ApiConfiguration
*/
public function setDebug($debug) {
$this->debug = $debug;
return $this;
}
/**
* @return bool
*/
public function getDebug() {
return $this->debug;
}
/**
* @param string $debugFile
* @return ApiConfiguration
*/
public function setDebugFile($debugFile) {
$this->debugFile = $debugFile;
return $this;
}
/**
* @return string
*/
public function getDebugFile() {
return $this->debugFile;
}
/**
* @return ApiConfiguration
*/
public static function getDefaultConfiguration() {
if (self::$defaultConfiguration == null) {
return new ApiConfiguration();
}
return self::$defaultConfiguration;
}
public static function setDefaultConfiguration(ApiConfiguration $config) {
self::$defaultConfiguration = $config;
}
}

View File

@ -44,7 +44,7 @@ class {{classname}} implements ArrayAccess {
* {{{description}}}{{/description}} * {{{description}}}{{/description}}
* @var {{{datatype}}} * @var {{{datatype}}}
*/ */
public ${{name}}; protected ${{name}};
{{/vars}} {{/vars}}
public function __construct(array $data = null) { public function __construct(array $data = null) {
if ($data != null) { if ($data != null) {