From 171bf969c7550cda408e8b20a96630dd330a17b7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 26 May 2015 23:20:34 +0800 Subject: [PATCH 1/6] add debug switch to configuration --- .../php/SwaggerClient-php/lib/APIClient.php | 20 +++++++++++++++++++ .../SwaggerClient-php/lib/Configuration.php | 3 +++ .../SwaggerClient-php/tests/PetApiTest.php | 3 +++ samples/client/petstore/php/test.php | 3 +++ 4 files changed, 29 insertions(+) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index f7002fba18d..bc243e852cb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -240,10 +240,30 @@ class APIClient { // Set user agent curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + // debugging for curl + if (Configuration::$debug) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); + + curl_setopt($curl, CURLOPT_VERBOSE, 1); + try { + $fp = fopen(Configuration::$debug_file, 'w'); + curl_setopt($curl, CURLOPT_STDERR, $fp); + } catch ( \Exception $e ) { + error_log("Exception in enabling curl debug: ".print_r($e, true), 3, Configuration::$debug_file); + } + } else { + curl_setopt($curl, CURLOPT_VERBOSE, 0); + } + // Make the request $response = curl_exec($curl); $response_info = curl_getinfo($curl); + // debug HTTP response body + if (Configuration::$debug) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($response, true)."\n~END~\n", 3, Configuration::$debug_file); + } + // Handle the response if ($response_info['http_code'] == 0) { throw new APIClientException("TIMEOUT: api call to " . $url . diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 1f91f8d9063..950b31ed587 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -34,6 +34,9 @@ class Configuration { // an instance of APIClient public static $apiClient; + public static $debug = false; // by default debugging is disabled + public static $debug_file = 'php://output'; //output debug log to STDOUT by default + /* * manually initalize API client */ diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 39c5cecd018..85f0c900a6c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -7,6 +7,9 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // add a new pet (id 10005) to ensure the pet object is available for all the tests public static function setUpBeforeClass() { + // enable debugging + //SwaggerClient\Configuration::$debug = true; + // skip initializing the API client as it should be automatic //$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); // new pet diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 41c206ee6b0..22bea9db889 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -6,6 +6,9 @@ require_once('SwaggerClient-php/SwaggerClient.php'); //$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); //$api_client->addDefaultHeader("test1", "value1"); +// to enable logging +//SwaggerClient\Configuration::$debug = true; + $petId = 10005; // ID of pet that needs to be fetched try { //$pet_api = new SwaggerClient\PetAPI($api_client); From 4d1d163a736f4ed22bf33eb0622e0777b27a2d81 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 26 May 2015 23:52:35 +0800 Subject: [PATCH 2/6] update php template to debug curl --- .../src/main/resources/php/APIClient.mustache | 15 +++++++++++++++ .../src/main/resources/php/configuration.mustache | 4 ++++ .../php/SwaggerClient-php/lib/APIClient.php | 7 +------ .../php/SwaggerClient-php/lib/Configuration.php | 1 + samples/client/petstore/php/test.php | 1 + 5 files changed, 22 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 70717056b9e..88954ffad3b 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -235,10 +235,25 @@ class APIClient { // Set user agent curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + // debugging for curl + if (Configuration::$debug) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); + + curl_setopt($curl, CURLOPT_VERBOSE, 1); + curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); + } else { + curl_setopt($curl, CURLOPT_VERBOSE, 0); + } + // Make the request $response = curl_exec($curl); $response_info = curl_getinfo($curl); + // debug HTTP response body + if (Configuration::$debug) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($response, true)."\n~END~\n", 3, Configuration::$debug_file); + } + // Handle the response if ($response_info['http_code'] == 0) { throw new APIClientException("TIMEOUT: api call to " . $url . diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 3eaa8dba1f1..5528e8076f3 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -34,6 +34,10 @@ class Configuration { // an instance of APIClient public static $apiClient; + // debugging + public static $debug = false; // by default debugging is disabled + public static $debug_file = 'php://output'; //output debug log to STDOUT by default + /* * manually initalize API client */ diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index bc243e852cb..3e9119003d7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -245,12 +245,7 @@ class APIClient { error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); curl_setopt($curl, CURLOPT_VERBOSE, 1); - try { - $fp = fopen(Configuration::$debug_file, 'w'); - curl_setopt($curl, CURLOPT_STDERR, $fp); - } catch ( \Exception $e ) { - error_log("Exception in enabling curl debug: ".print_r($e, true), 3, Configuration::$debug_file); - } + curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 950b31ed587..fe4cbc59998 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -34,6 +34,7 @@ class Configuration { // an instance of APIClient public static $apiClient; + // debugging public static $debug = false; // by default debugging is disabled public static $debug_file = 'php://output'; //output debug log to STDOUT by default diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 22bea9db889..4b63c75f472 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -8,6 +8,7 @@ require_once('SwaggerClient-php/SwaggerClient.php'); // to enable logging //SwaggerClient\Configuration::$debug = true; +//SwaggerClient\Configuration::$debug_file = '/var/tmp/php_debug.log'; $petId = 10005; // ID of pet that needs to be fetched try { From e993d0856359b3a6b2ef9bc7d98b60cd4ccd08c3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 28 May 2015 15:06:31 +0800 Subject: [PATCH 3/6] rename APIClient to ApiClient, APIClientException to APIException --- .../codegen/languages/PhpClientCodegen.java | 4 +- .../src/main/resources/php/APIClient.mustache | 12 ++--- ...ception.mustache => ApiException.mustache} | 2 +- .../src/main/resources/php/api.mustache | 4 +- .../main/resources/php/configuration.mustache | 6 +-- .../php/SwaggerClient-php/lib/APIClient.php | 12 ++--- ...PIClientException.php => ApiException.php} | 2 +- .../SwaggerClient-php/lib/Configuration.php | 6 +-- .../php/SwaggerClient-php/lib/PetApi.php | 4 +- .../php/SwaggerClient-php/lib/StoreApi.php | 4 +- .../php/SwaggerClient-php/lib/UserApi.php | 4 +- .../SwaggerClient-php/tests/PetApiTest.php | 44 +++++++++---------- samples/client/petstore/php/test.php | 2 +- 13 files changed, 53 insertions(+), 53 deletions(-) rename modules/swagger-codegen/src/main/resources/php/{APIClientException.mustache => ApiException.mustache} (95%) rename samples/client/petstore/php/SwaggerClient-php/lib/{APIClientException.php => ApiException.php} (95%) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java index 55d358154f8..dd50d623e5f 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java @@ -85,8 +85,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json")); supportingFiles.add(new SupportingFile("configuration.mustache", packagePath + "/lib", "Configuration.php")); - supportingFiles.add(new SupportingFile("APIClient.mustache", packagePath + "/lib", "APIClient.php")); - supportingFiles.add(new SupportingFile("APIClientException.mustache", packagePath + "/lib", "APIClientException.php")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", packagePath + "/lib", "ApiClient.php")); + supportingFiles.add(new SupportingFile("ApiException.mustache", packagePath + "/lib", "ApiException.php")); supportingFiles.add(new SupportingFile("require.mustache", packagePath, invokerPackage + ".php")); } diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 88954ffad3b..cadce36f64d 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -17,7 +17,7 @@ namespace {{invokerPackage}}; -class APIClient { +class ApiClient { public static $PATCH = "PATCH"; public static $POST = "POST"; @@ -173,7 +173,7 @@ class APIClient { * @param array $headerParams parameters to be place in request header * @return mixed */ - public function callAPI($resourcePath, $method, $queryParams, $postData, + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $authSettings) { $headers = array(); @@ -228,7 +228,7 @@ class APIClient { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method != self::$GET) { - throw new APIClientException('Method ' . $method . ' is not recognized.'); + throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -256,7 +256,7 @@ class APIClient { // Handle the response if ($response_info['http_code'] == 0) { - throw new APIClientException("TIMEOUT: api call to " . $url . + throw new ApiException("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); @@ -264,12 +264,12 @@ class APIClient { $data = $response; } } else if ($response_info['http_code'] == 401) { - throw new APIClientException("Unauthorized API request to " . $url . + throw new ApiException("Unauthorized API request to " . $url . ": " . serialize($response), 0, $response_info, $response); } else if ($response_info['http_code'] == 404) { $data = null; } else { - throw new APIClientException("Can't connect to the api: " . $url . + throw new ApiException("Can't connect to the api: " . $url . " response code: " . $response_info['http_code'], 0, $response_info, $response); } diff --git a/modules/swagger-codegen/src/main/resources/php/APIClientException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache similarity index 95% rename from modules/swagger-codegen/src/main/resources/php/APIClientException.mustache rename to modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 3cf74d69288..58a75eabeb1 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClientException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -19,7 +19,7 @@ namespace {{invokerPackage}}; use \Exception; -class APIClientException extends Exception { +class ApiException extends Exception { protected $response, $response_info; public function __construct($message="", $code=0, $response_info=null, $response=null) { diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 1c32eeb01c5..6b4e6e3db16 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -28,7 +28,7 @@ class {{classname}} { function __construct($apiClient = null) { if (null === $apiClient) { if (Configuration::$apiClient === null) { - Configuration::$apiClient = new APIClient(); // create a new API client if not present + Configuration::$apiClient = new ApiClient(); // create a new API client if not present $this->apiClient = Configuration::$apiClient; } else @@ -38,7 +38,7 @@ class {{classname}} { } } - private $apiClient; // instance of the APIClient + private $apiClient; // instance of the ApiClient /** * get the API client diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 5528e8076f3..ea5f813b5e0 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -31,7 +31,7 @@ class Configuration { public static $username = ''; public static $password = ''; - // an instance of APIClient + // an instance of ApiClient public static $apiClient; // debugging @@ -39,11 +39,11 @@ class Configuration { public static $debug_file = 'php://output'; //output debug log to STDOUT by default /* - * manually initalize API client + * manually initalize Api client */ public static function init() { if (self::$apiClient === null) - self::$apiClient = new APIClient(); + self::$apiClient = new ApiClient(); } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 3e9119003d7..5b3289b5a29 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -17,7 +17,7 @@ namespace SwaggerClient; -class APIClient { +class ApiClient { public static $PATCH = "PATCH"; public static $POST = "POST"; @@ -178,7 +178,7 @@ class APIClient { * @param array $headerParams parameters to be place in request header * @return mixed */ - public function callAPI($resourcePath, $method, $queryParams, $postData, + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $authSettings) { $headers = array(); @@ -233,7 +233,7 @@ class APIClient { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method != self::$GET) { - throw new APIClientException('Method ' . $method . ' is not recognized.'); + throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -261,7 +261,7 @@ class APIClient { // Handle the response if ($response_info['http_code'] == 0) { - throw new APIClientException("TIMEOUT: api call to " . $url . + throw new ApiException("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); @@ -269,12 +269,12 @@ class APIClient { $data = $response; } } else if ($response_info['http_code'] == 401) { - throw new APIClientException("Unauthorized API request to " . $url . + throw new ApiException("Unauthorized API request to " . $url . ": " . serialize($response), 0, $response_info, $response); } else if ($response_info['http_code'] == 404) { $data = null; } else { - throw new APIClientException("Can't connect to the api: " . $url . + throw new ApiException("Can't connect to the api: " . $url . " response code: " . $response_info['http_code'], 0, $response_info, $response); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClientException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php similarity index 95% rename from samples/client/petstore/php/SwaggerClient-php/lib/APIClientException.php rename to samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 8d83da0186e..8b8244718ee 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClientException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -19,7 +19,7 @@ namespace SwaggerClient; use \Exception; -class APIClientException extends Exception { +class ApiException extends Exception { protected $response, $response_info; public function __construct($message="", $code=0, $response_info=null, $response=null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index fe4cbc59998..a3412c93eb6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -31,7 +31,7 @@ class Configuration { public static $username = ''; public static $password = ''; - // an instance of APIClient + // an instance of ApiClient public static $apiClient; // debugging @@ -39,11 +39,11 @@ class Configuration { public static $debug_file = 'php://output'; //output debug log to STDOUT by default /* - * manually initalize API client + * manually initalize Api client */ public static function init() { if (self::$apiClient === null) - self::$apiClient = new APIClient(); + self::$apiClient = new ApiClient(); } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 9456f42bc15..338646bfefe 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -27,7 +27,7 @@ class PetApi { function __construct($apiClient = null) { if (null === $apiClient) { if (Configuration::$apiClient === null) { - Configuration::$apiClient = new APIClient(); // create a new API client if not present + Configuration::$apiClient = new ApiClient(); // create a new API client if not present $this->apiClient = Configuration::$apiClient; } else @@ -37,7 +37,7 @@ class PetApi { } } - private $apiClient; // instance of the APIClient + private $apiClient; // instance of the ApiClient /** * get the API client diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 629201965dc..73a060f421d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -27,7 +27,7 @@ class StoreApi { function __construct($apiClient = null) { if (null === $apiClient) { if (Configuration::$apiClient === null) { - Configuration::$apiClient = new APIClient(); // create a new API client if not present + Configuration::$apiClient = new ApiClient(); // create a new API client if not present $this->apiClient = Configuration::$apiClient; } else @@ -37,7 +37,7 @@ class StoreApi { } } - private $apiClient; // instance of the APIClient + private $apiClient; // instance of the ApiClient /** * get the API client diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index 0f4a1bf2dac..1e4f7dbc293 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -27,7 +27,7 @@ class UserApi { function __construct($apiClient = null) { if (null === $apiClient) { if (Configuration::$apiClient === null) { - Configuration::$apiClient = new APIClient(); // create a new API client if not present + Configuration::$apiClient = new ApiClient(); // create a new API client if not present $this->apiClient = Configuration::$apiClient; } else @@ -37,7 +37,7 @@ class UserApi { } } - private $apiClient; // instance of the APIClient + private $apiClient; // instance of the ApiClient /** * get the API client diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 85f0c900a6c..d02b8e74558 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -11,7 +11,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase //SwaggerClient\Configuration::$debug = true; // skip initializing the API client as it should be automatic - //$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + //$api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); // new pet $new_pet_id = 10005; $new_pet = new SwaggerClient\models\Pet; @@ -34,36 +34,36 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $add_response = $pet_api->addPet($new_pet); } - // test static functions defined in APIClient - public function testAPIClient() + // test static functions defined in ApiClient + public function testApiClient() { // test selectHeaderAccept - $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderAccept(array('application/xml','application/json'))); - $this->assertSame(NULL, SwaggerClient\APIClient::selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', SwaggerClient\APIClient::selectHeaderAccept(array('application/yaml','application/xml'))); + $this->assertSame('application/json', SwaggerClient\ApiClient::selectHeaderAccept(array('application/xml','application/json'))); + $this->assertSame(NULL, SwaggerClient\ApiClient::selectHeaderAccept(array())); + $this->assertSame('application/yaml,application/xml', SwaggerClient\ApiClient::selectHeaderAccept(array('application/yaml','application/xml'))); // test selectHeaderContentType - $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array('application/xml','application/json'))); - $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', SwaggerClient\APIClient::selectHeaderContentType(array('application/yaml','application/xml'))); + $this->assertSame('application/json', SwaggerClient\ApiClient::selectHeaderContentType(array('application/xml','application/json'))); + $this->assertSame('application/json', SwaggerClient\ApiClient::selectHeaderContentType(array())); + $this->assertSame('application/yaml,application/xml', SwaggerClient\ApiClient::selectHeaderContentType(array('application/yaml','application/xml'))); // test addDefaultHeader and getDefaultHeader - SwaggerClient\APIClient::addDefaultHeader('test1', 'value1'); - SwaggerClient\APIClient::addDefaultHeader('test2', 200); - $defaultHeader = SwaggerClient\APIClient::getDefaultHeader(); + SwaggerClient\ApiClient::addDefaultHeader('test1', 'value1'); + SwaggerClient\ApiClient::addDefaultHeader('test2', 200); + $defaultHeader = SwaggerClient\ApiClient::getDefaultHeader(); $this->assertSame('value1', $defaultHeader['test1']); $this->assertSame(200, $defaultHeader['test2']); // test deleteDefaultHeader - SwaggerClient\APIClient::deleteDefaultHeader('test2'); - $defaultHeader = SwaggerClient\APIClient::getDefaultHeader(); + SwaggerClient\ApiClient::deleteDefaultHeader('test2'); + $defaultHeader = SwaggerClient\ApiClient::getDefaultHeader(); $this->assertFalse(isset($defaultHeader['test2'])); $pet_api = new SwaggerClient\PetAPI(); $pet_api2 = new SwaggerClient\PetAPI(); - $apiClient3 = new SwaggerClient\APIClient(); + $apiClient3 = new SwaggerClient\ApiClient(); $apiClient3->setUserAgent = 'api client 3'; - $apiClient4 = new SwaggerClient\APIClient(); + $apiClient4 = new SwaggerClient\ApiClient(); $apiClient4->setUserAgent = 'api client 4'; $pet_api3 = new SwaggerClient\PetAPI($apiClient3); @@ -88,7 +88,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetPetById() { // initialize the API client without host - $api_client = new SwaggerClient\APIClient(); + $api_client = new SwaggerClient\ApiClient(); SwaggerClient\Configuration::$apiKey['api_key'] = '111222333444555'; $pet_id = 10005; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); @@ -106,7 +106,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetByStatus() { // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); $pet_api = new SwaggerClient\PetAPI($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); @@ -125,7 +125,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePet() { // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); // create updated pet object @@ -148,7 +148,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithForm() { // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); // update Pet (form) @@ -165,7 +165,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPet() { // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); $new_pet_id = 10001; $new_pet = new SwaggerClient\models\Pet; $new_pet->id = $new_pet_id; @@ -185,7 +185,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUploadFile() { // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); $pet_api = new SwaggerClient\PetAPI($api_client); // upload file $pet_id = 10001; diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 4b63c75f472..0721d7614f2 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -3,7 +3,7 @@ require_once('SwaggerClient-php/SwaggerClient.php'); // initialize the API client -//$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); +//$api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); //$api_client->addDefaultHeader("test1", "value1"); // to enable logging From 412fcf11f9312eb77d65d6a4d8593e584e9bb036 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 28 May 2015 15:19:05 +0800 Subject: [PATCH 4/6] update file separator --- .../codegen/languages/PhpClientCodegen.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java index dd50d623e5f..6fb7a7d70c1 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java @@ -83,11 +83,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("array", "array"); typeMapping.put("list", "array"); - supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json")); - supportingFiles.add(new SupportingFile("configuration.mustache", packagePath + "/lib", "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", packagePath + "/lib", "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", packagePath + "/lib", "ApiException.php")); - supportingFiles.add(new SupportingFile("require.mustache", packagePath, invokerPackage + ".php")); + supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json")); + supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php")); + supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php")); + supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php")); } @Override @@ -97,11 +97,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar); } @Override From 7080983521c957be3144f8d8582e5037989c3bb0 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 2 Jun 2015 17:25:38 +0800 Subject: [PATCH 5/6] return exception instead of null for 404, add properties to api exception class --- ' | 458 ++++++++++++++++++ .../src/main/resources/php/APIClient.mustache | 25 +- .../main/resources/php/ApiException.mustache | 36 +- .../main/resources/php/configuration.mustache | 44 +- .../php/SwaggerClient-php/lib/APIClient.php | 25 +- .../SwaggerClient-php/lib/ApiException.php | 36 +- .../SwaggerClient-php/lib/Configuration.php | 44 +- samples/client/petstore/php/test.php | 9 +- 8 files changed, 606 insertions(+), 71 deletions(-) create mode 100644 ' diff --git a/' b/' new file mode 100644 index 00000000000..fdb14df5153 --- /dev/null +++ b/' @@ -0,0 +1,458 @@ +host = '{{basePath}}'; + } else { + $this->host = $host; + } + } + + /** + * add default header + * + * @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 \InvalidArgumentException('User-agent must be a string.'); + + $this->user_agent= $user_agent; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent($user_agent) { + return $this->user_agent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + */ + public function setTimeout($seconds) { + if (!is_numeric($seconds) || $seconds < 0) + throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + + $this->curl_timeout = $seconds; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getTimeout() { + return $this->curl_timeout; + } + + + /** + * Get API key (with prefix if set) + * @param string key name + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKey) { + if (isset(Configuration::$apiKeyPrefix[$apiKey])) { + return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; + } else if (isset(Configuration::$apiKey[$apiKey])) { + return Configuration::$apiKey[$apiKey]; + } else { + return; + } + } + + /** + * update hearder and query param based on authentication setting + * + * @param array $headerParams header parameters (by ref) + * @param array $queryParams query parameters (by ref) + * @param array $authSettings array of authentication scheme (e.g ['api_key']) + */ + public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) + { + if (count($authSettings) == 0) + return; + + // one endpoint can have more than 1 auth settings + foreach($authSettings as $auth) { + // determine which one to use + switch($auth) { + {{#authMethods}} + 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}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; + {{/authMethods}} + default: + //TODO show warning about security definition not found + } + } + } + + /** + * @param string $resourcePath path to method endpoint + * @param string $method method to call + * @param array $queryParams parameters to be place in query URL + * @param array $postData parameters to be placed in POST body + * @param array $headerParams parameters to be place in request header + * @return mixed + */ + public function callApi($resourcePath, $method, $queryParams, $postData, + $headerParams, $authSettings) { + + $headers = array(); + + # determine authentication setting + $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); + + # construct the http header + if ($headerParams != null) { + # add default header + $headerParams = array_merge((array)self::$default_header, $headerParams); + + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + } + } + + // form data + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { + $postData = http_build_query($postData); + } + else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model + $postData = json_encode($this->sanitizeForSerialization($postData)); + } + + $url = $this->host . $resourcePath; + + $curl = curl_init(); + // set timeout, if needed + if ($this->curl_timeout != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); + } + // return the result on success, rather than just TRUE + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + + if (! empty($queryParams)) { + $url = ($url . '?' . http_build_query($queryParams)); + } + + if ($method == self::$POST) { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PATCH) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PUT) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$DELETE) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method != self::$GET) { + throw new ApiException('Method ' . $method . ' is not recognized.'); + } + curl_setopt($curl, CURLOPT_URL, $url); + + // Set user agent + curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + + // debugging for curl + if (Configuration::$debug) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); + + curl_setopt($curl, CURLOPT_VERBOSE, 1); + curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); + } else { + curl_setopt($curl, CURLOPT_VERBOSE, 0); + } + + // obtain the HTTP response headers + curl_setopt($curl, CURLOPT_HEADER, 1); + + // Make the request + $response = curl_exec($curl); + $response_info = curl_getinfo($curl); + + // debug HTTP response body + if (Configuration::$debug) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($response, true)."\n~END~\n", 3, Configuration::$debug_file); + } + + // Handle the response + if ($response_info['http_code'] == 0) { + throw new ApiException("Api call to $url timed out: ".serialize($response_info), 0, null, null); + } 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) { +// throw new ApiException("Unauthorized API request to " . $url . +// ": " . serialize($response), 0, $response_info, $response); +// } else if ($response_info['http_code'] == 404) { +// $data = null; + } else { + + $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); + $http_header = substr($response, 0, $http_header_size); + $http_body = substr($response, $http_header_size); + + throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], $http_header, $http_body); + } + return $data; + } + + /** + * Build a JSON POST object + */ + protected function sanitizeForSerialization($data) + { + if (is_scalar($data) || null === $data) { + $sanitized = $data; + } else if ($data instanceof \DateTime) { + $sanitized = $data->format(\DateTime::ISO8601); + } else if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = $this->sanitizeForSerialization($value); + } + $sanitized = $data; + } else if (is_object($data)) { + $values = array(); + foreach (array_keys($data::$swaggerTypes) as $property) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); + } + $sanitized = $values; + } else { + $sanitized = (string)$data; + } + + return $sanitized; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public static function toPathValue($value) { + return rawurlencode(self::toString($value)); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * @param object $object an object to be serialized to a string + * @return string the serialized object + */ + public static function toQueryValue($object) { + if (is_array($object)) { + return implode(',', $object); + } else { + return self::toString($object); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value a string which will be part of the header + * @return string the header string + */ + public static function toHeaderValue($value) { + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the form parameter + * @return string the form string + */ + public static function toFormValue($value) { + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the parameter + * @return string the header string + */ + public static function toString($value) { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } + else { + return $value; + } + } + + /** + * Deserialize a JSON string into an object + * + * @param object $object object or primitive to be deserialized + * @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) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { + $inner = substr($class, 4, -1); + $values = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $values[] = array($key => self::deserialize($value, $subClass)); + } + } + $deserialized = $values; + } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { + $subClass = substr($class, 6, -1); + $values = array(); + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool'))) { + settype($data, $class); + $deserialized = $data; + } else { + $class = "{{invokerPackage}}\\models\\".$class; + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + $original_property_name = $instance::$attributeMap[$property]; + if (isset($original_property_name) && isset($data->$original_property_name)) { + $instance->$property = self::deserialize($data->$original_property_name, $type); + } + } + $deserialized = $instance; + } + + 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); + } + } + +} + diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index cadce36f64d..df7f508de69 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -245,33 +245,32 @@ class ApiClient { curl_setopt($curl, CURLOPT_VERBOSE, 0); } + // obtain the HTTP response headers + curl_setopt($curl, CURLOPT_HEADER, 1); + // Make the request $response = curl_exec($curl); + $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); + $http_header = substr($response, 0, $http_header_size); + $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); // debug HTTP response body if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($response, 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, Configuration::$debug_file); } // Handle the response if ($response_info['http_code'] == 0) { - throw new ApiException("TIMEOUT: api call to " . $url . - " took more than 5s to return", 0, $response_info, $response); + throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - $data = json_decode($response); + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string - $data = $response; + $data = $http_body; } - } else if ($response_info['http_code'] == 401) { - throw new ApiException("Unauthorized API request to " . $url . - ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { - $data = null; } else { - throw new ApiException("Can't connect to the api: " . $url . - " response code: " . - $response_info['http_code'], 0, $response_info, $response); + throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], $http_header, $http_body); } return $data; } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 58a75eabeb1..d108c3d2902 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -20,19 +20,39 @@ namespace {{invokerPackage}}; use \Exception; class ApiException extends Exception { - protected $response, $response_info; - public function __construct($message="", $code=0, $response_info=null, $response=null) { + /** + * The HTTP body of the server response. + */ + protected $response_body; + + /** + * The HTTP header of the server response. + */ + protected $response_headers; + + public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { parent::__construct($message, $code); - $this->response_info = $response_info; - $this->response = $response; + $this->response_headers = $responseHeaders; + $this->response_body = $responseBody; } - public function getResponse() { - return $this->response; + /** + * Get the HTTP response header + * + * @return string HTTP response header + */ + public function getResponseHeaders() { + return $this->response_headers; } - public function getResponseInfo() { - return $this->response_info; + /** + * Get the HTTP response body + * + * @return string HTTP response body + */ + public function getResponseBody() { + return $this->response_body; } + } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index ea5f813b5e0..7099a2cb234 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -19,28 +19,44 @@ namespace {{invokerPackage}}; class Configuration { - public static $PATCH = "PATCH"; - public static $POST = "POST"; - public static $GET = "GET"; - public static $PUT = "PUT"; - public static $DELETE = "DELETE"; - - // authentication setting + /** + * Associate array to store API key(s) + */ public static $apiKey = array(); + + /** + * Associate array to store API prefix (e.g. Bearer) + */ public static $apiKeyPrefix = array(); + + /** + * Username for HTTP basic authentication + */ public static $username = ''; + + /** + * Password for HTTP basic authentication + */ public static $password = ''; - // an instance of ApiClient + /** + * The default instance of ApiClient + */ public static $apiClient; - // debugging - public static $debug = false; // by default debugging is disabled - public static $debug_file = 'php://output'; //output debug log to STDOUT by default + /** + * Debug switch (default set to false) + */ + public static $debug = false; - /* - * manually initalize Api client - */ + /** + * Debug file location (log to STDOUT by default) + */ + public static $debug_file = 'php://output'; + + /* + * manually initalize ApiClient + */ public static function init() { if (self::$apiClient === null) self::$apiClient = new ApiClient(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 5b3289b5a29..11b06862875 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -250,33 +250,32 @@ class ApiClient { curl_setopt($curl, CURLOPT_VERBOSE, 0); } + // obtain the HTTP response headers + curl_setopt($curl, CURLOPT_HEADER, 1); + // Make the request $response = curl_exec($curl); + $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); + $http_header = substr($response, 0, $http_header_size); + $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); // debug HTTP response body if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($response, 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, Configuration::$debug_file); } // Handle the response if ($response_info['http_code'] == 0) { - throw new ApiException("TIMEOUT: api call to " . $url . - " took more than 5s to return", 0, $response_info, $response); + throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - $data = json_decode($response); + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string - $data = $response; + $data = $http_body; } - } else if ($response_info['http_code'] == 401) { - throw new ApiException("Unauthorized API request to " . $url . - ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { - $data = null; } else { - throw new ApiException("Can't connect to the api: " . $url . - " response code: " . - $response_info['http_code'], 0, $response_info, $response); + throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], $http_header, $http_body); } return $data; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 8b8244718ee..40158cf76e6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -20,19 +20,39 @@ namespace SwaggerClient; use \Exception; class ApiException extends Exception { - protected $response, $response_info; - public function __construct($message="", $code=0, $response_info=null, $response=null) { + /** + * The HTTP body of the server response. + */ + protected $response_body; + + /** + * The HTTP header of the server response. + */ + protected $response_headers; + + public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { parent::__construct($message, $code); - $this->response_info = $response_info; - $this->response = $response; + $this->response_headers = $responseHeaders; + $this->response_body = $responseBody; } - public function getResponse() { - return $this->response; + /** + * Get the HTTP response header + * + * @return string HTTP response header + */ + public function getResponseHeaders() { + return $this->response_headers; } - public function getResponseInfo() { - return $this->response_info; + /** + * Get the HTTP response body + * + * @return string HTTP response body + */ + public function getResponseBody() { + return $this->response_body; } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index a3412c93eb6..8a0dc734a0d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -19,28 +19,44 @@ namespace SwaggerClient; class Configuration { - public static $PATCH = "PATCH"; - public static $POST = "POST"; - public static $GET = "GET"; - public static $PUT = "PUT"; - public static $DELETE = "DELETE"; - - // authentication setting + /** + * Associate array to store API key(s) + */ public static $apiKey = array(); + + /** + * Associate array to store API prefix (e.g. Bearer) + */ public static $apiKeyPrefix = array(); + + /** + * Username for HTTP basic authentication + */ public static $username = ''; + + /** + * Password for HTTP basic authentication + */ public static $password = ''; - // an instance of ApiClient + /** + * The default instance of ApiClient + */ public static $apiClient; - // debugging - public static $debug = false; // by default debugging is disabled - public static $debug_file = 'php://output'; //output debug log to STDOUT by default + /** + * Debug switch (default set to false) + */ + public static $debug = false; - /* - * manually initalize Api client - */ + /** + * Debug file location (log to STDOUT by default) + */ + public static $debug_file = 'php://output'; + + /* + * manually initalize ApiClient + */ public static function init() { if (self::$apiClient === null) self::$apiClient = new ApiClient(); diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 0721d7614f2..a358ea5df45 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -17,8 +17,15 @@ try { // return Pet (model) $response = $pet_api->getPetById($petId); var_dump($response); -} catch (Exception $e) { + + // test upload file (exception) + $upload_response = $pet_api->uploadFile($petId, "test meta", NULL); + +} catch (SwaggerClient\ApiException $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; + echo 'HTTP response headers: ', $e->getResponseHeaders(), "\n"; + echo 'HTTP response body: ', $e->getResponseBody(), "\n"; + echo 'HTTP status code: ', $e->getCode(), "\n"; } ?> From 2d6a7092e371f609ed6c3feaaa86201504f7ba8d Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 2 Jun 2015 20:43:11 +0800 Subject: [PATCH 6/6] removed unused file --- ' | 458 -------------------------------------------------------------- 1 file changed, 458 deletions(-) delete mode 100644 ' diff --git a/' b/' deleted file mode 100644 index fdb14df5153..00000000000 --- a/' +++ /dev/null @@ -1,458 +0,0 @@ -host = '{{basePath}}'; - } else { - $this->host = $host; - } - } - - /** - * add default header - * - * @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 \InvalidArgumentException('User-agent must be a string.'); - - $this->user_agent= $user_agent; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent($user_agent) { - return $this->user_agent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ - public function setTimeout($seconds) { - if (!is_numeric($seconds) || $seconds < 0) - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - - $this->curl_timeout = $seconds; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getTimeout() { - return $this->curl_timeout; - } - - - /** - * Get API key (with prefix if set) - * @param string key name - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKey) { - if (isset(Configuration::$apiKeyPrefix[$apiKey])) { - return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else if (isset(Configuration::$apiKey[$apiKey])) { - return Configuration::$apiKey[$apiKey]; - } else { - return; - } - } - - /** - * update hearder and query param based on authentication setting - * - * @param array $headerParams header parameters (by ref) - * @param array $queryParams query parameters (by ref) - * @param array $authSettings array of authentication scheme (e.g ['api_key']) - */ - public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) - { - if (count($authSettings) == 0) - return; - - // one endpoint can have more than 1 auth settings - foreach($authSettings as $auth) { - // determine which one to use - switch($auth) { - {{#authMethods}} - 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}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} - break; - {{/authMethods}} - default: - //TODO show warning about security definition not found - } - } - } - - /** - * @param string $resourcePath path to method endpoint - * @param string $method method to call - * @param array $queryParams parameters to be place in query URL - * @param array $postData parameters to be placed in POST body - * @param array $headerParams parameters to be place in request header - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, - $headerParams, $authSettings) { - - $headers = array(); - - # determine authentication setting - $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - - # construct the http header - if ($headerParams != null) { - # add default header - $headerParams = array_merge((array)self::$default_header, $headerParams); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } - } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { - $postData = http_build_query($postData); - } - else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->sanitizeForSerialization($postData)); - } - - $url = $this->host . $resourcePath; - - $curl = curl_init(); - // set timeout, if needed - if ($this->curl_timeout != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); - } - // return the result on success, rather than just TRUE - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } - - if ($method == self::$POST) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { - throw new ApiException('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); - - // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); - - // debugging for curl - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); - } else { - curl_setopt($curl, CURLOPT_VERBOSE, 0); - } - - // obtain the HTTP response headers - curl_setopt($curl, CURLOPT_HEADER, 1); - - // Make the request - $response = curl_exec($curl); - $response_info = curl_getinfo($curl); - - // debug HTTP response body - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($response, true)."\n~END~\n", 3, Configuration::$debug_file); - } - - // Handle the response - if ($response_info['http_code'] == 0) { - throw new ApiException("Api call to $url timed out: ".serialize($response_info), 0, null, null); - } 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) { -// throw new ApiException("Unauthorized API request to " . $url . -// ": " . serialize($response), 0, $response_info, $response); -// } else if ($response_info['http_code'] == 404) { -// $data = null; - } else { - - $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = substr($response, 0, $http_header_size); - $http_body = substr($response, $http_header_size); - - throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body); - } - return $data; - } - - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - - return $sanitized; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public static function toPathValue($value) { - return rawurlencode(self::toString($value)); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public static function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return self::toString($object); - } - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the header. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value a string which will be part of the header - * @return string the header string - */ - public static function toHeaderValue($value) { - return self::toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the http body (form parameter). If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the form parameter - * @return string the form string - */ - public static function toFormValue($value) { - return self::toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the parameter. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the parameter - * @return string the header string - */ - public static function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @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) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { - $inner = substr($class, 4, -1); - $values = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $values[] = array($key => self::deserialize($value, $subClass)); - } - } - $deserialized = $values; - } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); - $values = array(); - foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool'))) { - settype($data, $class); - $deserialized = $data; - } else { - $class = "{{invokerPackage}}\\models\\".$class; - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name) && isset($data->$original_property_name)) { - $instance->$property = self::deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } - - 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); - } - } - -} -