Merge pull request #794 from wing328/php_debug_switch

[PHP] add debug switch
This commit is contained in:
Tony Tam 2015-06-05 00:40:32 -07:00
commit 05700a6799
13 changed files with 233 additions and 111 deletions

View File

@ -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("APIClientException.mustache", packagePath + "/lib", "APIClientException.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

View File

@ -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,35 +228,49 @@ 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);
// 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);
$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($http_body, 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 .
" 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 APIClientException("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 .
" 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;
}

View File

@ -19,20 +19,40 @@ namespace {{invokerPackage}};
use \Exception;
class APIClientException extends Exception {
protected $response, $response_info;
class ApiException extends Exception {
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;
}
}

View File

@ -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

View File

@ -19,27 +19,47 @@ 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;
/**
* Debug switch (default set to false)
*/
public static $debug = false;
/**
* Debug file location (log to STDOUT by default)
*/
public static $debug_file = 'php://output';
/*
* manually initalize API client
* manually initalize ApiClient
*/
public static function init() {
if (self::$apiClient === null)
self::$apiClient = new APIClient();
self::$apiClient = new ApiClient();
}
}

View File

@ -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,35 +233,49 @@ 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);
// 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);
$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($http_body, 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 .
" 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 APIClientException("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 .
" 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;
}

View File

@ -19,20 +19,40 @@ namespace SwaggerClient;
use \Exception;
class APIClientException extends Exception {
protected $response, $response_info;
class ApiException extends Exception {
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;
}
}

View File

@ -19,27 +19,47 @@ 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;
/**
* Debug switch (default set to false)
*/
public static $debug = false;
/**
* Debug file location (log to STDOUT by default)
*/
public static $debug_file = 'php://output';
/*
* manually initalize API client
* manually initalize ApiClient
*/
public static function init() {
if (self::$apiClient === null)
self::$apiClient = new APIClient();
self::$apiClient = new ApiClient();
}
}

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -7,8 +7,11 @@ 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');
//$api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2');
// new pet
$new_pet_id = 10005;
$new_pet = new SwaggerClient\models\Pet;
@ -31,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);
@ -85,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);
@ -103,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");
@ -122,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
@ -145,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)
@ -162,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;
@ -182,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;

View File

@ -3,9 +3,13 @@
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
//SwaggerClient\Configuration::$debug = true;
//SwaggerClient\Configuration::$debug_file = '/var/tmp/php_debug.log';
$petId = 10005; // ID of pet that needs to be fetched
try {
//$pet_api = new SwaggerClient\PetAPI($api_client);
@ -13,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";
}
?>