From 6e396f15394f6d29642a3056ca3dcece53c69240 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Wed, 15 Mar 2017 10:18:52 +0000 Subject: [PATCH 01/37] reimplemented basic requests with httpplug --- .../src/main/resources/php/api.mustache | 131 ++-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 250 +++--- .../php/SwaggerClient-php/lib/Api/PetApi.php | 456 +++++++---- .../php/SwaggerClient-php/lib/Api/PetApi_.php | 721 ++++++++++++++++++ .../SwaggerClient-php/lib/Api/StoreApi.php | 231 ++++-- .../php/SwaggerClient-php/lib/Api/UserApi.php | 436 +++++++---- .../php/SwaggerClient-php/lib/ApiClient2.php | 163 ++++ .../SwaggerClient-php/lib/HeaderSelector.php | 96 +++ .../tests/HeaderSelectorTest.php | 41 + .../SwaggerClient-php/tests/PetApiTest.php | 199 ++--- .../SwaggerClient-php/tests/StoreApiTest.php | 32 +- 11 files changed, 2084 insertions(+), 672 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 6619f8da8c1..ee106f75610 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -18,10 +18,13 @@ namespace {{apiPackage}}; -use \{{invokerPackage}}\ApiClient; -use \{{invokerPackage}}\ApiException; -use \{{invokerPackage}}\Configuration; -use \{{invokerPackage}}\ObjectSerializer; +use GuzzleHttp\Psr7\Request; +use Http\Client\Exception; +use Http\Client\HttpClient; +use {{invokerPackage}}\ApiException; +use {{invokerPackage}}\HeaderSelector; +use {{invokerPackage}}\Model\Pet; +use {{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment @@ -34,50 +37,26 @@ use \{{invokerPackage}}\ObjectSerializer; {{#operations}}class {{classname}} { /** - * API Client - * - * @var \{{invokerPackage}}\ApiClient instance of the ApiClient + * @var HttpClient */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use + * @var ObjectSerializer */ - public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } - - $this->apiClient = $apiClient; - } + protected $serializer; /** - * Get API client - * - * @return \{{invokerPackage}}\ApiClient get the API client + * @param HttpClient $client */ - public function getApiClient() + public function __construct(HttpClient $client, HeaderSelector $selector = null) { - return $this->apiClient; + $this->client = $client; + $this->serializer = new ObjectSerializer(); + $this->headerSelector = $selector ?: new HeaderSelector(); } - /** - * Set the API client - * - * @param \{{invokerPackage}}\ApiClient $apiClient set the API client - * - * @return {{classname}} - */ - public function setApiClient(\{{invokerPackage}}\ApiClient $apiClient) - { - $this->apiClient = $apiClient; - return $this; - } - {{#operation}} - +{{#operation}} /** * Operation {{{operationId}}} * @@ -96,7 +75,7 @@ use \{{invokerPackage}}\ObjectSerializer; public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { list($response) = $this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - return $response; + {{#returnType}}return $response;{{/returnType}} } /** @@ -112,6 +91,7 @@ use \{{invokerPackage}}\ObjectSerializer; * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @throws \{{invokerPackage}}\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) @@ -125,55 +105,55 @@ use \{{invokerPackage}}\ObjectSerializer; {{/required}} {{#hasValidation}} {{#maxLength}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(strlen(${{paramName}}) > {{maxLength}})) { + if ({{^required}}${{paramName}} !== null && {{/required}}strlen(${{paramName}}) > {{maxLength}}) { throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); } {{/maxLength}} {{#minLength}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(strlen(${{paramName}}) < {{minLength}})) { + if ({{^required}}${{paramName}} !== null && {{/required}}strlen(${{paramName}}) < {{minLength}}) { throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); } {{/minLength}} {{#maximum}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { + if ({{^required}}${{paramName}} !== null && {{/required}}${{paramName}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); } {{/maximum}} {{#minimum}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(${{paramName}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { + if ({{^required}}${{paramName}} !== null && {{/required}}${{paramName}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); } {{/minimum}} {{#pattern}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) { + if ({{^required}}${{paramName}} !== null && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}}) { throw new \InvalidArgumentException("invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); } {{/pattern}} {{#maxItems}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(count(${{paramName}}) > {{maxItems}})) { + if ({{^required}}${{paramName}} !== null && {{/required}}count(${{paramName}}) > {{maxItems}}) { throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); } {{/maxItems}} {{#minItems}} - if ({{^required}}!is_null(${{paramName}}) && {{/required}}(count(${{paramName}}) < {{minItems}})) { + if ({{^required}}${{paramName}} !== null && {{/required}}count(${{paramName}}) < {{minItems}}) { throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); } {{/minItems}} {{/hasValidation}} {{/allParams}} - // parse inputs - $resourcePath = "{{{path}}}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('{{{path}}}', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept([{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}], + [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + ); + +/** {{#queryParams}} // query params {{#collectionFormat}} @@ -196,6 +176,8 @@ use \{{invokerPackage}}\ObjectSerializer; $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); } {{/headerParams}} + + */ {{#pathParams}} // path params {{#collectionFormat}} @@ -204,16 +186,14 @@ use \{{invokerPackage}}\ObjectSerializer; } {{/collectionFormat}} if (${{paramName}} !== null) { - $resourcePath = str_replace( - "{" . "{{baseName}}" . "}", - $this->apiClient->getSerializer()->toPathValue(${{paramName}}), - $resourcePath - ); + $resourcePath = str_replace('{' . '{{baseName}}' . '}', $this->serializer->toPathValue(${{paramName}}), $resourcePath); } {{/pathParams}} + {{#formParams}} // form params if (${{paramName}} !== null) { + /** {{#isFile}} // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax // See: https://wiki.php.net/rfc/curl-file-upload @@ -223,6 +203,7 @@ use \{{invokerPackage}}\ObjectSerializer; $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); } {{/isFile}} + */ {{^isFile}} $formParams['{{baseName}}'] = $this->apiClient->getSerializer()->toFormValue(${{paramName}}); {{/isFile}} @@ -241,6 +222,7 @@ use \{{invokerPackage}}\ObjectSerializer; } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** {{#authMethods}} {{#isApiKey}} // this endpoint requires API key authentication @@ -262,7 +244,31 @@ use \{{invokerPackage}}\ObjectSerializer; } {{/isOAuth}} {{/authMethods}} - // make the API Call +*/ + + try { + $request = new Request( + '{{httpMethod}}', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + {{#returnType}} + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '{{returnType}}', []), + $response->getStatusCode(), + [] + ]; + {{/returnType}} + {{^returnType}} + return [null, $response->getStatusCode(), []]; + {{/returnType}} + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -299,6 +305,7 @@ use \{{invokerPackage}}\ObjectSerializer; throw $e; } +*/ } {{/operation}} } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 7024bdb6820..69d717bfe87 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -28,10 +28,13 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Psr7\Request; +use Http\Client\Exception; +use Http\Client\HttpClient; +use Swagger\Client\ApiException; +use Swagger\Client\HeaderSelector; +use Swagger\Client\Model\Pet; +use Swagger\Client\ObjectSerializer; /** * FakeApi Class Doc Comment @@ -44,47 +47,23 @@ class FakeApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient + * @var HttpClient */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var ObjectSerializer */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } - - $this->apiClient = $apiClient; - } + protected $serializer; /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @param HttpClient $client */ - public function getApiClient() + public function __construct(HttpClient $client, HeaderSelector $selector = null) { - return $this->apiClient; - } - - /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return FakeApi - */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) - { - $this->apiClient = $apiClient; - return $this; + $this->client = $client; + $this->serializer = new ObjectSerializer(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -109,6 +88,7 @@ public function testClientModel($body) * * @param \Swagger\Client\Model\Client $body client model (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ public function testClientModelWithHttpInfo($body) @@ -117,17 +97,20 @@ public function testClientModelWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); } - // parse inputs - $resourcePath = "/fake"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/fake', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); + + +/** + + */ // body params $_tempBody = null; @@ -141,7 +124,27 @@ public function testClientModelWithHttpInfo($body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'PATCH', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Client', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -164,8 +167,8 @@ public function testClientModelWithHttpInfo($body) throw $e; } +*/ } - /** * Operation testEndpointParameters * @@ -191,7 +194,7 @@ public function testClientModelWithHttpInfo($body) public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) { list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); - return $response; + } /** @@ -214,6 +217,7 @@ public function testEndpointParameters($number, $double, $pattern_without_delimi * @param string $password None (optional) * @param string $callback None (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) @@ -222,10 +226,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if ($number === null) { throw new \InvalidArgumentException('Missing the required parameter $number when calling testEndpointParameters'); } - if (($number > 543.2)) { + if ($number > 543.2) { throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 543.2.'); } - if (($number < 32.1)) { + if ($number < 32.1) { throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 32.1.'); } @@ -233,10 +237,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if ($double === null) { throw new \InvalidArgumentException('Missing the required parameter $double when calling testEndpointParameters'); } - if (($double > 123.4)) { + if ($double > 123.4) { throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 123.4.'); } - if (($double < 67.8)) { + if ($double < 67.8) { throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 67.8.'); } @@ -244,7 +248,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if ($pattern_without_delimiter === null) { throw new \InvalidArgumentException('Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters'); } - if (!preg_match("/^[A-Z].*_/", $pattern_without_delimiter)) { + if (!preg_match("/^[A-Z].*_/", $pattern_without_delimiter) { throw new \InvalidArgumentException("invalid value for \"pattern_without_delimiter\" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*_/."); } @@ -252,101 +256,132 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if ($byte === null) { throw new \InvalidArgumentException('Missing the required parameter $byte when calling testEndpointParameters'); } - if (!is_null($integer) && ($integer > 100)) { + if ($integer !== null && $integer > 100) { throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 100.'); } - if (!is_null($integer) && ($integer < 10)) { + if ($integer !== null && $integer < 10) { throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } - if (!is_null($int32) && ($int32 > 200)) { + if ($int32 !== null && $int32 > 200) { throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 200.'); } - if (!is_null($int32) && ($int32 < 20)) { + if ($int32 !== null && $int32 < 20) { throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 20.'); } - if (!is_null($float) && ($float > 987.6)) { + if ($float !== null && $float > 987.6) { throw new \InvalidArgumentException('invalid value for "$float" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 987.6.'); } - if (!is_null($string) && !preg_match("/[a-z]/i", $string)) { + if ($string !== null && !preg_match("/[a-z]/i", $string) { throw new \InvalidArgumentException("invalid value for \"string\" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i."); } - if (!is_null($password) && (strlen($password) > 64)) { + if ($password !== null && strlen($password) > 64) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); } - if (!is_null($password) && (strlen($password) < 10)) { + if ($password !== null && strlen($password) < 10) { throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } - // parse inputs - $resourcePath = "/fake"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/fake', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/xml; charset=utf-8', 'application/json; charset=utf-8']); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml; charset=utf-8', 'application/json; charset=utf-8'], + ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] + ); + + +/** + + */ // form params if ($integer !== null) { + /** + */ $formParams['integer'] = $this->apiClient->getSerializer()->toFormValue($integer); } // form params if ($int32 !== null) { + /** + */ $formParams['int32'] = $this->apiClient->getSerializer()->toFormValue($int32); } // form params if ($int64 !== null) { + /** + */ $formParams['int64'] = $this->apiClient->getSerializer()->toFormValue($int64); } // form params if ($number !== null) { + /** + */ $formParams['number'] = $this->apiClient->getSerializer()->toFormValue($number); } // form params if ($float !== null) { + /** + */ $formParams['float'] = $this->apiClient->getSerializer()->toFormValue($float); } // form params if ($double !== null) { + /** + */ $formParams['double'] = $this->apiClient->getSerializer()->toFormValue($double); } // form params if ($string !== null) { + /** + */ $formParams['string'] = $this->apiClient->getSerializer()->toFormValue($string); } // form params if ($pattern_without_delimiter !== null) { + /** + */ $formParams['pattern_without_delimiter'] = $this->apiClient->getSerializer()->toFormValue($pattern_without_delimiter); } // form params if ($byte !== null) { + /** + */ $formParams['byte'] = $this->apiClient->getSerializer()->toFormValue($byte); } // form params if ($binary !== null) { + /** + */ $formParams['binary'] = $this->apiClient->getSerializer()->toFormValue($binary); } // form params if ($date !== null) { + /** + */ $formParams['date'] = $this->apiClient->getSerializer()->toFormValue($date); } // form params if ($date_time !== null) { + /** + */ $formParams['dateTime'] = $this->apiClient->getSerializer()->toFormValue($date_time); } // form params if ($password !== null) { + /** + */ $formParams['password'] = $this->apiClient->getSerializer()->toFormValue($password); } // form params if ($callback !== null) { + /** + */ $formParams['callback'] = $this->apiClient->getSerializer()->toFormValue($callback); } @@ -356,11 +391,26 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires HTTP basic authentication if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); } - // make the API Call +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -379,8 +429,8 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi throw $e; } +*/ } - /** * Operation testEnumParameters * @@ -400,7 +450,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi public function testEnumParameters($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { list($response) = $this->testEnumParametersWithHttpInfo($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); - return $response; + } /** @@ -417,22 +467,23 @@ public function testEnumParameters($enum_form_string_array = null, $enum_form_st * @param int $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { - // parse inputs - $resourcePath = "/fake"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/fake', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['*/*']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['*/*']); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['*/*'] + ); + +/** // query params if (is_array($enum_query_string_array)) { $enum_query_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_query_string_array, 'csv', true); @@ -459,16 +510,25 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ if ($enum_header_string !== null) { $headerParams['enum_header_string'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string); } + + */ + // form params if ($enum_form_string_array !== null) { + /** + */ $formParams['enum_form_string_array'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string_array); } // form params if ($enum_form_string !== null) { + /** + */ $formParams['enum_form_string'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string); } // form params if ($enum_query_double !== null) { + /** + */ $formParams['enum_query_double'] = $this->apiClient->getSerializer()->toFormValue($enum_query_double); } @@ -478,7 +538,22 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -497,5 +572,6 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ throw $e; } +*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 2a83fec174f..7894214b01f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -28,10 +28,13 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Psr7\Request; +use Http\Client\Exception; +use Http\Client\HttpClient; +use Swagger\Client\ApiException; +use Swagger\Client\HeaderSelector; +use Swagger\Client\Model\Pet; +use Swagger\Client\ObjectSerializer; /** * PetApi Class Doc Comment @@ -44,47 +47,23 @@ class PetApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient - */ - protected $apiClient; - - /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var HttpClient */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } - - $this->apiClient = $apiClient; - } + protected $client; /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @var ObjectSerializer */ - public function getApiClient() - { - return $this->apiClient; - } + protected $serializer; /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return PetApi + * @param HttpClient $client */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) + public function __construct(HttpClient $client, HeaderSelector $selector = null) { - $this->apiClient = $apiClient; - return $this; + $this->client = $client; + $this->serializer = new ObjectSerializer(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -99,7 +78,7 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) public function addPet($body) { list($response) = $this->addPetWithHttpInfo($body); - return $response; + } /** @@ -109,6 +88,7 @@ public function addPet($body) * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function addPetWithHttpInfo($body) @@ -117,17 +97,20 @@ public function addPetWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); } - // parse inputs - $resourcePath = "/pet"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', 'application/xml']); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); + + +/** + + */ // body params $_tempBody = null; @@ -141,11 +124,26 @@ public function addPetWithHttpInfo($body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -164,8 +162,8 @@ public function addPetWithHttpInfo($body) throw $e; } +*/ } - /** * Operation deletePet * @@ -179,7 +177,7 @@ public function addPetWithHttpInfo($body) public function deletePet($pet_id, $api_key = null) { list($response) = $this->deletePetWithHttpInfo($pet_id, $api_key); - return $response; + } /** @@ -190,6 +188,7 @@ public function deletePet($pet_id, $api_key = null) * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deletePetWithHttpInfo($pet_id, $api_key = null) @@ -198,30 +197,29 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet/{petId}', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + +/** // header params if ($api_key !== null) { $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); } + + */ // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); } + // for model (json/xml) if (isset($_tempBody)) { @@ -229,11 +227,26 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call +*/ + + try { + $request = new Request( + 'DELETE', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -252,8 +265,8 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) throw $e; } +*/ } - /** * Operation findPetsByStatus * @@ -276,6 +289,7 @@ public function findPetsByStatus($status) * * @param string[] $status Status values that need to be considered for filter (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByStatusWithHttpInfo($status) @@ -284,18 +298,18 @@ public function findPetsByStatusWithHttpInfo($status) if ($status === null) { throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); } - // parse inputs - $resourcePath = "/pet/findByStatus"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet/findByStatus', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + +/** // query params if (is_array($status)) { $status = $this->apiClient->getSerializer()->serializeCollection($status, 'csv', true); @@ -303,6 +317,9 @@ public function findPetsByStatusWithHttpInfo($status) if ($status !== null) { $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); } + + */ + // for model (json/xml) if (isset($_tempBody)) { @@ -310,11 +327,31 @@ public function findPetsByStatusWithHttpInfo($status) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -337,8 +374,8 @@ public function findPetsByStatusWithHttpInfo($status) throw $e; } +*/ } - /** * Operation findPetsByTags * @@ -361,6 +398,7 @@ public function findPetsByTags($tags) * * @param string[] $tags Tags to filter by (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByTagsWithHttpInfo($tags) @@ -369,18 +407,18 @@ public function findPetsByTagsWithHttpInfo($tags) if ($tags === null) { throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); } - // parse inputs - $resourcePath = "/pet/findByTags"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet/findByTags', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + +/** // query params if (is_array($tags)) { $tags = $this->apiClient->getSerializer()->serializeCollection($tags, 'csv', true); @@ -388,6 +426,9 @@ public function findPetsByTagsWithHttpInfo($tags) if ($tags !== null) { $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); } + + */ + // for model (json/xml) if (isset($_tempBody)) { @@ -395,11 +436,31 @@ public function findPetsByTagsWithHttpInfo($tags) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -422,8 +483,8 @@ public function findPetsByTagsWithHttpInfo($tags) throw $e; } +*/ } - /** * Operation getPetById * @@ -446,6 +507,7 @@ public function getPetById($pet_id) * * @param int $pet_id ID of pet to return (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ public function getPetByIdWithHttpInfo($pet_id) @@ -454,26 +516,25 @@ public function getPetByIdWithHttpInfo($pet_id) if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet/{petId}', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + +/** + + */ // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); } + // for model (json/xml) if (isset($_tempBody)) { @@ -481,12 +542,32 @@ public function getPetByIdWithHttpInfo($pet_id) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); if (strlen($apiKey) !== 0) { $headerParams['api_key'] = $apiKey; } - // make the API Call +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -509,8 +590,8 @@ public function getPetByIdWithHttpInfo($pet_id) throw $e; } +*/ } - /** * Operation updatePet * @@ -523,7 +604,7 @@ public function getPetByIdWithHttpInfo($pet_id) public function updatePet($body) { list($response) = $this->updatePetWithHttpInfo($body); - return $response; + } /** @@ -533,6 +614,7 @@ public function updatePet($body) * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithHttpInfo($body) @@ -541,17 +623,20 @@ public function updatePetWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); } - // parse inputs - $resourcePath = "/pet"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', 'application/xml']); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); + + +/** + + */ // body params $_tempBody = null; @@ -565,11 +650,26 @@ public function updatePetWithHttpInfo($body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call +*/ + + try { + $request = new Request( + 'PUT', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -588,8 +688,8 @@ public function updatePetWithHttpInfo($body) throw $e; } +*/ } - /** * Operation updatePetWithForm * @@ -604,7 +704,7 @@ public function updatePetWithHttpInfo($body) public function updatePetWithForm($pet_id, $name = null, $status = null) { list($response) = $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); - return $response; + } /** @@ -616,6 +716,7 @@ public function updatePetWithForm($pet_id, $name = null, $status = null) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) @@ -624,32 +725,35 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet/{petId}', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/x-www-form-urlencoded']); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/x-www-form-urlencoded'] + ); + +/** + + */ // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); } + // form params if ($name !== null) { + /** + */ $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); } // form params if ($status !== null) { + /** + */ $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); } @@ -659,11 +763,26 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -682,8 +801,8 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n throw $e; } +*/ } - /** * Operation uploadFile * @@ -710,6 +829,7 @@ public function uploadFile($pet_id, $additional_metadata = null, $file = null) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) */ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) @@ -718,32 +838,34 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - // parse inputs - $resourcePath = "/pet/{petId}/uploadImage"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/pet/{petId}/uploadImage', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['multipart/form-data']); + $httpBody= ''; + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['multipart/form-data'] + ); + + +/** + + */ // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); } + // form params if ($additional_metadata !== null) { + /** + */ $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); } // form params if ($file !== null) { + /** // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax // See: https://wiki.php.net/rfc/curl-file-upload if (function_exists('curl_file_create')) { @@ -751,6 +873,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } else { $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); } + */ } // for model (json/xml) @@ -759,11 +882,31 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires OAuth (access token) if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } - // make the API Call +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\ApiResponse', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -786,5 +929,6 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi throw $e; } +*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php new file mode 100644 index 00000000000..11ec90fc6b9 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php @@ -0,0 +1,721 @@ +client = $client; + $this->serializer = new ObjectSerializer(); + $this->headerSelector = $selector ?: new HeaderSelector(); + } + + /** + * Operation addPet + * + * Add a new pet to the store + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return void + */ + public function addPet($body) + { + list($response) = $this->addPetWithHttpInfo($body); + return $response; + } + + /** + * Operation addPetWithHttpInfo + * + * Add a new pet to the store + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function addPetWithHttpInfo($body) + { + // verify the required parameter 'body' is set + if ($body === null) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); + } + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + $request = new Request( + 'POST', + '/v2/pet', + $headers, + json_encode(ObjectSerializer::sanitizeForSerialization($body)) + ); + + try { + $response = $this->client->sendRequest($request); + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } + + $content = json_decode($response->getBody()->getContents()); + $result = ObjectSerializer::deserialize($content, Pet::class); + + return [ + $result, + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + /** + * Operation deletePet + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return void + */ + public function deletePet($pet_id, $api_key = null) + { + list($response) = $this->deletePetWithHttpInfo($pet_id, $api_key); + return $response; + } + + /** + * Operation deletePetWithHttpInfo + * + * Deletes a pet + * + * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function deletePetWithHttpInfo($pet_id, $api_key = null) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); + } + // parse inputs + $resourcePath = "/pet/{petId}"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->client->selectHeaderContentType([]); + + // header params + if ($api_key !== null) { + $headerParams['api_key'] = $this->client->getSerializer()->toHeaderValue($api_key); + } + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->client->getSerializer()->toPathValue($pet_id), + $resourcePath + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // this endpoint requires OAuth (access token) + if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->client->callApi( + $resourcePath, + 'DELETE', + $queryParams, + $httpBody, + $headerParams, + null, + '/pet/{petId}' + ); + + return [null, $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } + + /** + * Operation findPetsByStatus + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Pet[] + */ + public function findPetsByStatus($status) + { + list($response) = $this->findPetsByStatusWithHttpInfo($status); + return $response; + } + + /** + * Operation findPetsByStatusWithHttpInfo + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + */ + public function findPetsByStatusWithHttpInfo($status) + { + // verify the required parameter 'status' is set + if ($status === null) { + throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); + } + // parse inputs + $resourcePath = "/pet/findByStatus"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->client->selectHeaderContentType([]); + + // query params + if (is_array($status)) { + $status = $this->client->getSerializer()->serializeCollection($status, 'csv', true); + } + if ($status !== null) { + $queryParams['status'] = $this->client->getSerializer()->toQueryValue($status); + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // this endpoint requires OAuth (access token) + if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->client->callApi( + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]', + '/pet/findByStatus' + ); + + return [$this->client->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->client->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + + /** + * Operation findPetsByTags + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Pet[] + */ + public function findPetsByTags($tags) + { + list($response) = $this->findPetsByTagsWithHttpInfo($tags); + return $response; + } + + /** + * Operation findPetsByTagsWithHttpInfo + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) + */ + public function findPetsByTagsWithHttpInfo($tags) + { + // verify the required parameter 'tags' is set + if ($tags === null) { + throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); + } + // parse inputs + $resourcePath = "/pet/findByTags"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->client->selectHeaderContentType([]); + + // query params + if (is_array($tags)) { + $tags = $this->client->getSerializer()->serializeCollection($tags, 'csv', true); + } + if ($tags !== null) { + $queryParams['tags'] = $this->client->getSerializer()->toQueryValue($tags); + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // this endpoint requires OAuth (access token) + if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->client->callApi( + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\Pet[]', + '/pet/findByTags' + ); + + return [$this->client->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->client->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + + /** + * Operation getPetById + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\Pet + */ + public function getPetById($pet_id) + { + list($response) = $this->getPetByIdWithHttpInfo($pet_id); + return $response; + } + + /** + * Operation getPetByIdWithHttpInfo + * + * Find pet by ID + * + * @param int $pet_id ID of pet to return (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) + * @throws \Exception + * @throws \InvalidArgumentException + */ + public function getPetByIdWithHttpInfo($pet_id) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); + } + + $resourcePath = '/v2/pet/{petId}'; + $resourcePath = str_replace('{petId}', $this->serializer->toPathValue($pet_id), $resourcePath); + + $request = new Request( + 'GET', + $resourcePath, + $this->headerSelector->selectHeaders(['application/json'], []) + ); + + + try { + $response = $this->client->sendRequest($request); + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } + + $content = json_decode($response->getBody()->getContents()); + $result = ObjectSerializer::deserialize($content, Pet::class); + + return [ + $result, + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + /** + * Operation updatePet + * + * Update an existing pet + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return void + */ + public function updatePet($body) + { + list($response) = $this->updatePetWithHttpInfo($body); + return $response; + } + + /** + * Operation updatePetWithHttpInfo + * + * Update an existing pet + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function updatePetWithHttpInfo($body) + { + // verify the required parameter 'body' is set + if ($body === null) { + throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); + } + // parse inputs + $resourcePath = "/pet"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->client->selectHeaderContentType(['application/json', 'application/xml']); + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // this endpoint requires OAuth (access token) + if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->client->callApi( + $resourcePath, + 'PUT', + $queryParams, + $httpBody, + $headerParams, + null, + '/pet' + ); + + return [null, $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } + + /** + * Operation updatePetWithForm + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return void + */ + public function updatePetWithForm($pet_id, $name = null, $status = null) + { + list($response) = $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); + return $response; + } + + /** + * Operation updatePetWithFormWithHttpInfo + * + * Updates a pet in the store with form data + * + * @param int $pet_id ID of pet that needs to be updated (required) + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); + } + // parse inputs + $resourcePath = "/pet/{petId}"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->client->selectHeaderContentType(['application/x-www-form-urlencoded']); + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->client->getSerializer()->toPathValue($pet_id), + $resourcePath + ); + } + // form params + if ($name !== null) { + $formParams['name'] = $this->client->getSerializer()->toFormValue($name); + } + // form params + if ($status !== null) { + $formParams['status'] = $this->client->getSerializer()->toFormValue($status); + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // this endpoint requires OAuth (access token) + if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->client->callApi( + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + null, + '/pet/{petId}' + ); + + return [null, $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + } + + /** + * Operation uploadFile + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return \Swagger\Client\Model\ApiResponse + */ + public function uploadFile($pet_id, $additional_metadata = null, $file = null) + { + list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file); + return $response; + } + + /** + * Operation uploadFileWithHttpInfo + * + * uploads an image + * + * @param int $pet_id ID of pet to update (required) + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) + * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) + */ + public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) + { + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); + } + // parse inputs + $resourcePath = "/pet/{petId}/uploadImage"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->client->selectHeaderAccept(['application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->client->selectHeaderContentType(['multipart/form-data']); + + // path params + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->client->getSerializer()->toPathValue($pet_id), + $resourcePath + ); + } + // form params + if ($additional_metadata !== null) { + $formParams['additionalMetadata'] = $this->client->getSerializer()->toFormValue($additional_metadata); + } + // form params + if ($file !== null) { + // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax + // See: https://wiki.php.net/rfc/curl-file-upload + if (function_exists('curl_file_create')) { + $formParams['file'] = curl_file_create($this->client->getSerializer()->toFormValue($file)); + } else { + $formParams['file'] = '@' . $this->client->getSerializer()->toFormValue($file); + } + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // this endpoint requires OAuth (access token) + if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->client->callApi( + $resourcePath, + 'POST', + $queryParams, + $httpBody, + $headerParams, + '\Swagger\Client\Model\ApiResponse', + '/pet/{petId}/uploadImage' + ); + + return [$this->client->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->client->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index bfa8fd71583..ab156e4752f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -28,10 +28,13 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Psr7\Request; +use Http\Client\Exception; +use Http\Client\HttpClient; +use Swagger\Client\ApiException; +use Swagger\Client\HeaderSelector; +use Swagger\Client\Model\Pet; +use Swagger\Client\ObjectSerializer; /** * StoreApi Class Doc Comment @@ -44,47 +47,23 @@ class StoreApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient + * @var HttpClient */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var ObjectSerializer */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } - - $this->apiClient = $apiClient; - } - - /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client - */ - public function getApiClient() - { - return $this->apiClient; - } + protected $serializer; /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return StoreApi + * @param HttpClient $client */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) + public function __construct(HttpClient $client, HeaderSelector $selector = null) { - $this->apiClient = $apiClient; - return $this; + $this->client = $client; + $this->serializer = new ObjectSerializer(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -99,7 +78,7 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) public function deleteOrder($order_id) { list($response) = $this->deleteOrderWithHttpInfo($order_id); - return $response; + } /** @@ -109,6 +88,7 @@ public function deleteOrder($order_id) * * @param string $order_id ID of the order that needs to be deleted (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deleteOrderWithHttpInfo($order_id) @@ -123,12 +103,17 @@ public function deleteOrderWithHttpInfo($order_id) $queryParams = []; $headerParams = []; $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + + */ // path params if ($order_id !== null) { $resourcePath = str_replace( @@ -137,6 +122,7 @@ public function deleteOrderWithHttpInfo($order_id) $resourcePath ); } + // for model (json/xml) if (isset($_tempBody)) { @@ -144,7 +130,22 @@ public function deleteOrderWithHttpInfo($order_id) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'DELETE', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -163,8 +164,8 @@ public function deleteOrderWithHttpInfo($order_id) throw $e; } +*/ } - /** * Operation getInventory * @@ -185,21 +186,25 @@ public function getInventory() * Returns pet inventories by status * * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of map[string,int], HTTP status code, HTTP response headers (array of strings) */ public function getInventoryWithHttpInfo() { - // parse inputs - $resourcePath = "/store/inventory"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/store/inventory', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); + + +/** + + */ // for model (json/xml) @@ -208,12 +213,32 @@ public function getInventoryWithHttpInfo() } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } +/** // this endpoint requires API key authentication $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); if (strlen($apiKey) !== 0) { $headerParams['api_key'] = $apiKey; } - // make the API Call +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, 'map[string,int]', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -236,8 +261,8 @@ public function getInventoryWithHttpInfo() throw $e; } +*/ } - /** * Operation getOrderById * @@ -260,6 +285,7 @@ public function getOrderById($order_id) * * @param int $order_id ID of pet that needs to be fetched (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function getOrderByIdWithHttpInfo($order_id) @@ -268,10 +294,10 @@ public function getOrderByIdWithHttpInfo($order_id) if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); } - if (($order_id > 5)) { + if ($order_id > 5) { throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be smaller than or equal to 5.'); } - if (($order_id < 1)) { + if ($order_id < 1) { throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.'); } @@ -281,12 +307,17 @@ public function getOrderByIdWithHttpInfo($order_id) $queryParams = []; $headerParams = []; $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + +/** + + */ // path params if ($order_id !== null) { $resourcePath = str_replace( @@ -295,6 +326,7 @@ public function getOrderByIdWithHttpInfo($order_id) $resourcePath ); } + // for model (json/xml) if (isset($_tempBody)) { @@ -302,7 +334,27 @@ public function getOrderByIdWithHttpInfo($order_id) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -325,8 +377,8 @@ public function getOrderByIdWithHttpInfo($order_id) throw $e; } +*/ } - /** * Operation placeOrder * @@ -349,6 +401,7 @@ public function placeOrder($body) * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function placeOrderWithHttpInfo($body) @@ -357,17 +410,20 @@ public function placeOrderWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder'); } - // parse inputs - $resourcePath = "/store/order"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/store/order', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + + */ // body params $_tempBody = null; @@ -381,7 +437,27 @@ public function placeOrderWithHttpInfo($body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -404,5 +480,6 @@ public function placeOrderWithHttpInfo($body) throw $e; } +*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 8d893d055ec..4c55fd03a68 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -28,10 +28,13 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Psr7\Request; +use Http\Client\Exception; +use Http\Client\HttpClient; +use Swagger\Client\ApiException; +use Swagger\Client\HeaderSelector; +use Swagger\Client\Model\Pet; +use Swagger\Client\ObjectSerializer; /** * UserApi Class Doc Comment @@ -44,47 +47,23 @@ class UserApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient - */ - protected $apiClient; - - /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var HttpClient */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } - - $this->apiClient = $apiClient; - } + protected $client; /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @var ObjectSerializer */ - public function getApiClient() - { - return $this->apiClient; - } + protected $serializer; /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return UserApi + * @param HttpClient $client */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) + public function __construct(HttpClient $client, HeaderSelector $selector = null) { - $this->apiClient = $apiClient; - return $this; + $this->client = $client; + $this->serializer = new ObjectSerializer(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -99,7 +78,7 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) public function createUser($body) { list($response) = $this->createUserWithHttpInfo($body); - return $response; + } /** @@ -109,6 +88,7 @@ public function createUser($body) * * @param \Swagger\Client\Model\User $body Created user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUserWithHttpInfo($body) @@ -117,17 +97,20 @@ public function createUserWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUser'); } - // parse inputs - $resourcePath = "/user"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + + */ // body params $_tempBody = null; @@ -141,7 +124,22 @@ public function createUserWithHttpInfo($body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -160,8 +158,8 @@ public function createUserWithHttpInfo($body) throw $e; } +*/ } - /** * Operation createUsersWithArrayInput * @@ -174,7 +172,7 @@ public function createUserWithHttpInfo($body) public function createUsersWithArrayInput($body) { list($response) = $this->createUsersWithArrayInputWithHttpInfo($body); - return $response; + } /** @@ -184,6 +182,7 @@ public function createUsersWithArrayInput($body) * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUsersWithArrayInputWithHttpInfo($body) @@ -192,17 +191,20 @@ public function createUsersWithArrayInputWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithArrayInput'); } - // parse inputs - $resourcePath = "/user/createWithArray"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user/createWithArray', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + + */ // body params $_tempBody = null; @@ -216,7 +218,22 @@ public function createUsersWithArrayInputWithHttpInfo($body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -235,8 +252,8 @@ public function createUsersWithArrayInputWithHttpInfo($body) throw $e; } +*/ } - /** * Operation createUsersWithListInput * @@ -249,7 +266,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) public function createUsersWithListInput($body) { list($response) = $this->createUsersWithListInputWithHttpInfo($body); - return $response; + } /** @@ -259,6 +276,7 @@ public function createUsersWithListInput($body) * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUsersWithListInputWithHttpInfo($body) @@ -267,17 +285,20 @@ public function createUsersWithListInputWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithListInput'); } - // parse inputs - $resourcePath = "/user/createWithList"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user/createWithList', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + + */ // body params $_tempBody = null; @@ -291,7 +312,22 @@ public function createUsersWithListInputWithHttpInfo($body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'POST', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -310,8 +346,8 @@ public function createUsersWithListInputWithHttpInfo($body) throw $e; } +*/ } - /** * Operation deleteUser * @@ -324,7 +360,7 @@ public function createUsersWithListInputWithHttpInfo($body) public function deleteUser($username) { list($response) = $this->deleteUserWithHttpInfo($username); - return $response; + } /** @@ -334,6 +370,7 @@ public function deleteUser($username) * * @param string $username The name that needs to be deleted (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deleteUserWithHttpInfo($username) @@ -342,26 +379,25 @@ public function deleteUserWithHttpInfo($username) if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user/{username}', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + +/** + + */ // path params if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); + $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); } + // for model (json/xml) if (isset($_tempBody)) { @@ -369,7 +405,22 @@ public function deleteUserWithHttpInfo($username) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'DELETE', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -388,8 +439,8 @@ public function deleteUserWithHttpInfo($username) throw $e; } +*/ } - /** * Operation getUserByName * @@ -412,6 +463,7 @@ public function getUserByName($username) * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) */ public function getUserByNameWithHttpInfo($username) @@ -420,26 +472,25 @@ public function getUserByNameWithHttpInfo($username) if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user/{username}', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + */ // path params if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); + $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); } + // for model (json/xml) if (isset($_tempBody)) { @@ -447,7 +498,27 @@ public function getUserByNameWithHttpInfo($username) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\User', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -470,8 +541,8 @@ public function getUserByNameWithHttpInfo($username) throw $e; } +*/ } - /** * Operation loginUser * @@ -496,6 +567,7 @@ public function loginUser($username, $password) * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of string, HTTP status code, HTTP response headers (array of strings) */ public function loginUserWithHttpInfo($username, $password) @@ -508,18 +580,18 @@ public function loginUserWithHttpInfo($username, $password) if ($password === null) { throw new \InvalidArgumentException('Missing the required parameter $password when calling loginUser'); } - // parse inputs - $resourcePath = "/user/login"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user/login', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + +/** // query params if ($username !== null) { $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); @@ -528,6 +600,9 @@ public function loginUserWithHttpInfo($username, $password) if ($password !== null) { $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); } + + */ + // for model (json/xml) if (isset($_tempBody)) { @@ -535,7 +610,27 @@ public function loginUserWithHttpInfo($username, $password) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + $content = json_decode($response->getBody()->getContents()); + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + [] + ]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -558,8 +653,8 @@ public function loginUserWithHttpInfo($username, $password) throw $e; } +*/ } - /** * Operation logoutUser * @@ -571,7 +666,7 @@ public function loginUserWithHttpInfo($username, $password) public function logoutUser() { list($response) = $this->logoutUserWithHttpInfo(); - return $response; + } /** @@ -580,21 +675,25 @@ public function logoutUser() * Logs out current logged in user session * * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function logoutUserWithHttpInfo() { - // parse inputs - $resourcePath = "/user/logout"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user/logout', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + + */ // for model (json/xml) @@ -603,7 +702,22 @@ public function logoutUserWithHttpInfo() } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'GET', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -622,8 +736,8 @@ public function logoutUserWithHttpInfo() throw $e; } +*/ } - /** * Operation updateUser * @@ -637,7 +751,7 @@ public function logoutUserWithHttpInfo() public function updateUser($username, $body) { list($response) = $this->updateUserWithHttpInfo($username, $body); - return $response; + } /** @@ -648,6 +762,7 @@ public function updateUser($username, $body) * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException when invalid arguments provided * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updateUserWithHttpInfo($username, $body) @@ -660,26 +775,25 @@ public function updateUserWithHttpInfo($username, $body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updateUser'); } - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/user/{username}', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]); + $httpBody= ''; + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + + +/** + + */ // path params if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); + $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); } + // body params $_tempBody = null; if (isset($body)) { @@ -692,7 +806,22 @@ public function updateUserWithHttpInfo($username, $body) } elseif (count($formParams) > 0) { $httpBody = $formParams; // for HTTP post (form) } - // make the API Call +/** +*/ + + try { + $request = new Request( + 'PUT', + $resourcePath, + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), []]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -711,5 +840,6 @@ public function updateUserWithHttpInfo($username, $body) throw $e; } +*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php new file mode 100644 index 00000000000..0b4dc23f682 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php @@ -0,0 +1,163 @@ +serializer = new ObjectSerializer(); + $this->client = $client; + } + + /** + * Get the config + * + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Get the serializer + * + * @return ObjectSerializer + */ + public function getSerializer() + { + return $this->serializer; + } + + /** + * Make the HTTP call (Sync) + * + * @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 + * @param string $responseType expected response type of the endpoint + * @param string $endpointPath path to method endpoint before expanding parameters + * + * @throws \Swagger\Client\ApiException on a non 2xx response + * @return mixed + */ + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) + { + $request = new Request($method, $resourcePath, $headerParams, $postData); + try { + $response = $this->client->sendRequest($request); + } catch (Exception $exception) { + throw new ApiException('Client has thrown exception', null, $exception); + } + return [$response->getBody(), $response->getStatusCode(), $response->getHeaders()]; + } + + /** + * Return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * + * @return string Accept (e.g. application/json) + */ + public 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 string[] $content_type Array fo content-type + * + * @return string Content-Type (e.g. application/json) + */ + public 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/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php b/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php new file mode 100644 index 00000000000..4683e17bc7e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php @@ -0,0 +1,96 @@ +selectHeaderAccept($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + $headers['Content-Type'] = $this->selectHeaderContentType($contentTypes); + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * + * @return string Accept (e.g. application/json) + */ + private function selectHeaderAccept($accept) + { + if (count($accept) === 0 || (count($accept) === 1 && $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 string[] $contentType Array fo content-type + * + * @return string Content-Type (e.g. application/json) + */ + private function selectHeaderContentType($contentType) + { + if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $contentType)) { + return 'application/json'; + } else { + return implode(',', $contentType); + } + } + +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php new file mode 100644 index 00000000000..e0580064b63 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php @@ -0,0 +1,41 @@ +selectHeaders([ + 'application/xml', + 'application/json' + ], []); + $this->assertSame('application/json', $headers['Accept']); + + $headers = $selector->selectHeaders([], []); + $this->assertFalse(isset($headers['Accept'])); + + $header = $selector->selectHeaders([ + 'application/yaml', + 'application/xml' + ], []); + $this->assertSame('application/yaml,application/xml', $header['Accept']); + + // test selectHeaderContentType + $headers = $selector->selectHeaders([], [ + 'application/xml', + 'application/json' + ]); + $this->assertSame('application/json', $headers['Content-Type']); + + $headers = $selector->selectHeaders([], []); + $this->assertSame('application/json', $headers['Content-Type']); + $headers = $selector->selectHeaders([], [ + 'application/yaml', + 'application/xml' + ]); + $this->assertSame('application/yaml,application/xml', $headers['Content-Type']); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index bad55050ece..cd598d27ddc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -2,10 +2,17 @@ namespace Swagger\Client; +use Http\Adapter\Guzzle6\Client; +use Swagger\Client\Api\PetApi; +use Swagger\Client\Model\Pet; + class PetApiTest extends \PHPUnit_Framework_TestCase { // add a new pet (id 10005) to ensure the pet object is available for all the tests + /** @var PetApi */ + private $api; + public static function setUpBeforeClass() { // increase memory limit to avoid fatal error due to findPetByStatus @@ -23,7 +30,7 @@ public static function setUpBeforeClass() // enable debugging //Configuration::$debug = true; - + // skip initializing the API client as it should be automatic //$api_client = new ApiClient('http://petstore.swagger.io/v2'); // new pet @@ -31,7 +38,7 @@ public static function setUpBeforeClass() $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test"); - $new_pet->setPhotoUrls(array("http://test_php_unit_test.com")); + $new_pet->setPhotoUrls(["http://test_php_unit_test.com"]); // new tag $tag= new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet @@ -40,137 +47,87 @@ public static function setUpBeforeClass() $category = new Model\Category; $category->setId($new_pet_id); // use the same id as pet $category->setName("test php category"); - + $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - - $pet_api = new Api\PetApi(); + + $petApi = new Api\PetApi(new Client(new \GuzzleHttp\Client([ + 'base_uri' => 'http://petstore.swagger.io/v2/' + ]))); // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); + list(, $status) = $petApi->addPetWithHttpInfo($new_pet); + \PHPUnit_Framework_Assert::assertEquals(200, $status); } - - // test static functions defined in ApiClient - public function testApiClient() + + public function setUp() { - // test selectHeaderAccept - $api_client = new ApiClient(); - $this->assertSame('application/json', $api_client->selectHeaderAccept(array( - 'application/xml', - 'application/json' - ))); - $this->assertSame(null, $api_client->selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array( - 'application/yaml', - 'application/xml' - ))); - - // test selectHeaderContentType - $this->assertSame('application/json', $api_client->selectHeaderContentType(array( - 'application/xml', - 'application/json' - ))); - $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array( - 'application/yaml', - 'application/xml' - ))); - - // test addDefaultHeader and getDefaultHeader - $api_client->getConfig()->addDefaultHeader('test1', 'value1'); - $api_client->getConfig()->addDefaultHeader('test2', 200); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertSame('value1', $defaultHeader['test1']); - $this->assertSame(200, $defaultHeader['test2']); - - // test deleteDefaultHeader - $api_client->getConfig()->deleteDefaultHeader('test2'); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertFalse(isset($defaultHeader['test2'])); - - $pet_api2 = new Api\PetApi(); - $config3 = new Configuration(); - $apiClient3 = new ApiClient($config3); - $apiClient3->getConfig()->setUserAgent('api client 3'); - $config4 = new Configuration(); - $apiClient4 = new ApiClient($config4); - $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Api\PetApi($apiClient3); - - // 2 different api clients are not the same - $this->assertNotEquals($apiClient3, $apiClient4); - // customied pet api not using the old pet api's api client - $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); - - // test access token - $api_client->getConfig()->setAccessToken("testing_only"); - $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); + $this->api = new Api\PetApi( + new Client( + new \GuzzleHttp\Client(['base_uri' => 'http://petstore.swagger.io/v2/']) + ) + ); } - - // test getPetById with a Pet object (id 10005) + public function testGetPetById() { - // initialize the API client without host - $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - // return Pet (model) - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - $this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com'); - $this->assertSame($response->getCategory()->getId(), $pet_id); - $this->assertSame($response->getCategory()->getName(), 'test php category'); - $this->assertSame($response->getTags()[0]->getId(), $pet_id); - $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + $petId = 10005; + + $pet = $this->api->getPetById($petId); + $this->assertSame($pet->getId(), $petId); + $this->assertSame($pet->getName(), 'PHP Unit Test'); + $this->assertSame($pet->getPhotoUrls()[0], 'http://test_php_unit_test.com'); + $this->assertSame($pet->getCategory()->getId(), $petId); + $this->assertSame($pet->getCategory()->getName(), 'test php category'); + $this->assertSame($pet->getTags()[0]->getId(), $petId); + $this->assertSame($pet->getTags()[0]->getName(), 'test php tag'); } /** * comment out as we've removed invalid endpoints from the spec, we'll introduce something * similar in the future when we've time to update the petstore server * - // test getPetById with a Pet object (id 10005) - public function testGetPetByIdInObject() - { - // initialize the API client without host - $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - // return Pet (inline model) - $response = $pet_api->getPetByIdInObject($pet_id); - $this->assertInstanceOf('Swagger\Client\Model\InlineResponse200', $response); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - $this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com'); - - // category is type "object" - $this->assertInternalType('array', $response->getCategory()); - $this->assertSame($response->getCategory()['id'], $pet_id); - $this->assertSame($response->getCategory()['name'], 'test php category'); - - $this->assertSame($response->getTags()[0]->getId(), $pet_id); - $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); - } + * // test getPetById with a Pet object (id 10005) + * public function testGetPetByIdInObject() + * { + * // initialize the API client without host + * $pet_id = 10005; // ID of pet that needs to be fetched + * $pet_api = new Api\PetApi(); + * $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + * // return Pet (inline model) + * $response = $pet_api->getPetByIdInObject($pet_id); + * $this->assertInstanceOf('Swagger\Client\Model\InlineResponse200', $response); + * $this->assertSame($response->getId(), $pet_id); + * $this->assertSame($response->getName(), 'PHP Unit Test'); + * $this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com'); + * + * // category is type "object" + * $this->assertInternalType('array', $response->getCategory()); + * $this->assertSame($response->getCategory()['id'], $pet_id); + * $this->assertSame($response->getCategory()['name'], 'test php category'); + * + * $this->assertSame($response->getTags()[0]->getId(), $pet_id); + * $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + * } */ - + // test getPetByIdWithHttpInfo with a Pet object (id 10005) public function testGetPetByIdWithHttpInfo() { // initialize the API client without host - $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - // return Pet (model) - list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - $this->assertSame($response->getCategory()->getId(), $pet_id); - $this->assertSame($response->getCategory()->getName(), 'test php category'); - $this->assertSame($response->getTags()[0]->getId(), $pet_id); - $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + $petId = 10005; // ID of pet that needs to be fetched + + /** @var $pet Pet */ + list($pet, $status_code, $response_headers) = $this->api->getPetByIdWithHttpInfo($petId); + $this->assertSame($pet->getId(), $petId); + $this->assertSame($pet->getName(), 'PHP Unit Test'); + $this->assertSame($pet->getCategory()->getId(), $petId); + $this->assertSame($pet->getCategory()->getName(), 'test php category'); + $this->assertSame($pet->getTags()[0]->getId(), $petId); + $this->assertSame($pet->getTags()[0]->getName(), 'test php tag'); $this->assertSame($status_code, 200); - $this->assertSame($response_headers['Content-Type'], 'application/json'); + $this->assertSame($response_headers['Content-Type'], ['application/json']); } - + // test getPetByStatus and verify by the "id" of the response public function testFindPetByStatus() { @@ -190,7 +147,7 @@ public function testFindPetByStatus() $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); $this->assertSame(count($response), 0); // confirm no object returned } - + // test getPetsByTags and verify by the "id" of the response public function testFindPetsByTags() { @@ -234,7 +191,7 @@ public function testUpdatePet() $this->assertSame($response->getStatus(), 'pending'); $this->assertSame($response->getName(), 'updatePet'); } - + // test updatePetWithFormWithHttpInfo and verify by the "name" of the response public function testUpdatePetWithFormWithHttpInfo() { @@ -256,7 +213,7 @@ public function testUpdatePetWithFormWithHttpInfo() $this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getName(), 'update pet with form with http info'); } - + // test updatePetWithForm and verify by the "name" and "status" of the response public function testUpdatePetWithForm() { @@ -336,7 +293,7 @@ public function testAddPetUsingByteArray() $this->assertSame($response->getName(), 'PHP Unit Test 3'); } */ - + // test upload file public function testUploadFile() { @@ -351,7 +308,7 @@ public function testUploadFile() $this->assertInstanceOf('Swagger\Client\Model\ApiResponse', $response); } - + // test get inventory public function testGetInventory() { @@ -362,7 +319,7 @@ public function testGetInventory() $store_api = new Api\StoreApi($api_client); // get inventory $get_response = $store_api->getInventory(); - + $this->assertInternalType("int", $get_response['sold']); $this->assertInternalType("int", $get_response['pending']); } @@ -484,12 +441,12 @@ public function testDefaultValues() public function testHostOverride() { $orig_default = Configuration::getDefaultConfiguration(); - $new_default = new Configuration(); - + $new_default = new Configuration(); + $new_default->setHost("http://localhost/whatever"); Configuration::setDefaultConfiguration($new_default); - $pet_api = new Api\PetApi(); + $pet_api = new Api\PetApi(); $pet_host = $pet_api->getApiClient()->getConfig()->getHost(); $this->assertSame($pet_host, $new_default->getHost()); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 6b926c1d29d..d66e1d4770f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -76,20 +76,20 @@ public function testGetInventoryInObject() * checking (not on empty array is true, same thing could happen * with careless use of empty()). */ - public function testEmptyArrayResponse() - { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $apiClient = new ApiClient($config); - $storeApi = new Api\PetApi($apiClient); - // this call returns and empty array - $response = $storeApi->findPetsByStatus(array()); - - // make sure this is an array as we want it to be - $this->assertInternalType("array", $response); - - // make sure the array is empty just in case the petstore - // server changes its output - $this->assertEmpty($response); - } +// public function testEmptyArrayResponse() +// { +// // initialize the API client +// $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); +// $apiClient = new ApiClient($config); +// $storeApi = new Api\PetApi($apiClient); +// // this call returns and empty array +// $response = $storeApi->findPetsByStatus(array()); +// +// // make sure this is an array as we want it to be +// $this->assertInternalType("array", $response); +// +// // make sure the array is empty just in case the petstore +// // server changes its output +// $this->assertEmpty($response); +// } } From 5691bcd8f5eba050b41847c2713c7c9068bb7d0e Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Wed, 15 Mar 2017 13:19:05 +0000 Subject: [PATCH 02/37] added returning headers --- .../swagger-codegen/src/main/resources/php/api.mustache | 2 +- .../petstore/php/SwaggerClient-php/lib/Api/FakeApi.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Api/PetApi.php | 8 ++++---- .../petstore/php/SwaggerClient-php/lib/Api/StoreApi.php | 6 +++--- .../petstore/php/SwaggerClient-php/lib/Api/UserApi.php | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index ee106f75610..0e5e6a0a72d 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -259,7 +259,7 @@ use {{invokerPackage}}\ObjectSerializer; return [ ObjectSerializer::deserialize($content, '{{returnType}}', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; {{/returnType}} {{^returnType}} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 69d717bfe87..1cb55fdad80 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -139,7 +139,7 @@ public function testClientModelWithHttpInfo($body) return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Client', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 7894214b01f..c81791b0d55 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -346,7 +346,7 @@ public function findPetsByStatusWithHttpInfo($status) return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); @@ -455,7 +455,7 @@ public function findPetsByTagsWithHttpInfo($tags) return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); @@ -562,7 +562,7 @@ public function getPetByIdWithHttpInfo($pet_id) return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); @@ -901,7 +901,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\ApiResponse', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index ab156e4752f..04dee1f42b8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -233,7 +233,7 @@ public function getInventoryWithHttpInfo() return [ ObjectSerializer::deserialize($content, 'map[string,int]', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); @@ -349,7 +349,7 @@ public function getOrderByIdWithHttpInfo($order_id) return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); @@ -452,7 +452,7 @@ public function placeOrderWithHttpInfo($body) return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 4c55fd03a68..5097034e52d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -513,7 +513,7 @@ public function getUserByNameWithHttpInfo($username) return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\User', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); @@ -625,7 +625,7 @@ public function loginUserWithHttpInfo($username, $password) return [ ObjectSerializer::deserialize($content, 'string', []), $response->getStatusCode(), - [] + $response->getHeaders() ]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); From af05bed329d8bf3a810001a1dbed6ab49c7f84bd Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Wed, 15 Mar 2017 14:05:46 +0000 Subject: [PATCH 03/37] added query params support --- .../src/main/resources/php/api.mustache | 14 ++-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 34 ++++++---- .../php/SwaggerClient-php/lib/Api/PetApi.php | 65 +++++++++++-------- .../SwaggerClient-php/lib/Api/StoreApi.php | 29 +++++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 61 +++++++++-------- .../SwaggerClient-php/tests/PetApiTest.php | 16 ++--- 6 files changed, 126 insertions(+), 93 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 0e5e6a0a72d..7ed6662064c 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -19,6 +19,7 @@ namespace {{apiPackage}}; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; use Http\Client\HttpClient; use {{invokerPackage}}\ApiException; @@ -145,6 +146,7 @@ use {{invokerPackage}}\ObjectSerializer; $resourcePath = substr('{{{path}}}', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -153,19 +155,19 @@ use {{invokerPackage}}\ObjectSerializer; ); -/** {{#queryParams}} // query params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}', true); + ${{paramName}} = $this->serializer->serializeCollection(${{paramName}}, '{{collectionFormat}}', true); } {{/collectionFormat}} if (${{paramName}} !== null) { - $queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); + $queryParams['{{baseName}}'] = $this->serializer->toQueryValue(${{paramName}}); } {{/queryParams}} {{#headerParams}} +/** // header params {{#collectionFormat}} if (is_array(${{paramName}})) { @@ -175,9 +177,9 @@ use {{invokerPackage}}\ObjectSerializer; if (${{paramName}} !== null) { $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); } +*/ {{/headerParams}} - */ {{#pathParams}} // path params {{#collectionFormat}} @@ -246,10 +248,12 @@ use {{invokerPackage}}\ObjectSerializer; {{/authMethods}} */ + $query = http_build_query($queryParams); + try { $request = new Request( '{{httpMethod}}', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 1cb55fdad80..cc5d14d0a33 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -29,6 +29,7 @@ namespace Swagger\Client\Api; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -100,6 +101,7 @@ public function testClientModelWithHttpInfo($body) $resourcePath = substr('/fake', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -108,9 +110,7 @@ public function testClientModelWithHttpInfo($body) ); -/** - */ // body params $_tempBody = null; @@ -127,10 +127,12 @@ public function testClientModelWithHttpInfo($body) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'PATCH', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -288,6 +290,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $resourcePath = substr('/fake', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -296,9 +299,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi ); -/** - */ // form params if ($integer !== null) { @@ -398,10 +399,12 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -475,6 +478,7 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $resourcePath = substr('/fake', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -483,22 +487,22 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ ); -/** // query params if (is_array($enum_query_string_array)) { - $enum_query_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_query_string_array, 'csv', true); + $enum_query_string_array = $this->serializer->serializeCollection($enum_query_string_array, 'csv', true); } if ($enum_query_string_array !== null) { - $queryParams['enum_query_string_array'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_string_array); + $queryParams['enum_query_string_array'] = $this->serializer->toQueryValue($enum_query_string_array); } // query params if ($enum_query_string !== null) { - $queryParams['enum_query_string'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_string); + $queryParams['enum_query_string'] = $this->serializer->toQueryValue($enum_query_string); } // query params if ($enum_query_integer !== null) { - $queryParams['enum_query_integer'] = $this->apiClient->getSerializer()->toQueryValue($enum_query_integer); + $queryParams['enum_query_integer'] = $this->serializer->toQueryValue($enum_query_integer); } +/** // header params if (is_array($enum_header_string_array)) { $enum_header_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_header_string_array, 'csv'); @@ -506,12 +510,14 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ if ($enum_header_string_array !== null) { $headerParams['enum_header_string_array'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string_array); } +*/ +/** // header params if ($enum_header_string !== null) { $headerParams['enum_header_string'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string); } +*/ - */ // form params if ($enum_form_string_array !== null) { @@ -541,10 +547,12 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index c81791b0d55..8afe550728f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -29,6 +29,7 @@ namespace Swagger\Client\Api; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -100,6 +101,7 @@ public function addPetWithHttpInfo($body) $resourcePath = substr('/pet', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -108,9 +110,7 @@ public function addPetWithHttpInfo($body) ); -/** - */ // body params $_tempBody = null; @@ -131,10 +131,12 @@ public function addPetWithHttpInfo($body) } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -200,6 +202,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $resourcePath = substr('/pet/{petId}', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -213,8 +216,8 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) if ($api_key !== null) { $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); } +*/ - */ // path params if ($pet_id !== null) { $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); @@ -234,10 +237,12 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'DELETE', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -301,6 +306,7 @@ public function findPetsByStatusWithHttpInfo($status) $resourcePath = substr('/pet/findByStatus', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -309,16 +315,14 @@ public function findPetsByStatusWithHttpInfo($status) ); -/** // query params if (is_array($status)) { - $status = $this->apiClient->getSerializer()->serializeCollection($status, 'csv', true); + $status = $this->serializer->serializeCollection($status, 'csv', true); } if ($status !== null) { - $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); + $queryParams['status'] = $this->serializer->toQueryValue($status); } - */ // for model (json/xml) @@ -334,10 +338,12 @@ public function findPetsByStatusWithHttpInfo($status) } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -410,6 +416,7 @@ public function findPetsByTagsWithHttpInfo($tags) $resourcePath = substr('/pet/findByTags', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -418,16 +425,14 @@ public function findPetsByTagsWithHttpInfo($tags) ); -/** // query params if (is_array($tags)) { - $tags = $this->apiClient->getSerializer()->serializeCollection($tags, 'csv', true); + $tags = $this->serializer->serializeCollection($tags, 'csv', true); } if ($tags !== null) { - $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); + $queryParams['tags'] = $this->serializer->toQueryValue($tags); } - */ // for model (json/xml) @@ -443,10 +448,12 @@ public function findPetsByTagsWithHttpInfo($tags) } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -519,6 +526,7 @@ public function getPetByIdWithHttpInfo($pet_id) $resourcePath = substr('/pet/{petId}', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -527,9 +535,7 @@ public function getPetByIdWithHttpInfo($pet_id) ); -/** - */ // path params if ($pet_id !== null) { $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); @@ -550,10 +556,12 @@ public function getPetByIdWithHttpInfo($pet_id) } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -626,6 +634,7 @@ public function updatePetWithHttpInfo($body) $resourcePath = substr('/pet', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -634,9 +643,7 @@ public function updatePetWithHttpInfo($body) ); -/** - */ // body params $_tempBody = null; @@ -657,10 +664,12 @@ public function updatePetWithHttpInfo($body) } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'PUT', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -728,6 +737,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $resourcePath = substr('/pet/{petId}', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -736,9 +746,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n ); -/** - */ // path params if ($pet_id !== null) { $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); @@ -770,10 +778,12 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -841,6 +851,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $resourcePath = substr('/pet/{petId}/uploadImage', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -849,9 +860,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi ); -/** - */ // path params if ($pet_id !== null) { $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); @@ -889,10 +898,12 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 04dee1f42b8..2a2158352f5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -29,6 +29,7 @@ namespace Swagger\Client\Api; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -103,6 +104,7 @@ public function deleteOrderWithHttpInfo($order_id) $queryParams = []; $headerParams = []; $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -111,9 +113,7 @@ public function deleteOrderWithHttpInfo($order_id) ); -/** - */ // path params if ($order_id !== null) { $resourcePath = str_replace( @@ -133,10 +133,12 @@ public function deleteOrderWithHttpInfo($order_id) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'DELETE', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -194,6 +196,7 @@ public function getInventoryWithHttpInfo() $resourcePath = substr('/store/inventory', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -202,9 +205,7 @@ public function getInventoryWithHttpInfo() ); -/** - */ // for model (json/xml) @@ -221,10 +222,12 @@ public function getInventoryWithHttpInfo() } */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -307,6 +310,7 @@ public function getOrderByIdWithHttpInfo($order_id) $queryParams = []; $headerParams = []; $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -315,9 +319,7 @@ public function getOrderByIdWithHttpInfo($order_id) ); -/** - */ // path params if ($order_id !== null) { $resourcePath = str_replace( @@ -337,10 +339,12 @@ public function getOrderByIdWithHttpInfo($order_id) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -413,6 +417,7 @@ public function placeOrderWithHttpInfo($body) $resourcePath = substr('/store/order', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -421,9 +426,7 @@ public function placeOrderWithHttpInfo($body) ); -/** - */ // body params $_tempBody = null; @@ -440,10 +443,12 @@ public function placeOrderWithHttpInfo($body) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 5097034e52d..36d76d0b318 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -29,6 +29,7 @@ namespace Swagger\Client\Api; use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -100,6 +101,7 @@ public function createUserWithHttpInfo($body) $resourcePath = substr('/user', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -108,9 +110,7 @@ public function createUserWithHttpInfo($body) ); -/** - */ // body params $_tempBody = null; @@ -127,10 +127,12 @@ public function createUserWithHttpInfo($body) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -194,6 +196,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) $resourcePath = substr('/user/createWithArray', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -202,9 +205,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) ); -/** - */ // body params $_tempBody = null; @@ -221,10 +222,12 @@ public function createUsersWithArrayInputWithHttpInfo($body) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -288,6 +291,7 @@ public function createUsersWithListInputWithHttpInfo($body) $resourcePath = substr('/user/createWithList', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -296,9 +300,7 @@ public function createUsersWithListInputWithHttpInfo($body) ); -/** - */ // body params $_tempBody = null; @@ -315,10 +317,12 @@ public function createUsersWithListInputWithHttpInfo($body) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'POST', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -382,6 +386,7 @@ public function deleteUserWithHttpInfo($username) $resourcePath = substr('/user/{username}', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -390,9 +395,7 @@ public function deleteUserWithHttpInfo($username) ); -/** - */ // path params if ($username !== null) { $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); @@ -408,10 +411,12 @@ public function deleteUserWithHttpInfo($username) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'DELETE', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -475,6 +480,7 @@ public function getUserByNameWithHttpInfo($username) $resourcePath = substr('/user/{username}', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -483,9 +489,7 @@ public function getUserByNameWithHttpInfo($username) ); -/** - */ // path params if ($username !== null) { $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); @@ -501,10 +505,12 @@ public function getUserByNameWithHttpInfo($username) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -583,6 +589,7 @@ public function loginUserWithHttpInfo($username, $password) $resourcePath = substr('/user/login', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -591,17 +598,15 @@ public function loginUserWithHttpInfo($username, $password) ); -/** // query params if ($username !== null) { - $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); + $queryParams['username'] = $this->serializer->toQueryValue($username); } // query params if ($password !== null) { - $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); + $queryParams['password'] = $this->serializer->toQueryValue($password); } - */ // for model (json/xml) @@ -613,10 +618,12 @@ public function loginUserWithHttpInfo($username, $password) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -683,6 +690,7 @@ public function logoutUserWithHttpInfo() $resourcePath = substr('/user/logout', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -691,9 +699,7 @@ public function logoutUserWithHttpInfo() ); -/** - */ // for model (json/xml) @@ -705,10 +711,12 @@ public function logoutUserWithHttpInfo() /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'GET', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); @@ -778,6 +786,7 @@ public function updateUserWithHttpInfo($username, $body) $resourcePath = substr('/user/{username}', 1); $formParams = []; + $queryParams = []; $httpBody= ''; $headers = $this->headerSelector->selectHeaders( @@ -786,9 +795,7 @@ public function updateUserWithHttpInfo($username, $body) ); -/** - */ // path params if ($username !== null) { $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); @@ -809,10 +816,12 @@ public function updateUserWithHttpInfo($username, $body) /** */ + $query = http_build_query($queryParams); + try { $request = new Request( 'PUT', - $resourcePath, + Uri::composeComponents('', '', $resourcePath, $query, ''), $headers, $httpBody ); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index cd598d27ddc..72f13762663 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -131,21 +131,17 @@ public function testGetPetByIdWithHttpInfo() // test getPetByStatus and verify by the "id" of the response public function testFindPetByStatus() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_api = new Api\PetApi($api_client); - // return Pet (model) - $response = $pet_api->findPetsByStatus("available"); + $response = $this->api->findPetsByStatus(['available']); $this->assertGreaterThan(0, count($response)); // at least one object returned - $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet + + $this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet // loop through result to ensure status is "available" foreach ($response as $_pet) { - $this->assertSame($_pet['status'], "available"); + $this->assertSame($_pet['status'], 'available'); } // test invalid status - $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); - $this->assertSame(count($response), 0); // confirm no object returned + $response = $this->api->findPetsByStatus('unknown_and_incorrect_status'); + $this->assertCount(0, $response); // confirm no object returned } // test getPetsByTags and verify by the "id" of the response From 2147b5e27869ffde0f0619c8d00764195e2bb8f2 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Wed, 15 Mar 2017 14:06:42 +0000 Subject: [PATCH 04/37] removed constant reference to model class --- modules/swagger-codegen/src/main/resources/php/api.mustache | 1 - .../client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php | 1 - samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php | 1 - .../client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php | 1 - .../client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php | 1 - 5 files changed, 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 7ed6662064c..c43b1ab18e2 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -24,7 +24,6 @@ use Http\Client\Exception; use Http\Client\HttpClient; use {{invokerPackage}}\ApiException; use {{invokerPackage}}\HeaderSelector; -use {{invokerPackage}}\Model\Pet; use {{invokerPackage}}\ObjectSerializer; /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index cc5d14d0a33..ed604f74b4d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -34,7 +34,6 @@ use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\HeaderSelector; -use Swagger\Client\Model\Pet; use Swagger\Client\ObjectSerializer; /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 8afe550728f..c7fce42016d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -34,7 +34,6 @@ use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\HeaderSelector; -use Swagger\Client\Model\Pet; use Swagger\Client\ObjectSerializer; /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 2a2158352f5..d454cf93b3f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -34,7 +34,6 @@ use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\HeaderSelector; -use Swagger\Client\Model\Pet; use Swagger\Client\ObjectSerializer; /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 36d76d0b318..496d4227c83 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -34,7 +34,6 @@ use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\HeaderSelector; -use Swagger\Client\Model\Pet; use Swagger\Client\ObjectSerializer; /** From f360c7aabd53c6506682a67a2847019a1ce787f1 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Wed, 15 Mar 2017 14:25:02 +0000 Subject: [PATCH 05/37] some extra @throws; form params --- .../src/main/resources/php/api.mustache | 9 ++- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 47 ++++++----- .../php/SwaggerClient-php/lib/Api/PetApi.php | 38 +++++---- .../SwaggerClient-php/lib/Api/StoreApi.php | 14 ++-- .../php/SwaggerClient-php/lib/Api/UserApi.php | 36 +++++---- .../SwaggerClient-php/tests/PetApiTest.php | 80 +++++++------------ 6 files changed, 116 insertions(+), 108 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index c43b1ab18e2..b4402b7b3e8 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -70,11 +70,12 @@ use {{invokerPackage}}\ObjectSerializer; * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @throws \{{invokerPackage}}\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - list($response) = $this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{#returnType}}return $response;{{/returnType}} } @@ -91,7 +92,7 @@ use {{invokerPackage}}\ObjectSerializer; * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}} * @throws \{{invokerPackage}}\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) */ public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) @@ -182,9 +183,11 @@ use {{invokerPackage}}\ObjectSerializer; {{#pathParams}} // path params {{#collectionFormat}} + /** if (is_array(${{paramName}})) { ${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}'); } + */ {{/collectionFormat}} if (${{paramName}} !== null) { $resourcePath = str_replace('{' . '{{baseName}}' . '}', $this->serializer->toPathValue(${{paramName}}), $resourcePath); @@ -206,7 +209,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/isFile}} */ {{^isFile}} - $formParams['{{baseName}}'] = $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = $this->serializer->toFormValue(${{paramName}}); {{/isFile}} } {{/formParams}} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index ed604f74b4d..af7343c3510 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -73,6 +73,7 @@ public function __construct(HttpClient $client, HeaderSelector $selector = null) * * @param \Swagger\Client\Model\Client $body client model (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\Client */ public function testClientModel($body) @@ -88,7 +89,7 @@ public function testClientModel($body) * * @param \Swagger\Client\Model\Client $body client model (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ public function testClientModelWithHttpInfo($body) @@ -190,11 +191,12 @@ public function testClientModelWithHttpInfo($body) * @param string $password None (optional) * @param string $callback None (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) { - list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); + $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); } @@ -218,7 +220,7 @@ public function testEndpointParameters($number, $double, $pattern_without_delimi * @param string $password None (optional) * @param string $callback None (optional) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) @@ -304,85 +306,85 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if ($integer !== null) { /** */ - $formParams['integer'] = $this->apiClient->getSerializer()->toFormValue($integer); + $formParams['integer'] = $this->serializer->toFormValue($integer); } // form params if ($int32 !== null) { /** */ - $formParams['int32'] = $this->apiClient->getSerializer()->toFormValue($int32); + $formParams['int32'] = $this->serializer->toFormValue($int32); } // form params if ($int64 !== null) { /** */ - $formParams['int64'] = $this->apiClient->getSerializer()->toFormValue($int64); + $formParams['int64'] = $this->serializer->toFormValue($int64); } // form params if ($number !== null) { /** */ - $formParams['number'] = $this->apiClient->getSerializer()->toFormValue($number); + $formParams['number'] = $this->serializer->toFormValue($number); } // form params if ($float !== null) { /** */ - $formParams['float'] = $this->apiClient->getSerializer()->toFormValue($float); + $formParams['float'] = $this->serializer->toFormValue($float); } // form params if ($double !== null) { /** */ - $formParams['double'] = $this->apiClient->getSerializer()->toFormValue($double); + $formParams['double'] = $this->serializer->toFormValue($double); } // form params if ($string !== null) { /** */ - $formParams['string'] = $this->apiClient->getSerializer()->toFormValue($string); + $formParams['string'] = $this->serializer->toFormValue($string); } // form params if ($pattern_without_delimiter !== null) { /** */ - $formParams['pattern_without_delimiter'] = $this->apiClient->getSerializer()->toFormValue($pattern_without_delimiter); + $formParams['pattern_without_delimiter'] = $this->serializer->toFormValue($pattern_without_delimiter); } // form params if ($byte !== null) { /** */ - $formParams['byte'] = $this->apiClient->getSerializer()->toFormValue($byte); + $formParams['byte'] = $this->serializer->toFormValue($byte); } // form params if ($binary !== null) { /** */ - $formParams['binary'] = $this->apiClient->getSerializer()->toFormValue($binary); + $formParams['binary'] = $this->serializer->toFormValue($binary); } // form params if ($date !== null) { /** */ - $formParams['date'] = $this->apiClient->getSerializer()->toFormValue($date); + $formParams['date'] = $this->serializer->toFormValue($date); } // form params if ($date_time !== null) { /** */ - $formParams['dateTime'] = $this->apiClient->getSerializer()->toFormValue($date_time); + $formParams['dateTime'] = $this->serializer->toFormValue($date_time); } // form params if ($password !== null) { /** */ - $formParams['password'] = $this->apiClient->getSerializer()->toFormValue($password); + $formParams['password'] = $this->serializer->toFormValue($password); } // form params if ($callback !== null) { /** */ - $formParams['callback'] = $this->apiClient->getSerializer()->toFormValue($callback); + $formParams['callback'] = $this->serializer->toFormValue($callback); } // for model (json/xml) @@ -447,11 +449,12 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi * @param int $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function testEnumParameters($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { - list($response) = $this->testEnumParametersWithHttpInfo($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); + $this->testEnumParametersWithHttpInfo($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); } @@ -469,7 +472,7 @@ public function testEnumParameters($enum_form_string_array = null, $enum_form_st * @param int $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) @@ -522,19 +525,19 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ if ($enum_form_string_array !== null) { /** */ - $formParams['enum_form_string_array'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string_array); + $formParams['enum_form_string_array'] = $this->serializer->toFormValue($enum_form_string_array); } // form params if ($enum_form_string !== null) { /** */ - $formParams['enum_form_string'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string); + $formParams['enum_form_string'] = $this->serializer->toFormValue($enum_form_string); } // form params if ($enum_query_double !== null) { /** */ - $formParams['enum_query_double'] = $this->apiClient->getSerializer()->toFormValue($enum_query_double); + $formParams['enum_query_double'] = $this->serializer->toFormValue($enum_query_double); } // for model (json/xml) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index c7fce42016d..db6f5589cd6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -73,11 +73,12 @@ public function __construct(HttpClient $client, HeaderSelector $selector = null) * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function addPet($body) { - list($response) = $this->addPetWithHttpInfo($body); + $this->addPetWithHttpInfo($body); } @@ -88,7 +89,7 @@ public function addPet($body) * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function addPetWithHttpInfo($body) @@ -173,11 +174,12 @@ public function addPetWithHttpInfo($body) * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function deletePet($pet_id, $api_key = null) { - list($response) = $this->deletePetWithHttpInfo($pet_id, $api_key); + $this->deletePetWithHttpInfo($pet_id, $api_key); } @@ -189,7 +191,7 @@ public function deletePet($pet_id, $api_key = null) * @param int $pet_id Pet id to delete (required) * @param string $api_key (optional) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deletePetWithHttpInfo($pet_id, $api_key = null) @@ -278,6 +280,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) * * @param string[] $status Status values that need to be considered for filter (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\Pet[] */ public function findPetsByStatus($status) @@ -293,7 +296,7 @@ public function findPetsByStatus($status) * * @param string[] $status Status values that need to be considered for filter (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByStatusWithHttpInfo($status) @@ -388,6 +391,7 @@ public function findPetsByStatusWithHttpInfo($status) * * @param string[] $tags Tags to filter by (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\Pet[] */ public function findPetsByTags($tags) @@ -403,7 +407,7 @@ public function findPetsByTags($tags) * * @param string[] $tags Tags to filter by (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByTagsWithHttpInfo($tags) @@ -498,6 +502,7 @@ public function findPetsByTagsWithHttpInfo($tags) * * @param int $pet_id ID of pet to return (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\Pet */ public function getPetById($pet_id) @@ -513,7 +518,7 @@ public function getPetById($pet_id) * * @param int $pet_id ID of pet to return (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ public function getPetByIdWithHttpInfo($pet_id) @@ -606,11 +611,12 @@ public function getPetByIdWithHttpInfo($pet_id) * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function updatePet($body) { - list($response) = $this->updatePetWithHttpInfo($body); + $this->updatePetWithHttpInfo($body); } @@ -621,7 +627,7 @@ public function updatePet($body) * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithHttpInfo($body) @@ -707,11 +713,12 @@ public function updatePetWithHttpInfo($body) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function updatePetWithForm($pet_id, $name = null, $status = null) { - list($response) = $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); + $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); } @@ -724,7 +731,7 @@ public function updatePetWithForm($pet_id, $name = null, $status = null) * @param string $name Updated name of the pet (optional) * @param string $status Updated status of the pet (optional) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) @@ -755,13 +762,13 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n if ($name !== null) { /** */ - $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); + $formParams['name'] = $this->serializer->toFormValue($name); } // form params if ($status !== null) { /** */ - $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); + $formParams['status'] = $this->serializer->toFormValue($status); } // for model (json/xml) @@ -821,6 +828,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\ApiResponse */ public function uploadFile($pet_id, $additional_metadata = null, $file = null) @@ -838,7 +846,7 @@ public function uploadFile($pet_id, $additional_metadata = null, $file = null) * @param string $additional_metadata Additional data to pass to server (optional) * @param \SplFileObject $file file to upload (optional) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) */ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) @@ -869,7 +877,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi if ($additional_metadata !== null) { /** */ - $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); + $formParams['additionalMetadata'] = $this->serializer->toFormValue($additional_metadata); } // form params if ($file !== null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index d454cf93b3f..d1ad18c5860 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -73,11 +73,12 @@ public function __construct(HttpClient $client, HeaderSelector $selector = null) * * @param string $order_id ID of the order that needs to be deleted (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function deleteOrder($order_id) { - list($response) = $this->deleteOrderWithHttpInfo($order_id); + $this->deleteOrderWithHttpInfo($order_id); } @@ -88,7 +89,7 @@ public function deleteOrder($order_id) * * @param string $order_id ID of the order that needs to be deleted (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deleteOrderWithHttpInfo($order_id) @@ -173,6 +174,7 @@ public function deleteOrderWithHttpInfo($order_id) * Returns pet inventories by status * * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return map[string,int] */ public function getInventory() @@ -187,7 +189,7 @@ public function getInventory() * Returns pet inventories by status * * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of map[string,int], HTTP status code, HTTP response headers (array of strings) */ public function getInventoryWithHttpInfo() @@ -272,6 +274,7 @@ public function getInventoryWithHttpInfo() * * @param int $order_id ID of pet that needs to be fetched (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\Order */ public function getOrderById($order_id) @@ -287,7 +290,7 @@ public function getOrderById($order_id) * * @param int $order_id ID of pet that needs to be fetched (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function getOrderByIdWithHttpInfo($order_id) @@ -389,6 +392,7 @@ public function getOrderByIdWithHttpInfo($order_id) * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\Order */ public function placeOrder($body) @@ -404,7 +408,7 @@ public function placeOrder($body) * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function placeOrderWithHttpInfo($body) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 496d4227c83..a46783d63e0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -73,11 +73,12 @@ public function __construct(HttpClient $client, HeaderSelector $selector = null) * * @param \Swagger\Client\Model\User $body Created user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function createUser($body) { - list($response) = $this->createUserWithHttpInfo($body); + $this->createUserWithHttpInfo($body); } @@ -88,7 +89,7 @@ public function createUser($body) * * @param \Swagger\Client\Model\User $body Created user object (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUserWithHttpInfo($body) @@ -168,11 +169,12 @@ public function createUserWithHttpInfo($body) * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function createUsersWithArrayInput($body) { - list($response) = $this->createUsersWithArrayInputWithHttpInfo($body); + $this->createUsersWithArrayInputWithHttpInfo($body); } @@ -183,7 +185,7 @@ public function createUsersWithArrayInput($body) * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUsersWithArrayInputWithHttpInfo($body) @@ -263,11 +265,12 @@ public function createUsersWithArrayInputWithHttpInfo($body) * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function createUsersWithListInput($body) { - list($response) = $this->createUsersWithListInputWithHttpInfo($body); + $this->createUsersWithListInputWithHttpInfo($body); } @@ -278,7 +281,7 @@ public function createUsersWithListInput($body) * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function createUsersWithListInputWithHttpInfo($body) @@ -358,11 +361,12 @@ public function createUsersWithListInputWithHttpInfo($body) * * @param string $username The name that needs to be deleted (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function deleteUser($username) { - list($response) = $this->deleteUserWithHttpInfo($username); + $this->deleteUserWithHttpInfo($username); } @@ -373,7 +377,7 @@ public function deleteUser($username) * * @param string $username The name that needs to be deleted (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function deleteUserWithHttpInfo($username) @@ -452,6 +456,7 @@ public function deleteUserWithHttpInfo($username) * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\User */ public function getUserByName($username) @@ -467,7 +472,7 @@ public function getUserByName($username) * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) */ public function getUserByNameWithHttpInfo($username) @@ -556,6 +561,7 @@ public function getUserByNameWithHttpInfo($username) * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return string */ public function loginUser($username, $password) @@ -572,7 +578,7 @@ public function loginUser($username, $password) * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ public function loginUserWithHttpInfo($username, $password) @@ -667,11 +673,12 @@ public function loginUserWithHttpInfo($username, $password) * Logs out current logged in user session * * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function logoutUser() { - list($response) = $this->logoutUserWithHttpInfo(); + $this->logoutUserWithHttpInfo(); } @@ -681,7 +688,7 @@ public function logoutUser() * Logs out current logged in user session * * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function logoutUserWithHttpInfo() @@ -753,11 +760,12 @@ public function logoutUserWithHttpInfo() * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function updateUser($username, $body) { - list($response) = $this->updateUserWithHttpInfo($username, $body); + $this->updateUserWithHttpInfo($username, $body); } @@ -769,7 +777,7 @@ public function updateUser($username, $body) * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) * @throws \Swagger\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException when invalid arguments provided + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function updateUserWithHttpInfo($username, $body) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 72f13762663..c9ae70fc6ce 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -128,85 +128,67 @@ public function testGetPetByIdWithHttpInfo() $this->assertSame($response_headers['Content-Type'], ['application/json']); } - // test getPetByStatus and verify by the "id" of the response public function testFindPetByStatus() { - $response = $this->api->findPetsByStatus(['available']); + $response = $this->api->findPetsByStatus('available'); $this->assertGreaterThan(0, count($response)); // at least one object returned $this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet - // loop through result to ensure status is "available" - foreach ($response as $_pet) { - $this->assertSame($_pet['status'], 'available'); + foreach ($response as $pet) { + $this->assertSame($pet['status'], 'available'); } - // test invalid status + $response = $this->api->findPetsByStatus('unknown_and_incorrect_status'); - $this->assertCount(0, $response); // confirm no object returned + $this->assertCount(0, $response); } - // test getPetsByTags and verify by the "id" of the response public function testFindPetsByTags() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_api = new Api\PetApi($api_client); - // return Pet (model) - $response = $pet_api->findPetsByTags("test php tag"); + $response = $this->api->findPetsByTags('test php tag'); $this->assertGreaterThan(0, count($response)); // at least one object returned - $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" - foreach ($response as $_pet) { - $this->assertSame($_pet['tags'][0]['name'], "test php tag"); + $this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet + + foreach ($response as $pet) { + $this->assertSame($pet['tags'][0]['name'], 'test php tag'); } - // test invalid status - $response = $pet_api->findPetsByTags("unknown_and_incorrect_tag"); - $this->assertSame(count($response), 0); // confirm no object returned + + $response = $this->api->findPetsByTags('unknown_and_incorrect_tag'); + $this->assertCount(0, $response); } - // test updatePet (model/json)and verify by the "id" of the response public function testUpdatePet() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi($api_client); - // create updated pet object - $updated_pet = new Model\Pet; - $updated_pet->setId($pet_id); - $updated_pet->setName('updatePet'); // new name - $updated_pet->setStatus('pending'); // new status - // update Pet (model/json) - $update_response = $pet_api->updatePet($updated_pet); - // return nothing (void) - $this->assertSame($update_response, null); + $petId = 10001; + $updatedPet = new Model\Pet; + $updatedPet->setId($petId); + $updatedPet->setName('updatePet'); + $updatedPet->setStatus('pending'); + $result = $this->api->updatePet($updatedPet); + $this->assertNull($result); + // verify updated Pet - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getStatus(), 'pending'); - $this->assertSame($response->getName(), 'updatePet'); + $result = $this->api->getPetById($petId); + $this->assertSame($result->getId(), $petId); + $this->assertSame($result->getStatus(), 'pending'); + $this->assertSame($result->getName(), 'updatePet'); } // test updatePetWithFormWithHttpInfo and verify by the "name" of the response public function testUpdatePetWithFormWithHttpInfo() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi($api_client); + $petId = 10001; // ID of pet that needs to be fetched + // update Pet (form) - list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo( - $pet_id, + list($update_response, $status_code, $http_headers) = $this->api->updatePetWithFormWithHttpInfo( + $petId, 'update pet with form with http info' ); // return nothing (void) $this->assertNull($update_response); $this->assertSame($status_code, 200); $this->assertSame($http_headers['Content-Type'], 'application/json'); - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); + $response = $this->api->getPetById($petId); + $this->assertSame($response->getId(), $petId); $this->assertSame($response->getName(), 'update pet with form with http info'); } From d08fdcf25c1d273793ea7ceb1d93d896ec728f6e Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 16 Mar 2017 09:47:57 +0000 Subject: [PATCH 06/37] form and query params encoding --- .../src/main/resources/php/api.mustache | 9 ++-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 17 +++---- .../php/SwaggerClient-php/lib/Api/PetApi.php | 44 +++++++----------- .../SwaggerClient-php/lib/Api/StoreApi.php | 21 ++++----- .../php/SwaggerClient-php/lib/Api/UserApi.php | 46 +++++++------------ .../SwaggerClient-php/tests/PetApiTest.php | 32 ++++++------- 6 files changed, 63 insertions(+), 106 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index b4402b7b3e8..efdf630ae28 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -75,8 +75,8 @@ use {{invokerPackage}}\ObjectSerializer; */ public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - {{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - {{#returnType}}return $response;{{/returnType}} + {{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return $response;{{/returnType}} } /** @@ -224,7 +224,7 @@ use {{invokerPackage}}\ObjectSerializer; if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** {{#authMethods}} @@ -249,8 +249,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/isOAuth}} {{/authMethods}} */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index af7343c3510..6e4d5d8a438 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -122,12 +122,11 @@ public function testClientModelWithHttpInfo($body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -197,7 +196,6 @@ public function testClientModelWithHttpInfo($body) public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null) { $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); - } /** @@ -391,7 +389,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires HTTP basic authentication @@ -399,8 +397,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -455,7 +452,6 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi public function testEnumParameters($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { $this->testEnumParametersWithHttpInfo($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); - } /** @@ -544,12 +540,11 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index db6f5589cd6..93f58a6a8ff 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -79,7 +79,6 @@ public function __construct(HttpClient $client, HeaderSelector $selector = null) public function addPet($body) { $this->addPetWithHttpInfo($body); - } /** @@ -122,7 +121,7 @@ public function addPetWithHttpInfo($body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires OAuth (access token) @@ -130,8 +129,7 @@ public function addPetWithHttpInfo($body) $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -180,7 +178,6 @@ public function addPetWithHttpInfo($body) public function deletePet($pet_id, $api_key = null) { $this->deletePetWithHttpInfo($pet_id, $api_key); - } /** @@ -229,7 +226,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires OAuth (access token) @@ -237,8 +234,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -331,7 +327,7 @@ public function findPetsByStatusWithHttpInfo($status) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires OAuth (access token) @@ -339,8 +335,7 @@ public function findPetsByStatusWithHttpInfo($status) $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -442,7 +437,7 @@ public function findPetsByTagsWithHttpInfo($tags) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires OAuth (access token) @@ -450,8 +445,7 @@ public function findPetsByTagsWithHttpInfo($tags) $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -550,7 +544,7 @@ public function getPetByIdWithHttpInfo($pet_id) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires API key authentication @@ -559,8 +553,7 @@ public function getPetByIdWithHttpInfo($pet_id) $headerParams['api_key'] = $apiKey; } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -617,7 +610,6 @@ public function getPetByIdWithHttpInfo($pet_id) public function updatePet($body) { $this->updatePetWithHttpInfo($body); - } /** @@ -660,7 +652,7 @@ public function updatePetWithHttpInfo($body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires OAuth (access token) @@ -668,8 +660,7 @@ public function updatePetWithHttpInfo($body) $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -719,7 +710,6 @@ public function updatePetWithHttpInfo($body) public function updatePetWithForm($pet_id, $name = null, $status = null) { $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); - } /** @@ -775,7 +765,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires OAuth (access token) @@ -783,8 +773,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -896,7 +885,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires OAuth (access token) @@ -904,8 +893,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index d1ad18c5860..60b9e21208e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -79,7 +79,6 @@ public function __construct(HttpClient $client, HeaderSelector $selector = null) public function deleteOrder($order_id) { $this->deleteOrderWithHttpInfo($order_id); - } /** @@ -128,12 +127,11 @@ public function deleteOrderWithHttpInfo($order_id) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -213,7 +211,7 @@ public function getInventoryWithHttpInfo() if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** // this endpoint requires API key authentication @@ -222,8 +220,7 @@ public function getInventoryWithHttpInfo() $headerParams['api_key'] = $apiKey; } */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -336,12 +333,11 @@ public function getOrderByIdWithHttpInfo($order_id) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -441,12 +437,11 @@ public function placeOrderWithHttpInfo($body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index a46783d63e0..13c5b097607 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -79,7 +79,6 @@ public function __construct(HttpClient $client, HeaderSelector $selector = null) public function createUser($body) { $this->createUserWithHttpInfo($body); - } /** @@ -122,12 +121,11 @@ public function createUserWithHttpInfo($body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -175,7 +173,6 @@ public function createUserWithHttpInfo($body) public function createUsersWithArrayInput($body) { $this->createUsersWithArrayInputWithHttpInfo($body); - } /** @@ -218,12 +215,11 @@ public function createUsersWithArrayInputWithHttpInfo($body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -271,7 +267,6 @@ public function createUsersWithArrayInputWithHttpInfo($body) public function createUsersWithListInput($body) { $this->createUsersWithListInputWithHttpInfo($body); - } /** @@ -314,12 +309,11 @@ public function createUsersWithListInputWithHttpInfo($body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -367,7 +361,6 @@ public function createUsersWithListInputWithHttpInfo($body) public function deleteUser($username) { $this->deleteUserWithHttpInfo($username); - } /** @@ -409,12 +402,11 @@ public function deleteUserWithHttpInfo($username) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -504,12 +496,11 @@ public function getUserByNameWithHttpInfo($username) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -618,12 +609,11 @@ public function loginUserWithHttpInfo($username, $password) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -679,7 +669,6 @@ public function loginUserWithHttpInfo($username, $password) public function logoutUser() { $this->logoutUserWithHttpInfo(); - } /** @@ -712,12 +701,11 @@ public function logoutUserWithHttpInfo() if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -766,7 +754,6 @@ public function logoutUserWithHttpInfo() public function updateUser($username, $body) { $this->updateUserWithHttpInfo($username, $body); - } /** @@ -818,12 +805,11 @@ public function updateUserWithHttpInfo($username, $body) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } /** */ - - $query = http_build_query($queryParams); + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index c9ae70fc6ce..59dd03aea61 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -186,7 +186,7 @@ public function testUpdatePetWithFormWithHttpInfo() // return nothing (void) $this->assertNull($update_response); $this->assertSame($status_code, 200); - $this->assertSame($http_headers['Content-Type'], 'application/json'); + $this->assertSame($http_headers['Content-Type'], ['application/json']); $response = $this->api->getPetById($petId); $this->assertSame($response->getId(), $petId); $this->assertSame($response->getName(), 'update pet with form with http info'); @@ -195,16 +195,12 @@ public function testUpdatePetWithFormWithHttpInfo() // test updatePetWithForm and verify by the "name" and "status" of the response public function testUpdatePetWithForm() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi($api_client); - // update Pet (form) - $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); + $result = $this->api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) - $this->assertSame($update_response, null); - $response = $pet_api->getPetById($pet_id); + $this->assertNull($result); + + $response = $this->api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getName(), 'update pet with form'); $this->assertSame($response->getStatus(), 'sold'); @@ -213,20 +209,18 @@ public function testUpdatePetWithForm() // test addPet and verify by the "id" and "name" of the response public function testAddPet() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); $new_pet_id = 10005; - $new_pet = new Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test 2"); - $pet_api = new Api\PetApi($api_client); + $newPet = new Model\Pet; + $newPet->setId($new_pet_id); + $newPet->setName("PHP Unit Test 2"); + // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); + $add_response = $this->api->addPet($newPet); // return nothing (void) - $this->assertSame($add_response, null); + $this->assertNull($add_response); + // verify added Pet - $response = $pet_api->getPetById($new_pet_id); + $response = $this->api->getPetById($new_pet_id); $this->assertSame($response->getId(), $new_pet_id); $this->assertSame($response->getName(), 'PHP Unit Test 2'); } From e08bb6c64238e7f7ddfda68cf20dcd9380ee4a6d Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 17 Mar 2017 09:22:21 +0000 Subject: [PATCH 07/37] file upload / form multipart --- .../src/main/resources/php/api.mustache | 44 +-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 131 +++++---- .../php/SwaggerClient-php/lib/Api/PetApi.php | 274 +++++++++++++----- .../SwaggerClient-php/lib/Api/StoreApi.php | 129 +++++++-- .../php/SwaggerClient-php/lib/Api/UserApi.php | 257 ++++++++++++---- .../SwaggerClient-php/tests/PetApiTest.php | 11 +- 6 files changed, 590 insertions(+), 256 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index efdf630ae28..e069639ecde 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -18,6 +18,7 @@ namespace {{apiPackage}}; +use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; @@ -147,13 +148,8 @@ use {{invokerPackage}}\ObjectSerializer; $resourcePath = substr('{{{path}}}', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}], - [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - ); - + $httpBody = ''; + $multipart = false; {{#queryParams}} // query params @@ -197,17 +193,10 @@ use {{invokerPackage}}\ObjectSerializer; {{#formParams}} // form params if (${{paramName}} !== null) { - /** {{#isFile}} - // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax - // See: https://wiki.php.net/rfc/curl-file-upload - if (function_exists('curl_file_create')) { - $formParams['{{baseName}}'] = curl_file_create($this->apiClient->getSerializer()->toFormValue(${{paramName}})); - } else { - $formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}}); - } + $multipart = true; + $formParams['file'] = \GuzzleHttp\Psr7\try_fopen($this->serializer->toFormValue($file), 'rb'); {{/isFile}} - */ {{^isFile}} $formParams['{{baseName}}'] = $this->serializer->toFormValue(${{paramName}}); {{/isFile}} @@ -223,8 +212,21 @@ use {{invokerPackage}}\ObjectSerializer; // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** {{#authMethods}} @@ -251,6 +253,14 @@ use {{invokerPackage}}\ObjectSerializer; */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}], + [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( '{{httpMethod}}', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 6e4d5d8a438..113fecb5474 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -28,6 +28,7 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; @@ -102,13 +103,8 @@ public function testClientModelWithHttpInfo($body) $resourcePath = substr('/fake', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/json'], - ['application/json'] - ); - + $httpBody = ''; + $multipart = false; @@ -121,13 +117,34 @@ public function testClientModelWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'PATCH', @@ -290,106 +307,86 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $resourcePath = substr('/fake', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml; charset=utf-8', 'application/json; charset=utf-8'], - ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] - ); - + $httpBody = ''; + $multipart = false; // form params if ($integer !== null) { - /** - */ $formParams['integer'] = $this->serializer->toFormValue($integer); } // form params if ($int32 !== null) { - /** - */ $formParams['int32'] = $this->serializer->toFormValue($int32); } // form params if ($int64 !== null) { - /** - */ $formParams['int64'] = $this->serializer->toFormValue($int64); } // form params if ($number !== null) { - /** - */ $formParams['number'] = $this->serializer->toFormValue($number); } // form params if ($float !== null) { - /** - */ $formParams['float'] = $this->serializer->toFormValue($float); } // form params if ($double !== null) { - /** - */ $formParams['double'] = $this->serializer->toFormValue($double); } // form params if ($string !== null) { - /** - */ $formParams['string'] = $this->serializer->toFormValue($string); } // form params if ($pattern_without_delimiter !== null) { - /** - */ $formParams['pattern_without_delimiter'] = $this->serializer->toFormValue($pattern_without_delimiter); } // form params if ($byte !== null) { - /** - */ $formParams['byte'] = $this->serializer->toFormValue($byte); } // form params if ($binary !== null) { - /** - */ $formParams['binary'] = $this->serializer->toFormValue($binary); } // form params if ($date !== null) { - /** - */ $formParams['date'] = $this->serializer->toFormValue($date); } // form params if ($date_time !== null) { - /** - */ $formParams['dateTime'] = $this->serializer->toFormValue($date_time); } // form params if ($password !== null) { - /** - */ $formParams['password'] = $this->serializer->toFormValue($password); } // form params if ($callback !== null) { - /** - */ $formParams['callback'] = $this->serializer->toFormValue($callback); } // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires HTTP basic authentication @@ -399,6 +396,14 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml; charset=utf-8', 'application/json; charset=utf-8'], + ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', @@ -477,13 +482,8 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $resourcePath = substr('/fake', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['*/*'], - ['*/*'] - ); - + $httpBody = ''; + $multipart = false; // query params if (is_array($enum_query_string_array)) { @@ -519,33 +519,48 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ // form params if ($enum_form_string_array !== null) { - /** - */ $formParams['enum_form_string_array'] = $this->serializer->toFormValue($enum_form_string_array); } // form params if ($enum_form_string !== null) { - /** - */ $formParams['enum_form_string'] = $this->serializer->toFormValue($enum_form_string); } // form params if ($enum_query_double !== null) { - /** - */ $formParams['enum_query_double'] = $this->serializer->toFormValue($enum_query_double); } // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['*/*'] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 93f58a6a8ff..7ff602b0f1a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -28,6 +28,7 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; @@ -101,13 +102,8 @@ public function addPetWithHttpInfo($body) $resourcePath = substr('/pet', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - ['application/json', 'application/xml'] - ); - + $httpBody = ''; + $multipart = false; @@ -120,8 +116,21 @@ public function addPetWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires OAuth (access token) @@ -131,6 +140,14 @@ public function addPetWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', @@ -201,13 +218,8 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $resourcePath = substr('/pet/{petId}', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; /** // header params @@ -225,8 +237,21 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires OAuth (access token) @@ -236,6 +261,14 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'DELETE', @@ -305,13 +338,8 @@ public function findPetsByStatusWithHttpInfo($status) $resourcePath = substr('/pet/findByStatus', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // query params if (is_array($status)) { @@ -326,8 +354,21 @@ public function findPetsByStatusWithHttpInfo($status) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires OAuth (access token) @@ -337,6 +378,14 @@ public function findPetsByStatusWithHttpInfo($status) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -415,13 +464,8 @@ public function findPetsByTagsWithHttpInfo($tags) $resourcePath = substr('/pet/findByTags', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // query params if (is_array($tags)) { @@ -436,8 +480,21 @@ public function findPetsByTagsWithHttpInfo($tags) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires OAuth (access token) @@ -447,6 +504,14 @@ public function findPetsByTagsWithHttpInfo($tags) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -525,13 +590,8 @@ public function getPetByIdWithHttpInfo($pet_id) $resourcePath = substr('/pet/{petId}', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -543,8 +603,21 @@ public function getPetByIdWithHttpInfo($pet_id) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires API key authentication @@ -555,6 +628,14 @@ public function getPetByIdWithHttpInfo($pet_id) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -632,13 +713,8 @@ public function updatePetWithHttpInfo($body) $resourcePath = substr('/pet', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - ['application/json', 'application/xml'] - ); - + $httpBody = ''; + $multipart = false; @@ -651,8 +727,21 @@ public function updatePetWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires OAuth (access token) @@ -662,6 +751,14 @@ public function updatePetWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'PUT', @@ -734,13 +831,8 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $resourcePath = substr('/pet/{petId}', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - ['application/x-www-form-urlencoded'] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -750,22 +842,31 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n // form params if ($name !== null) { - /** - */ $formParams['name'] = $this->serializer->toFormValue($name); } // form params if ($status !== null) { - /** - */ $formParams['status'] = $this->serializer->toFormValue($status); } // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires OAuth (access token) @@ -775,6 +876,14 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/x-www-form-urlencoded'] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', @@ -848,13 +957,8 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $resourcePath = substr('/pet/{petId}/uploadImage', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/json'], - ['multipart/form-data'] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -864,28 +968,32 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi // form params if ($additional_metadata !== null) { - /** - */ $formParams['additionalMetadata'] = $this->serializer->toFormValue($additional_metadata); } // form params if ($file !== null) { - /** - // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax - // See: https://wiki.php.net/rfc/curl-file-upload - if (function_exists('curl_file_create')) { - $formParams['file'] = curl_file_create($this->apiClient->getSerializer()->toFormValue($file)); - } else { - $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); - } - */ + $multipart = true; + $formParams['file'] = \GuzzleHttp\Psr7\try_fopen($this->serializer->toFormValue($file), 'rb'); } // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires OAuth (access token) @@ -895,6 +1003,14 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['multipart/form-data'] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 60b9e21208e..912607777cf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -28,6 +28,7 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; @@ -104,13 +105,8 @@ public function deleteOrderWithHttpInfo($order_id) $headerParams = []; $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -126,13 +122,34 @@ public function deleteOrderWithHttpInfo($order_id) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'DELETE', @@ -196,13 +213,8 @@ public function getInventoryWithHttpInfo() $resourcePath = substr('/store/inventory', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; @@ -210,8 +222,21 @@ public function getInventoryWithHttpInfo() // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** // this endpoint requires API key authentication @@ -222,6 +247,14 @@ public function getInventoryWithHttpInfo() */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -310,13 +343,8 @@ public function getOrderByIdWithHttpInfo($order_id) $headerParams = []; $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -332,13 +360,34 @@ public function getOrderByIdWithHttpInfo($order_id) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -417,13 +466,8 @@ public function placeOrderWithHttpInfo($body) $resourcePath = substr('/store/order', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; @@ -436,13 +480,34 @@ public function placeOrderWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 13c5b097607..9f4701bf69b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -28,6 +28,7 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; @@ -101,13 +102,8 @@ public function createUserWithHttpInfo($body) $resourcePath = substr('/user', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; @@ -120,13 +116,34 @@ public function createUserWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', @@ -195,13 +212,8 @@ public function createUsersWithArrayInputWithHttpInfo($body) $resourcePath = substr('/user/createWithArray', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; @@ -214,13 +226,34 @@ public function createUsersWithArrayInputWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', @@ -289,13 +322,8 @@ public function createUsersWithListInputWithHttpInfo($body) $resourcePath = substr('/user/createWithList', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; @@ -308,13 +336,34 @@ public function createUsersWithListInputWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'POST', @@ -383,13 +432,8 @@ public function deleteUserWithHttpInfo($username) $resourcePath = substr('/user/{username}', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -401,13 +445,34 @@ public function deleteUserWithHttpInfo($username) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'DELETE', @@ -477,13 +542,8 @@ public function getUserByNameWithHttpInfo($username) $resourcePath = substr('/user/{username}', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -495,13 +555,34 @@ public function getUserByNameWithHttpInfo($username) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -586,13 +667,8 @@ public function loginUserWithHttpInfo($username, $password) $resourcePath = substr('/user/login', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // query params if ($username !== null) { @@ -608,13 +684,34 @@ public function loginUserWithHttpInfo($username, $password) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -686,13 +783,8 @@ public function logoutUserWithHttpInfo() $resourcePath = substr('/user/logout', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; @@ -700,13 +792,34 @@ public function logoutUserWithHttpInfo() // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'GET', @@ -781,13 +894,8 @@ public function updateUserWithHttpInfo($username, $body) $resourcePath = substr('/user/{username}', 1); $formParams = []; $queryParams = []; - $httpBody= ''; - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - + $httpBody = ''; + $multipart = false; // path params @@ -804,13 +912,34 @@ public function updateUserWithHttpInfo($username, $body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } /** */ $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + if ($httpBody instanceof MultipartStream) { + unset($headers['Content-Type']); + } + try { $request = new Request( 'PUT', diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 59dd03aea61..817ceddee06 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -2,8 +2,11 @@ namespace Swagger\Client; +use Guzzle\Http\Message\Request; +use GuzzleHttp\Psr7\MultipartStream; use Http\Adapter\Guzzle6\Client; use Swagger\Client\Api\PetApi; +use Swagger\Client\Model\ApiResponse; use Swagger\Client\Model\Pet; class PetApiTest extends \PHPUnit_Framework_TestCase @@ -269,15 +272,11 @@ public function testAddPetUsingByteArray() // test upload file public function testUploadFile() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_api = new Api\PetApi($api_client); // upload file $pet_id = 10001; - $response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); + $response = $this->api->uploadFile($pet_id, 'test meta', __DIR__ . '/../composer.json'); // return ApiResponse - $this->assertInstanceOf('Swagger\Client\Model\ApiResponse', $response); + $this->assertInstanceOf(ApiResponse::class, $response); } From 2c2b74e27099b43816f118f85646d4f774c4f5ee Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 17 Mar 2017 17:56:27 +0000 Subject: [PATCH 08/37] added missing response headers in WithHttpInfo calls --- .../src/main/resources/php/api.mustache | 2 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 4 ++-- .../php/SwaggerClient-php/lib/Api/PetApi.php | 8 ++++---- .../php/SwaggerClient-php/lib/Api/StoreApi.php | 2 +- .../php/SwaggerClient-php/lib/Api/UserApi.php | 12 ++++++------ .../php/SwaggerClient-php/tests/PetApiTest.php | 2 -- 6 files changed, 14 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index e069639ecde..66264ee2ad9 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -278,7 +278,7 @@ use {{invokerPackage}}\ObjectSerializer; ]; {{/returnType}} {{^returnType}} - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; {{/returnType}} } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 113fecb5474..210c018cd84 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -412,7 +412,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -569,7 +569,7 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 7ff602b0f1a..4033bce8ffe 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -156,7 +156,7 @@ public function addPetWithHttpInfo($body) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -277,7 +277,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -767,7 +767,7 @@ public function updatePetWithHttpInfo($body) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -892,7 +892,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 912607777cf..5ff632212d6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -158,7 +158,7 @@ public function deleteOrderWithHttpInfo($order_id) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 9f4701bf69b..ca54fc699c1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -152,7 +152,7 @@ public function createUserWithHttpInfo($body) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -262,7 +262,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -372,7 +372,7 @@ public function createUsersWithListInputWithHttpInfo($body) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -481,7 +481,7 @@ public function deleteUserWithHttpInfo($username) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -828,7 +828,7 @@ public function logoutUserWithHttpInfo() $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } @@ -948,7 +948,7 @@ public function updateUserWithHttpInfo($username, $body) $httpBody ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), []]; + return [null, $response->getStatusCode(), $response->getHeaders()]; } catch (Exception $exception) { throw new ApiException($exception->getMessage(), null, $exception); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 817ceddee06..085a2c04867 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -2,8 +2,6 @@ namespace Swagger\Client; -use Guzzle\Http\Message\Request; -use GuzzleHttp\Psr7\MultipartStream; use Http\Adapter\Guzzle6\Client; use Swagger\Client\Api\PetApi; use Swagger\Client\Model\ApiResponse; From ed36513555c3e6582893d7590789280fc80ad10e Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 17 Mar 2017 17:58:08 +0000 Subject: [PATCH 09/37] removed Store test From PetApiTest class --- .../php/SwaggerClient-php/tests/PetApiTest.php | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 085a2c04867..f41318c0e15 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -278,21 +278,6 @@ public function testUploadFile() } - // test get inventory - public function testGetInventory() - { - // initialize the API client - $config = new Configuration(); - $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new APIClient($config); - $store_api = new Api\StoreApi($api_client); - // get inventory - $get_response = $store_api->getInventory(); - - $this->assertInternalType("int", $get_response['sold']); - $this->assertInternalType("int", $get_response['pending']); - } - /* * comment out as we've removed invalid endpoints from the spec, we'll introduce something * similar in the future when we've time to update the petstore server From b0afab32006f110ac41edd48d683b14b67fba1c2 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 17 Mar 2017 18:01:29 +0000 Subject: [PATCH 10/37] removed configuration overriding test as its now task of client adapters --- .../php/SwaggerClient-php/tests/PetApiTest.php | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index f41318c0e15..47bd84a8ecb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -390,20 +390,4 @@ public function testDefaultValues() $this->assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } - - // Ensure that API Classes pickup ApiClient defaults to prevent regressions of PR #4525 - public function testHostOverride() - { - $orig_default = Configuration::getDefaultConfiguration(); - $new_default = new Configuration(); - - $new_default->setHost("http://localhost/whatever"); - Configuration::setDefaultConfiguration($new_default); - - $pet_api = new Api\PetApi(); - $pet_host = $pet_api->getApiClient()->getConfig()->getHost(); - $this->assertSame($pet_host, $new_default->getHost()); - - Configuration::setDefaultConfiguration($orig_default); // Reset to original to prevent failure of other tests that rely on this state - } } From a52be13b76e8a0c4f0144afbeea08de827a0b556 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 17 Mar 2017 18:07:01 +0000 Subject: [PATCH 11/37] updated store tests with new client initialization code --- .../SwaggerClient-php/tests/PetApiTest.php | 8 +-- .../SwaggerClient-php/tests/StoreApiTest.php | 66 +++++-------------- 2 files changed, 22 insertions(+), 52 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 47bd84a8ecb..e6c03afc170 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -41,7 +41,7 @@ public static function setUpBeforeClass() $new_pet->setName("PHP Unit Test"); $new_pet->setPhotoUrls(["http://test_php_unit_test.com"]); // new tag - $tag= new Model\Tag; + $tag = new Model\Tag; $tag->setId($new_pet_id); // use the same id as pet $tag->setName("test php tag"); // new category @@ -63,9 +63,9 @@ public static function setUpBeforeClass() public function setUp() { $this->api = new Api\PetApi( - new Client( - new \GuzzleHttp\Client(['base_uri' => 'http://petstore.swagger.io/v2/']) - ) + Client::createWithConfig([ + 'base_uri' => 'http://petstore.swagger.io/v2/' + ]) ); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index d66e1d4770f..bb6e1a18a06 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -2,50 +2,29 @@ namespace Swagger\Client; +use Http\Adapter\Guzzle6\Client; +use Swagger\Client\Api\StoreApi; + class StoreApiTest extends \PHPUnit_Framework_TestCase { + /** @var StoreApi */ + private $api; - // add a new pet (id 10005) to ensure the pet object is available for all the tests - public static function setUpBeforeClass() + public function setUp() { - // for error reporting (need to run with php5.3 to get no warning) - //ini_set('display_errors', 1); - //error_reporting(~0); - // new pet - $new_pet_id = 10005; - $new_pet = new Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test"); - $new_pet->setStatus("available"); - // new tag - $tag= new Model\Tag; - $tag->setId($new_pet_id); // use the same id as pet - $tag->setName("test php tag"); - // new category - $category = new Model\Category; - $category->setId($new_pet_id); // use the same id as pet - $category->setName("test php category"); - - $new_pet->setTags(array($tag)); - $new_pet->setCategory($category); - - $pet_api = new Api\PetAPI(); - // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); + $this->api = new Api\StoreApi( + Client::createWithConfig([ + 'base_uri' => 'http://petstore.swagger.io/v2/' + ]) + ); } - // test get inventory public function testGetInventory() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $store_api = new Api\StoreApi($api_client); - // get inventory - $get_response = $store_api->getInventory(); + $result = $this->api->getInventory(); - $this->assertInternalType("array", $get_response); - $this->assertInternalType("int", $get_response['available']); + $this->assertInternalType("array", $result); + $this->assertInternalType("int", $result['available']); } /* @@ -55,15 +34,10 @@ public function testGetInventory() // test get inventory public function testGetInventoryInObject() { - // initialize the API client - //$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient(); - $store_api = new Api\StoreApi($api_client); - // get inventory - $get_response = $store_api->getInventoryInObject(); + $result = $this->api->getInventoryInObject(); - $this->assertInternalType("array", $get_response); - $this->assertInternalType("int", $get_response['available']); + $this->assertInternalType("array", $result); + $this->assertInternalType("int", $result['available']); } */ @@ -78,12 +52,8 @@ public function testGetInventoryInObject() */ // public function testEmptyArrayResponse() // { -// // initialize the API client -// $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); -// $apiClient = new ApiClient($config); -// $storeApi = new Api\PetApi($apiClient); // // this call returns and empty array -// $response = $storeApi->findPetsByStatus(array()); +// $response = $this->api->findPetsByStatus(array()); // // // make sure this is an array as we want it to be // $this->assertInternalType("array", $response); From bab5ed31e3500997416eadb112267d0aa9db0b4f Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Sat, 18 Mar 2017 13:43:48 +0000 Subject: [PATCH 12/37] updated composer.json template --- .../src/main/resources/php/composer.mustache | 11 +++++++---- .../petstore/php/SwaggerClient-php/composer.json | 11 +++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 51bf2d5e286..c49cc1dcbe9 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -22,13 +22,16 @@ "php": ">=5.4", "ext-curl": "*", "ext-json": "*", - "ext-mbstring": "*" + "ext-mbstring": "*", + "php-http/httplug": "^1.1", + "guzzlehttp/psr7": "^1.4" }, "require-dev": { - "phpunit/phpunit": "~4.8", - "satooshi/php-coveralls": "~1.0", + "phpunit/phpunit": "^5.0", "squizlabs/php_codesniffer": "~2.6", - "friendsofphp/php-cs-fixer": "~1.12" + "friendsofphp/php-cs-fixer": "~1.12", + "php-http/guzzle6-adapter": "^1.1", + "php-http/curl-client": "^1.7" }, "autoload": { "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index 7d1a19b4318..bf27b85e1e8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -19,13 +19,16 @@ "php": ">=5.4", "ext-curl": "*", "ext-json": "*", - "ext-mbstring": "*" + "ext-mbstring": "*", + "php-http/httplug": "^1.1", + "guzzlehttp/psr7": "^1.4" }, "require-dev": { - "phpunit/phpunit": "~4.8", - "satooshi/php-coveralls": "~1.0", + "phpunit/phpunit": "^5.0", "squizlabs/php_codesniffer": "~2.6", - "friendsofphp/php-cs-fixer": "~1.12" + "friendsofphp/php-cs-fixer": "~1.12", + "php-http/guzzle6-adapter": "^1.1", + "php-http/curl-client": "^1.7" }, "autoload": { "psr-4": { "Swagger\\Client\\" : "lib/" } From 70c95d5a129f54280decd2f31d189f20b7d048d7 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Sat, 18 Mar 2017 14:16:47 +0000 Subject: [PATCH 13/37] not using json_decode if response is string --- .../src/main/resources/php/api.mustache | 6 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 8 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 28 +- .../php/SwaggerClient-php/lib/Api/PetApi_.php | 721 ------------------ .../SwaggerClient-php/lib/Api/StoreApi.php | 19 +- .../php/SwaggerClient-php/lib/Api/UserApi.php | 18 +- .../SwaggerClient-php/tests/UserApiTest.php | 21 +- 7 files changed, 84 insertions(+), 737 deletions(-) delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 66264ee2ad9..a5099d22f78 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -150,6 +150,7 @@ use {{invokerPackage}}\ObjectSerializer; $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '{{returnType}}'; {{#queryParams}} // query params @@ -270,7 +271,10 @@ use {{invokerPackage}}\ObjectSerializer; ); $response = $this->client->sendRequest($request); {{#returnType}} - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '{{returnType}}', []), $response->getStatusCode(), diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 210c018cd84..dffa0f3b973 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -105,6 +105,7 @@ public function testClientModelWithHttpInfo($body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\Client'; @@ -153,7 +154,10 @@ public function testClientModelWithHttpInfo($body) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Client', []), $response->getStatusCode(), @@ -309,6 +313,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; @@ -484,6 +489,7 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; // query params if (is_array($enum_query_string_array)) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 4033bce8ffe..65a0ae7de42 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -104,6 +104,7 @@ public function addPetWithHttpInfo($body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; @@ -220,6 +221,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; /** // header params @@ -340,6 +342,7 @@ public function findPetsByStatusWithHttpInfo($status) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\Pet[]'; // query params if (is_array($status)) { @@ -394,7 +397,10 @@ public function findPetsByStatusWithHttpInfo($status) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), $response->getStatusCode(), @@ -466,6 +472,7 @@ public function findPetsByTagsWithHttpInfo($tags) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\Pet[]'; // query params if (is_array($tags)) { @@ -520,7 +527,10 @@ public function findPetsByTagsWithHttpInfo($tags) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), $response->getStatusCode(), @@ -592,6 +602,7 @@ public function getPetByIdWithHttpInfo($pet_id) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\Pet'; // path params @@ -644,7 +655,10 @@ public function getPetByIdWithHttpInfo($pet_id) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet', []), $response->getStatusCode(), @@ -715,6 +729,7 @@ public function updatePetWithHttpInfo($body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; @@ -833,6 +848,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; // path params @@ -959,6 +975,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\ApiResponse'; // path params @@ -1019,7 +1036,10 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\ApiResponse', []), $response->getStatusCode(), diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php deleted file mode 100644 index 11ec90fc6b9..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi_.php +++ /dev/null @@ -1,721 +0,0 @@ -client = $client; - $this->serializer = new ObjectSerializer(); - $this->headerSelector = $selector ?: new HeaderSelector(); - } - - /** - * Operation addPet - * - * Add a new pet to the store - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return void - */ - public function addPet($body) - { - list($response) = $this->addPetWithHttpInfo($body); - return $response; - } - - /** - * Operation addPetWithHttpInfo - * - * Add a new pet to the store - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function addPetWithHttpInfo($body) - { - // verify the required parameter 'body' is set - if ($body === null) { - throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); - } - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); - - $request = new Request( - 'POST', - '/v2/pet', - $headers, - json_encode(ObjectSerializer::sanitizeForSerialization($body)) - ); - - try { - $response = $this->client->sendRequest($request); - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); - } - - $content = json_decode($response->getBody()->getContents()); - $result = ObjectSerializer::deserialize($content, Pet::class); - - return [ - $result, - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - /** - * Operation deletePet - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return void - */ - public function deletePet($pet_id, $api_key = null) - { - list($response) = $this->deletePetWithHttpInfo($pet_id, $api_key); - return $response; - } - - /** - * Operation deletePetWithHttpInfo - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function deletePetWithHttpInfo($pet_id, $api_key = null) - { - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); - } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; - $formParams = []; - $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->client->selectHeaderContentType([]); - - // header params - if ($api_key !== null) { - $headerParams['api_key'] = $this->client->getSerializer()->toHeaderValue($api_key); - } - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->client->getSerializer()->toPathValue($pet_id), - $resourcePath - ); - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - // this endpoint requires OAuth (access token) - if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->client->callApi( - $resourcePath, - 'DELETE', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet/{petId}' - ); - - return [null, $statusCode, $httpHeader]; - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - throw $e; - } - } - - /** - * Operation findPetsByStatus - * - * Finds Pets by status - * - * @param string[] $status Status values that need to be considered for filter (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return \Swagger\Client\Model\Pet[] - */ - public function findPetsByStatus($status) - { - list($response) = $this->findPetsByStatusWithHttpInfo($status); - return $response; - } - - /** - * Operation findPetsByStatusWithHttpInfo - * - * Finds Pets by status - * - * @param string[] $status Status values that need to be considered for filter (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) - */ - public function findPetsByStatusWithHttpInfo($status) - { - // verify the required parameter 'status' is set - if ($status === null) { - throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); - } - // parse inputs - $resourcePath = "/pet/findByStatus"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; - $formParams = []; - $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->client->selectHeaderContentType([]); - - // query params - if (is_array($status)) { - $status = $this->client->getSerializer()->serializeCollection($status, 'csv', true); - } - if ($status !== null) { - $queryParams['status'] = $this->client->getSerializer()->toQueryValue($status); - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - // this endpoint requires OAuth (access token) - if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->client->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet[]', - '/pet/findByStatus' - ); - - return [$this->client->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->client->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * Operation findPetsByTags - * - * Finds Pets by tags - * - * @param string[] $tags Tags to filter by (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return \Swagger\Client\Model\Pet[] - */ - public function findPetsByTags($tags) - { - list($response) = $this->findPetsByTagsWithHttpInfo($tags); - return $response; - } - - /** - * Operation findPetsByTagsWithHttpInfo - * - * Finds Pets by tags - * - * @param string[] $tags Tags to filter by (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) - */ - public function findPetsByTagsWithHttpInfo($tags) - { - // verify the required parameter 'tags' is set - if ($tags === null) { - throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); - } - // parse inputs - $resourcePath = "/pet/findByTags"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; - $formParams = []; - $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->client->selectHeaderContentType([]); - - // query params - if (is_array($tags)) { - $tags = $this->client->getSerializer()->serializeCollection($tags, 'csv', true); - } - if ($tags !== null) { - $queryParams['tags'] = $this->client->getSerializer()->toQueryValue($tags); - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - // this endpoint requires OAuth (access token) - if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->client->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet[]', - '/pet/findByTags' - ); - - return [$this->client->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->client->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } - - /** - * Operation getPetById - * - * Find pet by ID - * - * @param int $pet_id ID of pet to return (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return \Swagger\Client\Model\Pet - */ - public function getPetById($pet_id) - { - list($response) = $this->getPetByIdWithHttpInfo($pet_id); - return $response; - } - - /** - * Operation getPetByIdWithHttpInfo - * - * Find pet by ID - * - * @param int $pet_id ID of pet to return (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) - * @throws \Exception - * @throws \InvalidArgumentException - */ - public function getPetByIdWithHttpInfo($pet_id) - { - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); - } - - $resourcePath = '/v2/pet/{petId}'; - $resourcePath = str_replace('{petId}', $this->serializer->toPathValue($pet_id), $resourcePath); - - $request = new Request( - 'GET', - $resourcePath, - $this->headerSelector->selectHeaders(['application/json'], []) - ); - - - try { - $response = $this->client->sendRequest($request); - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); - } - - $content = json_decode($response->getBody()->getContents()); - $result = ObjectSerializer::deserialize($content, Pet::class); - - return [ - $result, - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - /** - * Operation updatePet - * - * Update an existing pet - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return void - */ - public function updatePet($body) - { - list($response) = $this->updatePetWithHttpInfo($body); - return $response; - } - - /** - * Operation updatePetWithHttpInfo - * - * Update an existing pet - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function updatePetWithHttpInfo($body) - { - // verify the required parameter 'body' is set - if ($body === null) { - throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); - } - // parse inputs - $resourcePath = "/pet"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; - $formParams = []; - $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->client->selectHeaderContentType(['application/json', 'application/xml']); - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - // this endpoint requires OAuth (access token) - if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->client->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet' - ); - - return [null, $statusCode, $httpHeader]; - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - throw $e; - } - } - - /** - * Operation updatePetWithForm - * - * Updates a pet in the store with form data - * - * @param int $pet_id ID of pet that needs to be updated (required) - * @param string $name Updated name of the pet (optional) - * @param string $status Updated status of the pet (optional) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return void - */ - public function updatePetWithForm($pet_id, $name = null, $status = null) - { - list($response) = $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); - return $response; - } - - /** - * Operation updatePetWithFormWithHttpInfo - * - * Updates a pet in the store with form data - * - * @param int $pet_id ID of pet that needs to be updated (required) - * @param string $name Updated name of the pet (optional) - * @param string $status Updated status of the pet (optional) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) - { - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); - } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; - $formParams = []; - $_header_accept = $this->client->selectHeaderAccept(['application/xml', 'application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->client->selectHeaderContentType(['application/x-www-form-urlencoded']); - - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->client->getSerializer()->toPathValue($pet_id), - $resourcePath - ); - } - // form params - if ($name !== null) { - $formParams['name'] = $this->client->getSerializer()->toFormValue($name); - } - // form params - if ($status !== null) { - $formParams['status'] = $this->client->getSerializer()->toFormValue($status); - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - // this endpoint requires OAuth (access token) - if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->client->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet/{petId}' - ); - - return [null, $statusCode, $httpHeader]; - } catch (ApiException $e) { - switch ($e->getCode()) { - } - - throw $e; - } - } - - /** - * Operation uploadFile - * - * uploads an image - * - * @param int $pet_id ID of pet to update (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param \SplFileObject $file file to upload (optional) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return \Swagger\Client\Model\ApiResponse - */ - public function uploadFile($pet_id, $additional_metadata = null, $file = null) - { - list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file); - return $response; - } - - /** - * Operation uploadFileWithHttpInfo - * - * uploads an image - * - * @param int $pet_id ID of pet to update (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param \SplFileObject $file file to upload (optional) - * @throws \Swagger\Client\ApiException on non-2xx response - * @return array of \Swagger\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) - */ - public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null) - { - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); - } - // parse inputs - $resourcePath = "/pet/{petId}/uploadImage"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; - $formParams = []; - $_header_accept = $this->client->selectHeaderAccept(['application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->client->selectHeaderContentType(['multipart/form-data']); - - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->client->getSerializer()->toPathValue($pet_id), - $resourcePath - ); - } - // form params - if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = $this->client->getSerializer()->toFormValue($additional_metadata); - } - // form params - if ($file !== null) { - // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax - // See: https://wiki.php.net/rfc/curl-file-upload - if (function_exists('curl_file_create')) { - $formParams['file'] = curl_file_create($this->client->getSerializer()->toFormValue($file)); - } else { - $formParams['file'] = '@' . $this->client->getSerializer()->toFormValue($file); - } - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) - } - // this endpoint requires OAuth (access token) - if (strlen($this->client->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->client->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->client->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\ApiResponse', - '/pet/{petId}/uploadImage' - ); - - return [$this->client->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader]; - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->client->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - } - - throw $e; - } - } -} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 5ff632212d6..e6091f4fd2b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -107,6 +107,7 @@ public function deleteOrderWithHttpInfo($order_id) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; // path params @@ -215,6 +216,7 @@ public function getInventoryWithHttpInfo() $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = 'map[string,int]'; @@ -263,7 +265,10 @@ public function getInventoryWithHttpInfo() $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, 'map[string,int]', []), $response->getStatusCode(), @@ -345,6 +350,7 @@ public function getOrderByIdWithHttpInfo($order_id) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\Order'; // path params @@ -396,7 +402,10 @@ public function getOrderByIdWithHttpInfo($order_id) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), $response->getStatusCode(), @@ -468,6 +477,7 @@ public function placeOrderWithHttpInfo($body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\Order'; @@ -516,7 +526,10 @@ public function placeOrderWithHttpInfo($body) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), $response->getStatusCode(), diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index ca54fc699c1..050216fa1e5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -104,6 +104,7 @@ public function createUserWithHttpInfo($body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; @@ -214,6 +215,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; @@ -324,6 +326,7 @@ public function createUsersWithListInputWithHttpInfo($body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; @@ -434,6 +437,7 @@ public function deleteUserWithHttpInfo($username) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; // path params @@ -544,6 +548,7 @@ public function getUserByNameWithHttpInfo($username) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = '\Swagger\Client\Model\User'; // path params @@ -591,7 +596,10 @@ public function getUserByNameWithHttpInfo($username) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\User', []), $response->getStatusCode(), @@ -669,6 +677,7 @@ public function loginUserWithHttpInfo($username, $password) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = 'string'; // query params if ($username !== null) { @@ -720,7 +729,10 @@ public function loginUserWithHttpInfo($username, $password) $httpBody ); $response = $this->client->sendRequest($request); - $content = json_decode($response->getBody()->getContents()); + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } return [ ObjectSerializer::deserialize($content, 'string', []), $response->getStatusCode(), @@ -785,6 +797,7 @@ public function logoutUserWithHttpInfo() $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; @@ -896,6 +909,7 @@ public function updateUserWithHttpInfo($username, $body) $queryParams = []; $httpBody = ''; $multipart = false; + $returnType = ''; // path params diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index a8487e58764..eb487ce9335 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -2,10 +2,15 @@ namespace Swagger\Client; +use Http\Adapter\Guzzle6\Client; +use Swagger\Client\Api\UserApi; + class UserApiTest extends \PHPUnit_Framework_TestCase { - // add a new pet (id 10005) to ensure the pet object is available for all the tests + /** @var UserApi*/ + private $api; + public static function setUpBeforeClass() { // for error reporting (need to run with php5.3 to get no warning) @@ -13,15 +18,21 @@ public static function setUpBeforeClass() //error_reporting(~0); } + public function setUp() + { + $this->api = new Api\UserApi( + Client::createWithConfig([ + 'base_uri' => 'http://petstore.swagger.io/v2/' + ]) + ); + } + // test login user public function testLoginUser() { // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $user_api = new Api\UserApi($api_client); // login - $response = $user_api->loginUser("xxxxx", "yyyyyyyy"); + $response = $this->api->loginUser("xxxxx", "yyyyyyyy"); $this->assertInternalType("string", $response); $this->assertRegExp( From 3b7980680f011d1020710417dd1c02ec6c9df082 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Sat, 18 Mar 2017 14:17:09 +0000 Subject: [PATCH 14/37] renamed some variables to camelCase --- .../SwaggerClient-php/tests/PetApiTest.php | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index e6c03afc170..53e909edacd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -35,28 +35,28 @@ public static function setUpBeforeClass() // skip initializing the API client as it should be automatic //$api_client = new ApiClient('http://petstore.swagger.io/v2'); // new pet - $new_pet_id = 10005; - $new_pet = new Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test"); - $new_pet->setPhotoUrls(["http://test_php_unit_test.com"]); + $newPetId = 10005; + $newPet = new Model\Pet; + $newPet->setId($newPetId); + $newPet->setName("PHP Unit Test"); + $newPet->setPhotoUrls(["http://test_php_unit_test.com"]); // new tag $tag = new Model\Tag; - $tag->setId($new_pet_id); // use the same id as pet + $tag->setId($newPetId); // use the same id as pet $tag->setName("test php tag"); // new category $category = new Model\Category; - $category->setId($new_pet_id); // use the same id as pet + $category->setId($newPetId); // use the same id as pet $category->setName("test php category"); - $new_pet->setTags(array($tag)); - $new_pet->setCategory($category); + $newPet->setTags(array($tag)); + $newPet->setCategory($category); $petApi = new Api\PetApi(new Client(new \GuzzleHttp\Client([ 'base_uri' => 'http://petstore.swagger.io/v2/' ]))); // add a new pet (model) - list(, $status) = $petApi->addPetWithHttpInfo($new_pet); + list(, $status) = $petApi->addPetWithHttpInfo($newPet); \PHPUnit_Framework_Assert::assertEquals(200, $status); } From b5973d708e567cc175db6d9ef5c74a08687737df Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Sat, 18 Mar 2017 14:26:17 +0000 Subject: [PATCH 15/37] removed ApiClient and Configuration classes --- .../codegen/languages/PhpClientCodegen.java | 2 - .../src/main/resources/php/ApiClient.mustache | 357 --------- .../main/resources/php/configuration.mustache | 700 ------------------ .../php/SwaggerClient-php/lib/ApiClient.php | 367 --------- .../php/SwaggerClient-php/lib/ApiClient2.php | 163 ---- .../SwaggerClient-php/lib/Configuration.php | 521 +------------ 6 files changed, 32 insertions(+), 2078 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/php/ApiClient.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/php/configuration.mustache delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index d0b6589a587..76154f3f701 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -301,8 +301,6 @@ public void processOpts() { // make test path available in mustache template additionalProperties.put("testBasePath", testBasePath); - supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache deleted file mode 100644 index dd1a221d766..00000000000 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ /dev/null @@ -1,357 +0,0 @@ -partial_header}} -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -namespace {{invokerPackage}}; - -/** - * ApiClient Class Doc Comment - * - * @category Class - * @package {{invokerPackage}} - * @author Swagger Codegen team - * @link https://github.com/swagger-api/swagger-codegen - */ -class ApiClient -{ - public static $PATCH = "PATCH"; - public static $POST = "POST"; - public static $GET = "GET"; - public static $HEAD = "HEAD"; - public static $OPTIONS = "OPTIONS"; - public static $PUT = "PUT"; - public static $DELETE = "DELETE"; - - /** - * Configuration - * - * @var Configuration - */ - protected $config; - - /** - * Object Serializer - * - * @var ObjectSerializer - */ - protected $serializer; - - /** - * Constructor of the class - * - * @param Configuration $config config for this ApiClient - */ - public function __construct(\{{invokerPackage}}\Configuration $config = null) - { - if ($config === null) { - $config = Configuration::getDefaultConfiguration(); - } - - $this->config = $config; - $this->serializer = new ObjectSerializer(); - } - - /** - * Get the config - * - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Get the serializer - * - * @return ObjectSerializer - */ - public function getSerializer() - { - return $this->serializer; - } - - /** - * Get API key (with prefix if set) - * - * @param string $apiKeyIdentifier name of apikey - * - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKeyIdentifier) - { - $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); - $apiKey = $this->config->getApiKey($apiKeyIdentifier); - - if (!isset($apiKey)) { - return null; - } - - if (isset($prefix)) { - $keyWithPrefix = $prefix." ".$apiKey; - } else { - $keyWithPrefix = $apiKey; - } - - return $keyWithPrefix; - } - - /** - * Make the HTTP call (Sync) - * - * @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 - * @param string $responseType expected response type of the endpoint - * @param string $endpointPath path to method endpoint before expanding parameters - * - * @throws \{{invokerPackage}}\ApiException on a non 2xx response - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) - { - $headers = []; - - // construct the http header - $headerParams = array_merge( - (array)$this->config->getDefaultHeaders(), - (array)$headerParams - ); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { - $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model - $postData = json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($postData)); - } - - $url = $this->config->getHost() . $resourcePath; - - $curl = curl_init(); - // set timeout, if needed - if ($this->config->getCurlTimeout() !== 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); - } - // set connect timeout, if needed - if ($this->config->getCurlConnectTimeout() != 0) { - curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); - } - - // return the result on success, rather than just true - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - // disable SSL verification, if needed - if ($this->config->getSSLVerification() === false) { - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); - } - - if ($this->config->getCurlProxyHost()) { - curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); - } - - if ($this->config->getCurlProxyPort()) { - curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); - } - - if ($this->config->getCurlProxyType()) { - curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); - } - - if ($this->config->getCurlProxyUser()) { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); - } - - 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); - } elseif ($method === self::$HEAD) { - curl_setopt($curl, CURLOPT_NOBODY, true); - } elseif ($method === self::$OPTIONS) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($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->config->getUserAgent()); - - // debugging for curl - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), '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 = $this->httpParseHeaders(substr($response, 0, $http_header_size)); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); - - // debug HTTP response body - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - } - - // Handle the response - if ($response_info['http_code'] === 0) { - $curl_error_message = curl_error($curl); - - // curl_exec can sometimes fail but still return a blank message from curl_error(). - if (!empty($curl_error_message)) { - $error_message = "API call to $url failed: $curl_error_message"; - } else { - $error_message = "API call to $url failed, but for an unknown reason. " . - "This could happen if you are disconnected from the network."; - } - - $exception = new ApiException($error_message, 0, null, null); - $exception->setResponseObject($response_info); - throw $exception; - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { - // return raw body if response is a file - if ($responseType === '\SplFileObject' || $responseType === 'string') { - return [$http_body, $response_info['http_code'], $http_header]; - } - - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - } else { - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - - throw new ApiException( - "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], - $http_header, - $data - ); - } - return [$data, $response_info['http_code'], $http_header]; - } - - /** - * Return the header 'Accept' based on an array of Accept provided - * - * @param string[] $accept Array of header - * - * @return string Accept (e.g. application/json) - */ - public 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 string[] $content_type Array fo content-type - * - * @return string Content-Type (e.g. application/json) - */ - public 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); - } - } - - /** - * Return an array of HTTP response headers - * - * @param string $raw_headers A string of raw HTTP response headers - * - * @return string[] Array of HTTP response heaers - */ - protected function httpParseHeaders($raw_headers) - { - // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 - $headers = []; - $key = ''; - - foreach (explode("\n", $raw_headers) as $h) { - $h = explode(':', $h, 2); - - if (isset($h[1])) { - if (!isset($headers[$h[0]])) { - $headers[$h[0]] = trim($h[1]); - } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); - } else { - $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); - } - - $key = $h[0]; - } else { - if (substr($h[0], 0, 1) === "\t") { - $headers[$key] .= "\r\n\t".trim($h[0]); - } elseif (!$key) { - $headers[0] = trim($h[0]); - } - trim($h[0]); - } - } - - return $headers; - } -} diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache deleted file mode 100644 index 4e10f33823c..00000000000 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ /dev/null @@ -1,700 +0,0 @@ -partial_header}} -/** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen - * Do not edit the class manually. - */ - -namespace {{invokerPackage}}; - -/** - * Configuration Class Doc Comment - * PHP version 5 - * - * @category Class - * @package {{invokerPackage}} - * @author Swagger Codegen team - * @link https://github.com/swagger-api/swagger-codegen - */ -class Configuration -{ - private static $defaultConfiguration; - - /** - * Associate array to store API key(s) - * - * @var string[] - */ - protected $apiKeys = []; - - /** - * Associate array to store API prefix (e.g. Bearer) - * - * @var string[] - */ - protected $apiKeyPrefixes = []; - - /** - * Access token for OAuth - * - * @var string - */ - protected $accessToken = ''; - - /** - * Username for HTTP basic authentication - * - * @var string - */ - protected $username = ''; - - /** - * Password for HTTP basic authentication - * - * @var string - */ - protected $password = ''; - - /** - * The default header(s) - * - * @var array - */ - protected $defaultHeaders = []; - - /** - * The host - * - * @var string - */ - protected $host = '{{{basePath}}}'; - - /** - * Timeout (second) of the HTTP request, by default set to 0, no timeout - * - * @var string - */ - protected $curlTimeout = 0; - - /** - * Timeout (second) of the HTTP connection, by default set to 0, no timeout - * - * @var string - */ - protected $curlConnectTimeout = 0; - - /** - * User agent of the HTTP request, set to "PHP-Swagger" by default - * - * @var string - */ - protected $userAgent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}'; - - /** - * Debug switch (default set to false) - * - * @var bool - */ - protected $debug = false; - - /** - * Debug file location (log to STDOUT by default) - * - * @var string - */ - protected $debugFile = 'php://output'; - - /** - * Debug file location (log to STDOUT by default) - * - * @var string - */ - protected $tempFolderPath; - - /** - * Indicates if SSL verification should be enabled or disabled. - * - * This is useful if the host uses a self-signed SSL certificate. - * - * @var boolean True if the certificate should be validated, false otherwise. - */ - protected $sslVerification = true; - - /** - * Curl proxy host - * - * @var string - */ - protected $proxyHost; - - /** - * Curl proxy port - * - * @var integer - */ - protected $proxyPort; - - /** - * Curl proxy type, e.g. CURLPROXY_HTTP or CURLPROXY_SOCKS5 - * - * @see https://secure.php.net/manual/en/function.curl-setopt.php - * @var integer - */ - protected $proxyType; - - /** - * Curl proxy username - * - * @var string - */ - protected $proxyUser; - - /** - * Curl proxy password - * - * @var string - */ - protected $proxyPassword; - - /** - * Constructor - */ - public function __construct() - { - $this->tempFolderPath = sys_get_temp_dir(); - } - - /** - * Sets API key - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $key API key or token - * - * @return $this - */ - public function setApiKey($apiKeyIdentifier, $key) - { - $this->apiKeys[$apiKeyIdentifier] = $key; - return $this; - } - - /** - * Gets API key - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return string API key or token - */ - public function getApiKey($apiKeyIdentifier) - { - return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; - } - - /** - * Sets the prefix for API key (e.g. Bearer) - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer - * - * @return $this - */ - public function setApiKeyPrefix($apiKeyIdentifier, $prefix) - { - $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; - return $this; - } - - /** - * Gets API key prefix - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return string - */ - public function getApiKeyPrefix($apiKeyIdentifier) - { - return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; - } - - /** - * Sets the access token for OAuth - * - * @param string $accessToken Token for OAuth - * - * @return $this - */ - public function setAccessToken($accessToken) - { - $this->accessToken = $accessToken; - return $this; - } - - /** - * Gets the access token for OAuth - * - * @return string Access token for OAuth - */ - public function getAccessToken() - { - return $this->accessToken; - } - - /** - * Sets the username for HTTP basic authentication - * - * @param string $username Username for HTTP basic authentication - * - * @return $this - */ - public function setUsername($username) - { - $this->username = $username; - return $this; - } - - /** - * Gets the username for HTTP basic authentication - * - * @return string Username for HTTP basic authentication - */ - public function getUsername() - { - return $this->username; - } - - /** - * Sets the password for HTTP basic authentication - * - * @param string $password Password for HTTP basic authentication - * - * @return $this - */ - public function setPassword($password) - { - $this->password = $password; - return $this; - } - - /** - * Gets the password for HTTP basic authentication - * - * @return string Password for HTTP basic authentication - */ - public function getPassword() - { - return $this->password; - } - - /** - * Adds a default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * - * @throws \InvalidArgumentException - * @return $this - */ - public function addDefaultHeader($headerName, $headerValue) - { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * Gets the default header - * - * @return array An array of default header(s) - */ - public function getDefaultHeaders() - { - return $this->defaultHeaders; - } - - /** - * Deletes a default header - * - * @param string $headerName the header to delete - * - * @return $this - */ - public function deleteDefaultHeader($headerName) - { - unset($this->defaultHeaders[$headerName]); - return $this; - } - - /** - * Sets the host - * - * @param string $host Host - * - * @return $this - */ - public function setHost($host) - { - $this->host = $host; - return $this; - } - - /** - * Gets the host - * - * @return string Host - */ - public function getHost() - { - return $this->host; - } - - /** - * Sets the user agent of the api client - * - * @param string $userAgent the user agent of the api client - * - * @throws \InvalidArgumentException - * @return $this - */ - public function setUserAgent($userAgent) - { - if (!is_string($userAgent)) { - throw new \InvalidArgumentException('User-agent must be a string.'); - } - - $this->userAgent = $userAgent; - return $this; - } - - /** - * Gets the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() - { - return $this->userAgent; - } - - /** - * Sets the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - * - * @throws \InvalidArgumentException - * @return $this - */ - public function setCurlTimeout($seconds) - { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - } - - $this->curlTimeout = $seconds; - return $this; - } - - /** - * Gets the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getCurlTimeout() - { - return $this->curlTimeout; - } - - /** - * Sets the HTTP connect timeout value - * - * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] - * - * @throws \InvalidArgumentException - * @return $this - */ - public function setCurlConnectTimeout($seconds) - { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); - } - - $this->curlConnectTimeout = $seconds; - return $this; - } - - /** - * Gets the HTTP connect timeout value - * - * @return string HTTP connect timeout value - */ - public function getCurlConnectTimeout() - { - return $this->curlConnectTimeout; - } - - - /** - * Sets the HTTP Proxy Host - * - * @param string $proxyHost HTTP Proxy URL - * - * @return $this - */ - public function setCurlProxyHost($proxyHost) - { - $this->proxyHost = $proxyHost; - return $this; - } - - /** - * Gets the HTTP Proxy Host - * - * @return string - */ - public function getCurlProxyHost() - { - return $this->proxyHost; - } - - /** - * Sets the HTTP Proxy Port - * - * @param integer $proxyPort HTTP Proxy Port - * - * @return $this - */ - public function setCurlProxyPort($proxyPort) - { - $this->proxyPort = $proxyPort; - return $this; - } - - /** - * Gets the HTTP Proxy Port - * - * @return integer - */ - public function getCurlProxyPort() - { - return $this->proxyPort; - } - - /** - * Sets the HTTP Proxy Type - * - * @param integer $proxyType HTTP Proxy Type - * - * @return $this - */ - public function setCurlProxyType($proxyType) - { - $this->proxyType = $proxyType; - return $this; - } - - /** - * Gets the HTTP Proxy Type - * - * @return integer - */ - public function getCurlProxyType() - { - return $this->proxyType; - } - - /** - * Sets the HTTP Proxy User - * - * @param string $proxyUser HTTP Proxy User - * - * @return $this - */ - public function setCurlProxyUser($proxyUser) - { - $this->proxyUser = $proxyUser; - return $this; - } - - /** - * Gets the HTTP Proxy User - * - * @return string - */ - public function getCurlProxyUser() - { - return $this->proxyUser; - } - - /** - * Sets the HTTP Proxy Password - * - * @param string $proxyPassword HTTP Proxy Password - * - * @return $this - */ - public function setCurlProxyPassword($proxyPassword) - { - $this->proxyPassword = $proxyPassword; - return $this; - } - - /** - * Gets the HTTP Proxy Password - * - * @return string - */ - public function getCurlProxyPassword() - { - return $this->proxyPassword; - } - - /** - * Sets debug flag - * - * @param bool $debug Debug flag - * - * @return $this - */ - public function setDebug($debug) - { - $this->debug = $debug; - return $this; - } - - /** - * Gets the debug flag - * - * @return bool - */ - public function getDebug() - { - return $this->debug; - } - - /** - * Sets the debug file - * - * @param string $debugFile Debug file - * - * @return $this - */ - public function setDebugFile($debugFile) - { - $this->debugFile = $debugFile; - return $this; - } - - /** - * Gets the debug file - * - * @return string - */ - public function getDebugFile() - { - return $this->debugFile; - } - - /** - * Sets the temp folder path - * - * @param string $tempFolderPath Temp folder path - * - * @return $this - */ - public function setTempFolderPath($tempFolderPath) - { - $this->tempFolderPath = $tempFolderPath; - return $this; - } - - /** - * Gets the temp folder path - * - * @return string Temp folder path - */ - public function getTempFolderPath() - { - return $this->tempFolderPath; - } - - /** - * Sets if SSL verification should be enabled or disabled - * - * @param boolean $sslVerification True if the certificate should be validated, false otherwise - * - * @return $this - */ - public function setSSLVerification($sslVerification) - { - $this->sslVerification = $sslVerification; - return $this; - } - - /** - * Gets if SSL verification should be enabled or disabled - * - * @return boolean True if the certificate should be validated, false otherwise - */ - public function getSSLVerification() - { - return $this->sslVerification; - } - - /** - * Gets the default configuration instance - * - * @return Configuration - */ - public static function getDefaultConfiguration() - { - if (self::$defaultConfiguration === null) { - self::$defaultConfiguration = new Configuration(); - } - - return self::$defaultConfiguration; - } - - /** - * Sets the detault configuration instance - * - * @param Configuration $config An instance of the Configuration Object - * - * @return void - */ - public static function setDefaultConfiguration(Configuration $config) - { - self::$defaultConfiguration = $config; - } - - /** - * Gets the essential information for debugging - * - * @return string The report for debugging - */ - public static function toDebugReport() - { - $report = 'PHP SDK ({{invokerPackage}}) Debug Report:' . PHP_EOL; - $report .= ' OS: ' . php_uname() . PHP_EOL; - $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; - $report .= ' OpenAPI Spec Version: {{version}}' . PHP_EOL; - {{#artifactVersion}} - $report .= ' SDK Package Version: {{artifactVersion}}' . PHP_EOL; - {{/artifactVersion}} - $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; - - return $report; - } -} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php deleted file mode 100644 index b8add9f133c..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ /dev/null @@ -1,367 +0,0 @@ -config = $config; - $this->serializer = new ObjectSerializer(); - } - - /** - * Get the config - * - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Get the serializer - * - * @return ObjectSerializer - */ - public function getSerializer() - { - return $this->serializer; - } - - /** - * Get API key (with prefix if set) - * - * @param string $apiKeyIdentifier name of apikey - * - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKeyIdentifier) - { - $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); - $apiKey = $this->config->getApiKey($apiKeyIdentifier); - - if (!isset($apiKey)) { - return null; - } - - if (isset($prefix)) { - $keyWithPrefix = $prefix." ".$apiKey; - } else { - $keyWithPrefix = $apiKey; - } - - return $keyWithPrefix; - } - - /** - * Make the HTTP call (Sync) - * - * @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 - * @param string $responseType expected response type of the endpoint - * @param string $endpointPath path to method endpoint before expanding parameters - * - * @throws \Swagger\Client\ApiException on a non 2xx response - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) - { - $headers = []; - - // construct the http header - $headerParams = array_merge( - (array)$this->config->getDefaultHeaders(), - (array)$headerParams - ); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { - $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model - $postData = json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($postData)); - } - - $url = $this->config->getHost() . $resourcePath; - - $curl = curl_init(); - // set timeout, if needed - if ($this->config->getCurlTimeout() !== 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); - } - // set connect timeout, if needed - if ($this->config->getCurlConnectTimeout() != 0) { - curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); - } - - // return the result on success, rather than just true - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - // disable SSL verification, if needed - if ($this->config->getSSLVerification() === false) { - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); - } - - if ($this->config->getCurlProxyHost()) { - curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); - } - - if ($this->config->getCurlProxyPort()) { - curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); - } - - if ($this->config->getCurlProxyType()) { - curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); - } - - if ($this->config->getCurlProxyUser()) { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); - } - - 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); - } elseif ($method === self::$HEAD) { - curl_setopt($curl, CURLOPT_NOBODY, true); - } elseif ($method === self::$OPTIONS) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($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->config->getUserAgent()); - - // debugging for curl - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), '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 = $this->httpParseHeaders(substr($response, 0, $http_header_size)); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); - - // debug HTTP response body - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - } - - // Handle the response - if ($response_info['http_code'] === 0) { - $curl_error_message = curl_error($curl); - - // curl_exec can sometimes fail but still return a blank message from curl_error(). - if (!empty($curl_error_message)) { - $error_message = "API call to $url failed: $curl_error_message"; - } else { - $error_message = "API call to $url failed, but for an unknown reason. " . - "This could happen if you are disconnected from the network."; - } - - $exception = new ApiException($error_message, 0, null, null); - $exception->setResponseObject($response_info); - throw $exception; - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { - // return raw body if response is a file - if ($responseType === '\SplFileObject' || $responseType === 'string') { - return [$http_body, $response_info['http_code'], $http_header]; - } - - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - } else { - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - - throw new ApiException( - "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], - $http_header, - $data - ); - } - return [$data, $response_info['http_code'], $http_header]; - } - - /** - * Return the header 'Accept' based on an array of Accept provided - * - * @param string[] $accept Array of header - * - * @return string Accept (e.g. application/json) - */ - public 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 string[] $content_type Array fo content-type - * - * @return string Content-Type (e.g. application/json) - */ - public 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); - } - } - - /** - * Return an array of HTTP response headers - * - * @param string $raw_headers A string of raw HTTP response headers - * - * @return string[] Array of HTTP response heaers - */ - protected function httpParseHeaders($raw_headers) - { - // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 - $headers = []; - $key = ''; - - foreach (explode("\n", $raw_headers) as $h) { - $h = explode(':', $h, 2); - - if (isset($h[1])) { - if (!isset($headers[$h[0]])) { - $headers[$h[0]] = trim($h[1]); - } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); - } else { - $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); - } - - $key = $h[0]; - } else { - if (substr($h[0], 0, 1) === "\t") { - $headers[$key] .= "\r\n\t".trim($h[0]); - } elseif (!$key) { - $headers[0] = trim($h[0]); - } - trim($h[0]); - } - } - - return $headers; - } -} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php deleted file mode 100644 index 0b4dc23f682..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient2.php +++ /dev/null @@ -1,163 +0,0 @@ -serializer = new ObjectSerializer(); - $this->client = $client; - } - - /** - * Get the config - * - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Get the serializer - * - * @return ObjectSerializer - */ - public function getSerializer() - { - return $this->serializer; - } - - /** - * Make the HTTP call (Sync) - * - * @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 - * @param string $responseType expected response type of the endpoint - * @param string $endpointPath path to method endpoint before expanding parameters - * - * @throws \Swagger\Client\ApiException on a non 2xx response - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) - { - $request = new Request($method, $resourcePath, $headerParams, $postData); - try { - $response = $this->client->sendRequest($request); - } catch (Exception $exception) { - throw new ApiException('Client has thrown exception', null, $exception); - } - return [$response->getBody(), $response->getStatusCode(), $response->getHeaders()]; - } - - /** - * Return the header 'Accept' based on an array of Accept provided - * - * @param string[] $accept Array of header - * - * @return string Accept (e.g. application/json) - */ - public 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 string[] $content_type Array fo content-type - * - * @return string Content-Type (e.g. application/json) - */ - public 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/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 17e0a6feda3..2a252b39448 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -30,7 +30,6 @@ /** * Configuration Class Doc Comment - * PHP version 5 * * @category Class * @package Swagger\Client @@ -39,7 +38,10 @@ */ class Configuration { - private static $defaultConfiguration; + /** + * @var string + */ + protected $host; /** * Associate array to store API key(s) @@ -77,119 +79,33 @@ class Configuration protected $password = ''; /** - * The default header(s) - * - * @var array - */ - protected $defaultHeaders = []; - - /** - * The host - * - * @var string - */ - protected $host = 'http://petstore.swagger.io:80/v2'; - - /** - * Timeout (second) of the HTTP request, by default set to 0, no timeout - * - * @var string - */ - protected $curlTimeout = 0; - - /** - * Timeout (second) of the HTTP connection, by default set to 0, no timeout - * - * @var string - */ - protected $curlConnectTimeout = 0; - - /** - * User agent of the HTTP request, set to "PHP-Swagger" by default - * - * @var string - */ - protected $userAgent = 'Swagger-Codegen/1.0.0/php'; - - /** - * Debug switch (default set to false) - * - * @var bool - */ - protected $debug = false; - - /** - * Debug file location (log to STDOUT by default) - * - * @var string - */ - protected $debugFile = 'php://output'; - - /** - * Debug file location (log to STDOUT by default) - * - * @var string - */ - protected $tempFolderPath; - - /** - * Indicates if SSL verification should be enabled or disabled. - * - * This is useful if the host uses a self-signed SSL certificate. - * - * @var boolean True if the certificate should be validated, false otherwise. - */ - protected $sslVerification = true; - - /** - * Curl proxy host - * - * @var string - */ - protected $proxyHost; - - /** - * Curl proxy port - * - * @var integer - */ - protected $proxyPort; - - /** - * Curl proxy type, e.g. CURLPROXY_HTTP or CURLPROXY_SOCKS5 + * Sets the host * - * @see https://secure.php.net/manual/en/function.curl-setopt.php - * @var integer - */ - protected $proxyType; - - /** - * Curl proxy username + * @param string $host Host * - * @var string + * @return $this */ - protected $proxyUser; + public function setHost($host) + { + $this->host = $host; + return $this; + } /** - * Curl proxy password + * Gets the host * - * @var string - */ - protected $proxyPassword; - - /** - * Constructor + * @return string Host */ - public function __construct() + public function getHost() { - $this->tempFolderPath = sys_get_temp_dir(); + return $this->host; } /** * Sets API key * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $key API key or token + * @param string $key API key or token * * @return $this */ @@ -215,7 +131,7 @@ public function getApiKey($apiKeyIdentifier) * Sets the prefix for API key (e.g. Bearer) * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer + * @param string $prefix API key prefix, e.g. Bearer * * @return $this */ @@ -307,401 +223,28 @@ public function getPassword() } /** - * Adds a default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * - * @throws \InvalidArgumentException - * @return $this - */ - public function addDefaultHeader($headerName, $headerValue) - { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * Gets the default header - * - * @return array An array of default header(s) - */ - public function getDefaultHeaders() - { - return $this->defaultHeaders; - } - - /** - * Deletes a default header - * - * @param string $headerName the header to delete - * - * @return $this - */ - public function deleteDefaultHeader($headerName) - { - unset($this->defaultHeaders[$headerName]); - return $this; - } - - /** - * Sets the host - * - * @param string $host Host - * - * @return $this - */ - public function setHost($host) - { - $this->host = $host; - return $this; - } - - /** - * Gets the host - * - * @return string Host - */ - public function getHost() - { - return $this->host; - } - - /** - * Sets the user agent of the api client + * Get API key (with prefix if set) * - * @param string $userAgent the user agent of the api client + * @param string $apiKeyIdentifier name of apikey * - * @throws \InvalidArgumentException - * @return $this + * @return string API key with the prefix */ - public function setUserAgent($userAgent) + public function getApiKeyWithPrefix($apiKeyIdentifier) { - if (!is_string($userAgent)) { - throw new \InvalidArgumentException('User-agent must be a string.'); - } + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); - $this->userAgent = $userAgent; - return $this; - } - - /** - * Gets the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() - { - return $this->userAgent; - } - - /** - * Sets the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - * - * @throws \InvalidArgumentException - * @return $this - */ - public function setCurlTimeout($seconds) - { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + if ($apiKey === null) { + return null; } - $this->curlTimeout = $seconds; - return $this; - } - - /** - * Gets the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getCurlTimeout() - { - return $this->curlTimeout; - } - - /** - * Sets the HTTP connect timeout value - * - * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] - * - * @throws \InvalidArgumentException - * @return $this - */ - public function setCurlConnectTimeout($seconds) - { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; } - $this->curlConnectTimeout = $seconds; - return $this; - } - - /** - * Gets the HTTP connect timeout value - * - * @return string HTTP connect timeout value - */ - public function getCurlConnectTimeout() - { - return $this->curlConnectTimeout; - } - - - /** - * Sets the HTTP Proxy Host - * - * @param string $proxyHost HTTP Proxy URL - * - * @return $this - */ - public function setCurlProxyHost($proxyHost) - { - $this->proxyHost = $proxyHost; - return $this; - } - - /** - * Gets the HTTP Proxy Host - * - * @return string - */ - public function getCurlProxyHost() - { - return $this->proxyHost; - } - - /** - * Sets the HTTP Proxy Port - * - * @param integer $proxyPort HTTP Proxy Port - * - * @return $this - */ - public function setCurlProxyPort($proxyPort) - { - $this->proxyPort = $proxyPort; - return $this; - } - - /** - * Gets the HTTP Proxy Port - * - * @return integer - */ - public function getCurlProxyPort() - { - return $this->proxyPort; - } - - /** - * Sets the HTTP Proxy Type - * - * @param integer $proxyType HTTP Proxy Type - * - * @return $this - */ - public function setCurlProxyType($proxyType) - { - $this->proxyType = $proxyType; - return $this; - } - - /** - * Gets the HTTP Proxy Type - * - * @return integer - */ - public function getCurlProxyType() - { - return $this->proxyType; - } - - /** - * Sets the HTTP Proxy User - * - * @param string $proxyUser HTTP Proxy User - * - * @return $this - */ - public function setCurlProxyUser($proxyUser) - { - $this->proxyUser = $proxyUser; - return $this; - } - - /** - * Gets the HTTP Proxy User - * - * @return string - */ - public function getCurlProxyUser() - { - return $this->proxyUser; - } - - /** - * Sets the HTTP Proxy Password - * - * @param string $proxyPassword HTTP Proxy Password - * - * @return $this - */ - public function setCurlProxyPassword($proxyPassword) - { - $this->proxyPassword = $proxyPassword; - return $this; - } - - /** - * Gets the HTTP Proxy Password - * - * @return string - */ - public function getCurlProxyPassword() - { - return $this->proxyPassword; - } - - /** - * Sets debug flag - * - * @param bool $debug Debug flag - * - * @return $this - */ - public function setDebug($debug) - { - $this->debug = $debug; - return $this; - } - - /** - * Gets the debug flag - * - * @return bool - */ - public function getDebug() - { - return $this->debug; - } - - /** - * Sets the debug file - * - * @param string $debugFile Debug file - * - * @return $this - */ - public function setDebugFile($debugFile) - { - $this->debugFile = $debugFile; - return $this; - } - - /** - * Gets the debug file - * - * @return string - */ - public function getDebugFile() - { - return $this->debugFile; - } - - /** - * Sets the temp folder path - * - * @param string $tempFolderPath Temp folder path - * - * @return $this - */ - public function setTempFolderPath($tempFolderPath) - { - $this->tempFolderPath = $tempFolderPath; - return $this; - } - - /** - * Gets the temp folder path - * - * @return string Temp folder path - */ - public function getTempFolderPath() - { - return $this->tempFolderPath; - } - - /** - * Sets if SSL verification should be enabled or disabled - * - * @param boolean $sslVerification True if the certificate should be validated, false otherwise - * - * @return $this - */ - public function setSSLVerification($sslVerification) - { - $this->sslVerification = $sslVerification; - return $this; - } - - /** - * Gets if SSL verification should be enabled or disabled - * - * @return boolean True if the certificate should be validated, false otherwise - */ - public function getSSLVerification() - { - return $this->sslVerification; - } - - /** - * Gets the default configuration instance - * - * @return Configuration - */ - public static function getDefaultConfiguration() - { - if (self::$defaultConfiguration === null) { - self::$defaultConfiguration = new Configuration(); - } - - return self::$defaultConfiguration; - } - - /** - * Sets the detault configuration instance - * - * @param Configuration $config An instance of the Configuration Object - * - * @return void - */ - public static function setDefaultConfiguration(Configuration $config) - { - self::$defaultConfiguration = $config; - } - - /** - * Gets the essential information for debugging - * - * @return string The report for debugging - */ - public static function toDebugReport() - { - $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; - $report .= ' OS: ' . php_uname() . PHP_EOL; - $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; - $report .= ' OpenAPI Spec Version: 1.0.0' . PHP_EOL; - $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; - - return $report; + return $keyWithPrefix; } } + From a06c485c63c26758a74b3d19a7248f6d28e1d215 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Sat, 18 Mar 2017 14:55:07 +0000 Subject: [PATCH 16/37] added HeaderSelector template --- .../codegen/languages/PhpClientCodegen.java | 1 + .../resources/php/HeaderSelector.mustache | 100 +++++++++++++++++ .../src/main/resources/php/api.mustache | 13 ++- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 39 ++++--- .../php/SwaggerClient-php/lib/Api/PetApi.php | 104 +++++++++++------- .../SwaggerClient-php/lib/Api/StoreApi.php | 52 +++++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 104 +++++++++++------- .../SwaggerClient-php/lib/HeaderSelector.php | 28 +++-- .../tests/HeaderSelectorTest.php | 19 +++- 9 files changed, 331 insertions(+), 129 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/php/HeaderSelector.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 76154f3f701..b39afba95ce 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -303,6 +303,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); + supportingFiles.add(new SupportingFile("HeaderSelector.mustache", toPackagePath(invokerPackage, srcBasePath), "HeaderSelector.php")); supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); diff --git a/modules/swagger-codegen/src/main/resources/php/HeaderSelector.mustache b/modules/swagger-codegen/src/main/resources/php/HeaderSelector.mustache new file mode 100644 index 00000000000..909beb134d2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/HeaderSelector.mustache @@ -0,0 +1,100 @@ +partial_header}} +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +namespace {{invokerPackage}}; + +use \Exception; + +/** + * ApiException Class Doc Comment + * + * @category Class + * @package {{invokerPackage}} + * @author Swagger Codegen team + * @link https://github.com/swagger-api/swagger-codegen + */ +class HeaderSelector +{ + + /** + * @param string[] $accept + * @param string[] $contentTypes + * @return array + */ + public function selectHeaders($accept, $contentTypes) + { + $headers = []; + + $accept = $this->selectAcceptHeader($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + $headers['Content-Type'] = $this->selectContentTypeHeader($contentTypes); + return $headers; + } + + /** + * @param string[] $accept + * @return array + */ + public function selectHeadersForMultipart($accept) + { + $headers = $this->selectHeaders($accept, []); + + unset($headers['Content-Type']); + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * + * @return string Accept (e.g. application/json) + */ + private function selectAcceptHeader($accept) + { + if (count($accept) === 0 || (count($accept) === 1 && $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 string[] $contentType Array fo content-type + * + * @return string Content-Type (e.g. application/json) + */ + private function selectContentTypeHeader($contentType) + { + if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $contentType)) { + return 'application/json'; + } else { + return implode(',', $contentType); + } + } +} + diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index a5099d22f78..c3206f28f94 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -254,12 +254,15 @@ use {{invokerPackage}}\ObjectSerializer; */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}], - [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}], + [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + ); } try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index dffa0f3b973..5359d88ccdb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -138,12 +138,15 @@ public function testClientModelWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/json'], - ['application/json'] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] + ); } try { @@ -401,12 +404,15 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml; charset=utf-8', 'application/json; charset=utf-8'], - ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml; charset=utf-8', 'application/json; charset=utf-8'], + ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] + ); } try { @@ -559,12 +565,15 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['*/*'], - ['*/*'] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['*/*'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['*/*'] + ); } try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 65a0ae7de42..6107cd9aacc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -141,12 +141,15 @@ public function addPetWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - ['application/json', 'application/xml'] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); } try { @@ -263,12 +266,15 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -381,12 +387,15 @@ public function findPetsByStatusWithHttpInfo($status) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -511,12 +520,15 @@ public function findPetsByTagsWithHttpInfo($tags) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -639,12 +651,15 @@ public function getPetByIdWithHttpInfo($pet_id) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -766,12 +781,15 @@ public function updatePetWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - ['application/json', 'application/xml'] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); } try { @@ -892,12 +910,15 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - ['application/x-www-form-urlencoded'] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/x-www-form-urlencoded'] + ); } try { @@ -1020,12 +1041,15 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/json'], - ['multipart/form-data'] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['multipart/form-data'] + ); } try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index e6091f4fd2b..043e4c17564 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -143,12 +143,15 @@ public function deleteOrderWithHttpInfo($order_id) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -249,12 +252,15 @@ public function getInventoryWithHttpInfo() */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); } try { @@ -386,12 +392,15 @@ public function getOrderByIdWithHttpInfo($order_id) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -510,12 +519,15 @@ public function placeOrderWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 050216fa1e5..24093fd98aa 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -137,12 +137,15 @@ public function createUserWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -248,12 +251,15 @@ public function createUsersWithArrayInputWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -359,12 +365,15 @@ public function createUsersWithListInputWithHttpInfo($body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -469,12 +478,15 @@ public function deleteUserWithHttpInfo($username) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -580,12 +592,15 @@ public function getUserByNameWithHttpInfo($username) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -713,12 +728,15 @@ public function loginUserWithHttpInfo($username, $password) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -825,12 +843,15 @@ public function logoutUserWithHttpInfo() */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { @@ -946,12 +967,15 @@ public function updateUserWithHttpInfo($username, $body) */ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json'], - [] - ); if ($httpBody instanceof MultipartStream) { - unset($headers['Content-Type']); + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); } try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php b/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php index 4683e17bc7e..77cee4dd319 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php @@ -28,6 +28,8 @@ namespace Swagger\Client; +use \Exception; + /** * ApiException Class Doc Comment * @@ -40,20 +42,32 @@ class HeaderSelector { /** - * @param $accept - * @param $contentTypes + * @param string[] $accept + * @param string[] $contentTypes * @return array */ public function selectHeaders($accept, $contentTypes) { $headers = []; - $accept = $this->selectHeaderAccept($accept); + $accept = $this->selectAcceptHeader($accept); if ($accept !== null) { $headers['Accept'] = $accept; } - $headers['Content-Type'] = $this->selectHeaderContentType($contentTypes); + $headers['Content-Type'] = $this->selectContentTypeHeader($contentTypes); + return $headers; + } + + /** + * @param string[] $accept + * @return array + */ + public function selectHeadersForMultipart($accept) + { + $headers = $this->selectHeaders($accept, []); + + unset($headers['Content-Type']); return $headers; } @@ -64,7 +78,7 @@ public function selectHeaders($accept, $contentTypes) * * @return string Accept (e.g. application/json) */ - private function selectHeaderAccept($accept) + private function selectAcceptHeader($accept) { if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) { return null; @@ -82,7 +96,7 @@ private function selectHeaderAccept($accept) * * @return string Content-Type (e.g. application/json) */ - private function selectHeaderContentType($contentType) + private function selectContentTypeHeader($contentType) { if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { return 'application/json'; @@ -92,5 +106,5 @@ private function selectHeaderContentType($contentType) return implode(',', $contentType); } } - } + diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php index e0580064b63..7a89448f89e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php @@ -6,7 +6,6 @@ class HeaderSelectorTest extends \PHPUnit_Framework_TestCase { public function testSelectingHeaders() { - // test selectHeaderAccept $selector = new HeaderSelector(); $headers = $selector->selectHeaders([ 'application/xml', @@ -15,7 +14,7 @@ public function testSelectingHeaders() $this->assertSame('application/json', $headers['Accept']); $headers = $selector->selectHeaders([], []); - $this->assertFalse(isset($headers['Accept'])); + $this->assertArrayNotHasKey('Accept', $headers); $header = $selector->selectHeaders([ 'application/yaml', @@ -38,4 +37,20 @@ public function testSelectingHeaders() ]); $this->assertSame('application/yaml,application/xml', $headers['Content-Type']); } + + public function testSelectingHeadersForMultipartBody() + { + // test selectHeaderAccept + $selector = new HeaderSelector(); + $headers = $selector->selectHeadersForMultipart([ + 'application/xml', + 'application/json' + ]); + $this->assertSame('application/json', $headers['Accept']); + $this->assertArrayNotHasKey('Content-Type', $headers); + + $headers = $selector->selectHeadersForMultipart([]); + $this->assertArrayNotHasKey('Accept', $headers); + $this->assertArrayNotHasKey('Content-Type', $headers); + } } From 066291fb798950e177df1c37999771a3c11671e3 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Sat, 18 Mar 2017 15:20:33 +0000 Subject: [PATCH 17/37] added ObjectSerializer injection --- modules/swagger-codegen/src/main/resources/php/api.mustache | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index c3206f28f94..4e621dba469 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -49,11 +49,13 @@ use {{invokerPackage}}\ObjectSerializer; /** * @param HttpClient $client + * @param HeaderSelector $selector + * @param ObjectSerializer $serializer */ - public function __construct(HttpClient $client, HeaderSelector $selector = null) + public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) { $this->client = $client; - $this->serializer = new ObjectSerializer(); + $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); } From 95784cbd7f2dccaf9e77b72f82e01684d36419f7 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Sat, 18 Mar 2017 15:20:44 +0000 Subject: [PATCH 18/37] regenerated all samples --- .../php/SwaggerClient-php/composer.json | 11 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 127 ++-- .../php/SwaggerClient-php/lib/ApiClient.php | 367 --------- .../SwaggerClient-php/lib/Configuration.php | 702 ------------------ .../SwaggerClient-php/lib/HeaderSelector.php | 110 +++ .../lib/ObjectSerializer.php | 18 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 6 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 6 +- .../SwaggerClient-php/lib/Api/StoreApi.php | 6 +- .../php/SwaggerClient-php/lib/Api/UserApi.php | 6 +- 10 files changed, 221 insertions(+), 1138 deletions(-) delete mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php delete mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php create mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/lib/HeaderSelector.php diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json index 7d1a19b4318..bf27b85e1e8 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json @@ -19,13 +19,16 @@ "php": ">=5.4", "ext-curl": "*", "ext-json": "*", - "ext-mbstring": "*" + "ext-mbstring": "*", + "php-http/httplug": "^1.1", + "guzzlehttp/psr7": "^1.4" }, "require-dev": { - "phpunit/phpunit": "~4.8", - "satooshi/php-coveralls": "~1.0", + "phpunit/phpunit": "^5.0", "squizlabs/php_codesniffer": "~2.6", - "friendsofphp/php-cs-fixer": "~1.12" + "friendsofphp/php-cs-fixer": "~1.12", + "php-http/guzzle6-adapter": "^1.1", + "php-http/curl-client": "^1.7" }, "autoload": { "psr-4": { "Swagger\\Client\\" : "lib/" } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 07f9f0e92fb..389f232679f 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -28,10 +28,14 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Psr7\MultipartStream; +use GuzzleHttp\Psr7\Request; +use GuzzleHttp\Psr7\Uri; +use Http\Client\Exception; +use Http\Client\HttpClient; +use Swagger\Client\ApiException; +use Swagger\Client\HeaderSelector; +use Swagger\Client\ObjectSerializer; /** * FakeApi Class Doc Comment @@ -44,47 +48,25 @@ class FakeApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient - */ - protected $apiClient; - - /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var HttpClient */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } - - $this->apiClient = $apiClient; - } + protected $client; /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @var ObjectSerializer */ - public function getApiClient() - { - return $this->apiClient; - } + protected $serializer; /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return FakeApi + * @param HttpClient $client + * @param HeaderSelector $selector + * @param ObjectSerializer $serializer */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) + public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) { - $this->apiClient = $apiClient; - return $this; + $this->client = $client; + $this->serializer = $serializer ?: new ObjectSerializer(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -94,12 +76,12 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) * * @param string $test_code_inject____end____rn_n_r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return void */ public function testCodeInjectEndRnNR($test_code_inject____end____rn_n_r = null) { - list($response) = $this->testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r); - return $response; + $this->testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r); } /** @@ -109,37 +91,73 @@ public function testCodeInjectEndRnNR($test_code_inject____end____rn_n_r = null) * * @param string $test_code_inject____end____rn_n_r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r = null) { - // parse inputs - $resourcePath = "/fake"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = substr('/fake', 1); $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/json', '*_/ \" =end --']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', '*_/ \" =end --']); + $queryParams = []; + $httpBody = ''; + $multipart = false; + $returnType = ''; + - // default format to json - $resourcePath = str_replace("{format}", "json", $resourcePath); // form params if ($test_code_inject____end____rn_n_r !== null) { - $formParams['test code inject */ ' " =end -- \r\n \n \r'] = $this->apiClient->getSerializer()->toFormValue($test_code_inject____end____rn_n_r); + $formParams['test code inject */ ' " =end -- \r\n \n \r'] = $this->serializer->toFormValue($test_code_inject____end____rn_n_r); } // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } - // make the API Call +/** +*/ + $query = \GuzzleHttp\Psr7\build_query($queryParams); + + if ($httpBody instanceof MultipartStream) { + $headers = $this->headerSelector->selectHeadersForMultipart( + ['application/json', '*_/ \" =end --'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json', '*_/ \" =end --'], + ['application/json', '*_/ \" =end --'] + ); + } + + try { + $request = new Request( + 'PUT', + Uri::composeComponents('', '', $resourcePath, $query, ''), + $headers, + $httpBody + ); + $response = $this->client->sendRequest($request); + return [null, $response->getStatusCode(), $response->getHeaders()]; + } catch (Exception $exception) { + throw new ApiException($exception->getMessage(), null, $exception); + } +/** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, @@ -158,5 +176,6 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn throw $e; } +*/ } } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php deleted file mode 100644 index ea22b4f99ee..00000000000 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php +++ /dev/null @@ -1,367 +0,0 @@ -config = $config; - $this->serializer = new ObjectSerializer(); - } - - /** - * Get the config - * - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Get the serializer - * - * @return ObjectSerializer - */ - public function getSerializer() - { - return $this->serializer; - } - - /** - * Get API key (with prefix if set) - * - * @param string $apiKeyIdentifier name of apikey - * - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKeyIdentifier) - { - $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); - $apiKey = $this->config->getApiKey($apiKeyIdentifier); - - if (!isset($apiKey)) { - return null; - } - - if (isset($prefix)) { - $keyWithPrefix = $prefix." ".$apiKey; - } else { - $keyWithPrefix = $apiKey; - } - - return $keyWithPrefix; - } - - /** - * Make the HTTP call (Sync) - * - * @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 - * @param string $responseType expected response type of the endpoint - * @param string $endpointPath path to method endpoint before expanding parameters - * - * @throws \Swagger\Client\ApiException on a non 2xx response - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) - { - $headers = []; - - // construct the http header - $headerParams = array_merge( - (array)$this->config->getDefaultHeaders(), - (array)$headerParams - ); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { - $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model - $postData = json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($postData)); - } - - $url = $this->config->getHost() . $resourcePath; - - $curl = curl_init(); - // set timeout, if needed - if ($this->config->getCurlTimeout() !== 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); - } - // set connect timeout, if needed - if ($this->config->getCurlConnectTimeout() != 0) { - curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); - } - - // return the result on success, rather than just true - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - // disable SSL verification, if needed - if ($this->config->getSSLVerification() === false) { - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); - } - - if ($this->config->getCurlProxyHost()) { - curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); - } - - if ($this->config->getCurlProxyPort()) { - curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); - } - - if ($this->config->getCurlProxyType()) { - curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); - } - - if ($this->config->getCurlProxyUser()) { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); - } - - 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); - } elseif ($method === self::$HEAD) { - curl_setopt($curl, CURLOPT_NOBODY, true); - } elseif ($method === self::$OPTIONS) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($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->config->getUserAgent()); - - // debugging for curl - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), '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 = $this->httpParseHeaders(substr($response, 0, $http_header_size)); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); - - // debug HTTP response body - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - } - - // Handle the response - if ($response_info['http_code'] === 0) { - $curl_error_message = curl_error($curl); - - // curl_exec can sometimes fail but still return a blank message from curl_error(). - if (!empty($curl_error_message)) { - $error_message = "API call to $url failed: $curl_error_message"; - } else { - $error_message = "API call to $url failed, but for an unknown reason. " . - "This could happen if you are disconnected from the network."; - } - - $exception = new ApiException($error_message, 0, null, null); - $exception->setResponseObject($response_info); - throw $exception; - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { - // return raw body if response is a file - if ($responseType === '\SplFileObject' || $responseType === 'string') { - return [$http_body, $response_info['http_code'], $http_header]; - } - - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - } else { - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - - throw new ApiException( - "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], - $http_header, - $data - ); - } - return [$data, $response_info['http_code'], $http_header]; - } - - /** - * Return the header 'Accept' based on an array of Accept provided - * - * @param string[] $accept Array of header - * - * @return string Accept (e.g. application/json) - */ - public 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 string[] $content_type Array fo content-type - * - * @return string Content-Type (e.g. application/json) - */ - public 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); - } - } - - /** - * Return an array of HTTP response headers - * - * @param string $raw_headers A string of raw HTTP response headers - * - * @return string[] Array of HTTP response heaers - */ - protected function httpParseHeaders($raw_headers) - { - // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 - $headers = []; - $key = ''; - - foreach (explode("\n", $raw_headers) as $h) { - $h = explode(':', $h, 2); - - if (isset($h[1])) { - if (!isset($headers[$h[0]])) { - $headers[$h[0]] = trim($h[1]); - } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); - } else { - $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); - } - - $key = $h[0]; - } else { - if (substr($h[0], 0, 1) === "\t") { - $headers[$key] .= "\r\n\t".trim($h[0]); - } elseif (!$key) { - $headers[0] = trim($h[0]); - } - trim($h[0]); - } - } - - return $headers; - } -} diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php deleted file mode 100644 index d430f0c7717..00000000000 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ /dev/null @@ -1,702 +0,0 @@ -tempFolderPath = sys_get_temp_dir(); - } - - /** - * Sets API key - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $key API key or token - * - * @return Configuration - */ - public function setApiKey($apiKeyIdentifier, $key) - { - $this->apiKeys[$apiKeyIdentifier] = $key; - return $this; - } - - /** - * Gets API key - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return string API key or token - */ - public function getApiKey($apiKeyIdentifier) - { - return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; - } - - /** - * Sets the prefix for API key (e.g. Bearer) - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer - * - * @return Configuration - */ - public function setApiKeyPrefix($apiKeyIdentifier, $prefix) - { - $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; - return $this; - } - - /** - * Gets API key prefix - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return string - */ - public function getApiKeyPrefix($apiKeyIdentifier) - { - return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; - } - - /** - * Sets the access token for OAuth - * - * @param string $accessToken Token for OAuth - * - * @return Configuration - */ - public function setAccessToken($accessToken) - { - $this->accessToken = $accessToken; - return $this; - } - - /** - * Gets the access token for OAuth - * - * @return string Access token for OAuth - */ - public function getAccessToken() - { - return $this->accessToken; - } - - /** - * Sets the username for HTTP basic authentication - * - * @param string $username Username for HTTP basic authentication - * - * @return Configuration - */ - public function setUsername($username) - { - $this->username = $username; - return $this; - } - - /** - * Gets the username for HTTP basic authentication - * - * @return string Username for HTTP basic authentication - */ - public function getUsername() - { - return $this->username; - } - - /** - * Sets the password for HTTP basic authentication - * - * @param string $password Password for HTTP basic authentication - * - * @return Configuration - */ - public function setPassword($password) - { - $this->password = $password; - return $this; - } - - /** - * Gets the password for HTTP basic authentication - * - * @return string Password for HTTP basic authentication - */ - public function getPassword() - { - return $this->password; - } - - /** - * Adds a default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * - * @return Configuration - */ - public function addDefaultHeader($headerName, $headerValue) - { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * Gets the default header - * - * @return array An array of default header(s) - */ - public function getDefaultHeaders() - { - return $this->defaultHeaders; - } - - /** - * Deletes a default header - * - * @param string $headerName the header to delete - * - * @return Configuration - */ - public function deleteDefaultHeader($headerName) - { - unset($this->defaultHeaders[$headerName]); - } - - /** - * Sets the host - * - * @param string $host Host - * - * @return Configuration - */ - public function setHost($host) - { - $this->host = $host; - return $this; - } - - /** - * Gets the host - * - * @return string Host - */ - public function getHost() - { - return $this->host; - } - - /** - * Sets the user agent of the api client - * - * @param string $userAgent the user agent of the api client - * - * @return Configuration - */ - public function setUserAgent($userAgent) - { - if (!is_string($userAgent)) { - throw new \InvalidArgumentException('User-agent must be a string.'); - } - - $this->userAgent = $userAgent; - return $this; - } - - /** - * Gets the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() - { - return $this->userAgent; - } - - /** - * Sets the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - * - * @return Configuration - */ - public function setCurlTimeout($seconds) - { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - } - - $this->curlTimeout = $seconds; - return $this; - } - - /** - * Gets the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getCurlTimeout() - { - return $this->curlTimeout; - } - - /** - * Sets the HTTP connect timeout value - * - * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] - * - * @return Configuration - */ - public function setCurlConnectTimeout($seconds) - { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); - } - - $this->curlConnectTimeout = $seconds; - return $this; - } - - /** - * Gets the HTTP connect timeout value - * - * @return string HTTP connect timeout value - */ - public function getCurlConnectTimeout() - { - return $this->curlConnectTimeout; - } - - - /** - * Sets the HTTP Proxy Host - * - * @param string $proxyHost HTTP Proxy URL - * - * @return ApiClient - */ - public function setCurlProxyHost($proxyHost) - { - $this->proxyHost = $proxyHost; - return $this; - } - - /** - * Gets the HTTP Proxy Host - * - * @return string - */ - public function getCurlProxyHost() - { - return $this->proxyHost; - } - - /** - * Sets the HTTP Proxy Port - * - * @param integer $proxyPort HTTP Proxy Port - * - * @return ApiClient - */ - public function setCurlProxyPort($proxyPort) - { - $this->proxyPort = $proxyPort; - return $this; - } - - /** - * Gets the HTTP Proxy Port - * - * @return integer - */ - public function getCurlProxyPort() - { - return $this->proxyPort; - } - - /** - * Sets the HTTP Proxy Type - * - * @param integer $proxyType HTTP Proxy Type - * - * @return ApiClient - */ - public function setCurlProxyType($proxyType) - { - $this->proxyType = $proxyType; - return $this; - } - - /** - * Gets the HTTP Proxy Type - * - * @return integer - */ - public function getCurlProxyType() - { - return $this->proxyType; - } - - /** - * Sets the HTTP Proxy User - * - * @param string $proxyUser HTTP Proxy User - * - * @return ApiClient - */ - public function setCurlProxyUser($proxyUser) - { - $this->proxyUser = $proxyUser; - return $this; - } - - /** - * Gets the HTTP Proxy User - * - * @return string - */ - public function getCurlProxyUser() - { - return $this->proxyUser; - } - - /** - * Sets the HTTP Proxy Password - * - * @param string $proxyPassword HTTP Proxy Password - * - * @return ApiClient - */ - public function setCurlProxyPassword($proxyPassword) - { - $this->proxyPassword = $proxyPassword; - return $this; - } - - /** - * Gets the HTTP Proxy Password - * - * @return string - */ - public function getCurlProxyPassword() - { - return $this->proxyPassword; - } - - /** - * Sets debug flag - * - * @param bool $debug Debug flag - * - * @return Configuration - */ - public function setDebug($debug) - { - $this->debug = $debug; - return $this; - } - - /** - * Gets the debug flag - * - * @return bool - */ - public function getDebug() - { - return $this->debug; - } - - /** - * Sets the debug file - * - * @param string $debugFile Debug file - * - * @return Configuration - */ - public function setDebugFile($debugFile) - { - $this->debugFile = $debugFile; - return $this; - } - - /** - * Gets the debug file - * - * @return string - */ - public function getDebugFile() - { - return $this->debugFile; - } - - /** - * Sets the temp folder path - * - * @param string $tempFolderPath Temp folder path - * - * @return Configuration - */ - public function setTempFolderPath($tempFolderPath) - { - $this->tempFolderPath = $tempFolderPath; - return $this; - } - - /** - * Gets the temp folder path - * - * @return string Temp folder path - */ - public function getTempFolderPath() - { - return $this->tempFolderPath; - } - - /** - * Sets if SSL verification should be enabled or disabled - * - * @param boolean $sslVerification True if the certificate should be validated, false otherwise - * - * @return Configuration - */ - public function setSSLVerification($sslVerification) - { - $this->sslVerification = $sslVerification; - return $this; - } - - /** - * Gets if SSL verification should be enabled or disabled - * - * @return boolean True if the certificate should be validated, false otherwise - */ - public function getSSLVerification() - { - return $this->sslVerification; - } - - /** - * Gets the default configuration instance - * - * @return Configuration - */ - public static function getDefaultConfiguration() - { - if (self::$defaultConfiguration === null) { - self::$defaultConfiguration = new Configuration(); - } - - return self::$defaultConfiguration; - } - - /** - * Sets the detault configuration instance - * - * @param Configuration $config An instance of the Configuration Object - * - * @return void - */ - public static function setDefaultConfiguration(Configuration $config) - { - self::$defaultConfiguration = $config; - } - - /** - * Gets the essential information for debugging - * - * @return string The report for debugging - */ - public static function toDebugReport() - { - $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; - $report .= ' OS: ' . php_uname() . PHP_EOL; - $report .= ' PHP Version: ' . phpversion() . PHP_EOL; - $report .= ' OpenAPI Spec Version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r' . PHP_EOL; - $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; - - return $report; - } -} diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/HeaderSelector.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/HeaderSelector.php new file mode 100644 index 00000000000..a12b0f6e1ed --- /dev/null +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/HeaderSelector.php @@ -0,0 +1,110 @@ +selectAcceptHeader($accept); + if ($accept !== null) { + $headers['Accept'] = $accept; + } + + $headers['Content-Type'] = $this->selectContentTypeHeader($contentTypes); + return $headers; + } + + /** + * @param string[] $accept + * @return array + */ + public function selectHeadersForMultipart($accept) + { + $headers = $this->selectHeaders($accept, []); + + unset($headers['Content-Type']); + return $headers; + } + + /** + * Return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * + * @return string Accept (e.g. application/json) + */ + private function selectAcceptHeader($accept) + { + if (count($accept) === 0 || (count($accept) === 1 && $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 string[] $contentType Array fo content-type + * + * @return string Content-Type (e.g. application/json) + */ + private function selectContentTypeHeader($contentType) + { + if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $contentType)) { + return 'application/json'; + } else { + return implode(',', $contentType); + } + } +} + diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index 4bfe77988bd..759790e17e3 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -59,10 +59,16 @@ public static function sanitizeForSerialization($data) return $data; } elseif (is_object($data)) { $values = []; - foreach (array_keys($data::swaggerTypes()) as $property) { + foreach ($data::swaggerTypes() as $property => $swaggerType) { $getter = $data::getters()[$property]; - if ($data->$getter() !== null) { - $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($data->$getter()); + $value = $data->$getter(); + if (method_exists($swaggerType, 'getAllowableEnumValues') + && !in_array($value, $swaggerType::getAllowableEnumValues())) { + $imploded = implode("', '", $swaggerType::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$swaggerType', must be one of: '$imploded'"); + } + if ($value !== null) { + $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value); } } return (object)$values; @@ -269,6 +275,12 @@ public static function deserialize($data, $class, $httpHeaders = null) } return $deserialized; + } elseif (method_exists($class, 'getAllowableEnumValues')) { + if (!in_array($data, $class::getAllowableEnumValues())) { + $imploded = implode("', '", $class::getAllowableEnumValues()); + throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); + } + return $data; } else { // If a discriminator is defined and points to a valid subclass, use it. $discriminator = $class::DISCRIMINATOR; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 5359d88ccdb..2b977b5759c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -59,11 +59,13 @@ class FakeApi /** * @param HttpClient $client + * @param HeaderSelector $selector + * @param ObjectSerializer $serializer */ - public function __construct(HttpClient $client, HeaderSelector $selector = null) + public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) { $this->client = $client; - $this->serializer = new ObjectSerializer(); + $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 6107cd9aacc..6b6d3fed5cd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -59,11 +59,13 @@ class PetApi /** * @param HttpClient $client + * @param HeaderSelector $selector + * @param ObjectSerializer $serializer */ - public function __construct(HttpClient $client, HeaderSelector $selector = null) + public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) { $this->client = $client; - $this->serializer = new ObjectSerializer(); + $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 043e4c17564..afe282b8d8b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -59,11 +59,13 @@ class StoreApi /** * @param HttpClient $client + * @param HeaderSelector $selector + * @param ObjectSerializer $serializer */ - public function __construct(HttpClient $client, HeaderSelector $selector = null) + public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) { $this->client = $client; - $this->serializer = new ObjectSerializer(); + $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 24093fd98aa..7e1e39b57ce 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -59,11 +59,13 @@ class UserApi /** * @param HttpClient $client + * @param HeaderSelector $selector + * @param ObjectSerializer $serializer */ - public function __construct(HttpClient $client, HeaderSelector $selector = null) + public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) { $this->client = $client; - $this->serializer = new ObjectSerializer(); + $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); } From 4d13b9e0bb4a4be58159de9db67c29340203b6ab Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Tue, 21 Mar 2017 09:02:04 +0000 Subject: [PATCH 19/37] added AuthConfig and readded support for custom api keys --- .../codegen/languages/PhpClientCodegen.java | 1 + .../main/resources/php/AuthConfig.mustache | 212 ++++++++++ .../src/main/resources/php/api.mustache | 56 ++- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 28 +- .../SwaggerClient-php/lib/ApiException.php | 12 +- .../php/SwaggerClient-php/lib/AuthConfig.php | 222 +++++++++++ .../php/SwaggerClient-php/lib/Api/FakeApi.php | 46 ++- .../php/SwaggerClient-php/lib/Api/PetApi.php | 138 ++++--- .../SwaggerClient-php/lib/Api/StoreApi.php | 52 ++- .../php/SwaggerClient-php/lib/Api/UserApi.php | 56 +-- .../php/SwaggerClient-php/lib/ApiClient.php | 367 ++++++++++++++++++ .../php/SwaggerClient-php/lib/AuthConfig.php | 222 +++++++++++ .../tests/FakeHttpClient.php | 38 ++ .../SwaggerClient-php/tests/PetApiTest.php | 18 + 14 files changed, 1320 insertions(+), 148 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/php/AuthConfig.mustache create mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/AuthConfig.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index b39afba95ce..62ea2eed56a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -302,6 +302,7 @@ public void processOpts() { additionalProperties.put("testBasePath", testBasePath); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); + supportingFiles.add(new SupportingFile("AuthConfig.mustache", toPackagePath(invokerPackage, srcBasePath), "AuthConfig.php")); supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); supportingFiles.add(new SupportingFile("HeaderSelector.mustache", toPackagePath(invokerPackage, srcBasePath), "HeaderSelector.php")); supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); diff --git a/modules/swagger-codegen/src/main/resources/php/AuthConfig.mustache b/modules/swagger-codegen/src/main/resources/php/AuthConfig.mustache new file mode 100644 index 00000000000..5ca5113d6a2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/AuthConfig.mustache @@ -0,0 +1,212 @@ +partial_header}} +/** + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +namespace {{invokerPackage}}; + +/** + * AuthConfig Class Doc Comment + * + * @category Class + * @package {{invokerPackage}} + * @author Swagger Codegen team + * @link https://github.com/swagger-api/swagger-codegen + */ +class AuthConfig +{ + /** + * Associate array to store API key(s) + * + * @var string[] + */ + protected $apiKeys = []; + + /** + * Associate array to store API prefix (e.g. Bearer) + * + * @var string[] + */ + protected $apiKeyPrefixes = []; + + /** + * Access token for OAuth + * + * @var string + */ + protected $accessToken = ''; + + /** + * Username for HTTP basic authentication + * + * @var string + */ + protected $username = ''; + + /** + * Password for HTTP basic authentication + * + * @var string + */ + protected $password = ''; + + /** + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * + * @return $this + */ + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } +} + diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 4e621dba469..489de599eed 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -24,6 +24,7 @@ use GuzzleHttp\Psr7\Uri; use Http\Client\Exception; use Http\Client\HttpClient; use {{invokerPackage}}\ApiException; +use {{invokerPackage}}\AuthConfig; use {{invokerPackage}}\HeaderSelector; use {{invokerPackage}}\ObjectSerializer; @@ -47,16 +48,35 @@ use {{invokerPackage}}\ObjectSerializer; */ protected $serializer; + /** + * @var AuthConfig + */ + protected $authConfig; + /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer + * @param AuthConfig $authConfig */ - public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) - { + public function __construct( + HttpClient $client, + AuthConfig $authConfig = null, + HeaderSelector $selector = null, + ObjectSerializer $serializer = null + ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); + $this->authConfig = $authConfig ?: new AuthConfig(); + } + + /** + * @return AuthConfig + */ + public function getAuthConfig() + { + return $this->authConfig; } {{#operation}} @@ -231,15 +251,26 @@ use {{invokerPackage}}\ObjectSerializer; $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** + + if ($httpBody instanceof MultipartStream) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}], + [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + ); + } {{#authMethods}} {{#isApiKey}} // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); - if (strlen($apiKey) !== 0) { - {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} + $apiKey = $this->authConfig->getApiKeyWithPrefix('{{keyParamName}}'); + if ($apiKey !== null) { + {{#isKeyInHeader}}$headers['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} } {{/isApiKey}} + /** {{#isBasic}} // this endpoint requires HTTP basic authentication if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { @@ -252,21 +283,10 @@ use {{invokerPackage}}\ObjectSerializer; $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); } {{/isOAuth}} + */ {{/authMethods}} -*/ $query = \GuzzleHttp\Psr7\build_query($queryParams); - if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( - [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - ); - } else { - $headers = $this->headerSelector->selectHeaders( - [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}], - [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - ); - } - try { $request = new Request( '{{httpMethod}}', diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 389f232679f..bc81a545148 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -34,6 +34,7 @@ use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; +use Swagger\Client\AuthConfig; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -57,16 +58,35 @@ class FakeApi */ protected $serializer; + /** + * @var AuthConfig + */ + protected $authConfig; + /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer + * @param AuthConfig $authConfig */ - public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) - { + public function __construct( + HttpClient $client, + AuthConfig $authConfig = null, + HeaderSelector $selector = null, + ObjectSerializer $serializer = null + ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); + $this->authConfig = $authConfig ?: new AuthConfig(); + } + + /** + * @return AuthConfig + */ + public function getAuthConfig() + { + return $this->authConfig; } /** @@ -130,9 +150,6 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -144,6 +161,7 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn ['application/json', '*_/ \" =end --'] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php index 6bc8c02024d..752176f5cd7 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php @@ -51,7 +51,7 @@ class ApiException extends Exception /** * The HTTP header of the server response. * - * @var string[] + * @var string[]|null */ protected $responseHeaders; @@ -65,10 +65,10 @@ class ApiException extends Exception /** * Constructor * - * @param string $message Error message - * @param int $code HTTP status code - * @param string[] $responseHeaders HTTP response header - * @param mixed $responseBody HTTP decoded body of the server response either as \stdClass or string + * @param string $message Error message + * @param int $code HTTP status code + * @param string[]|null $responseHeaders HTTP response header + * @param mixed $responseBody HTTP decoded body of the server response either as \stdClass or string */ public function __construct($message = "", $code = 0, $responseHeaders = [], $responseBody = null) { @@ -80,7 +80,7 @@ public function __construct($message = "", $code = 0, $responseHeaders = [], $re /** * Gets the HTTP response header * - * @return string[] HTTP response headers + * @return string[]|null HTTP response header */ public function getResponseHeaders() { diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php new file mode 100644 index 00000000000..2880ade430c --- /dev/null +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php @@ -0,0 +1,222 @@ +apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } +} + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 2b977b5759c..0c24cceb470 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -34,6 +34,7 @@ use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; +use Swagger\Client\AuthConfig; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -57,16 +58,35 @@ class FakeApi */ protected $serializer; + /** + * @var AuthConfig + */ + protected $authConfig; + /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer + * @param AuthConfig $authConfig */ - public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) - { + public function __construct( + HttpClient $client, + AuthConfig $authConfig = null, + HeaderSelector $selector = null, + ObjectSerializer $serializer = null + ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); + $this->authConfig = $authConfig ?: new AuthConfig(); + } + + /** + * @return AuthConfig + */ + public function getAuthConfig() + { + return $this->authConfig; } /** @@ -136,9 +156,6 @@ public function testClientModelWithHttpInfo($body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -150,6 +167,7 @@ public function testClientModelWithHttpInfo($body) ['application/json'] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -398,13 +416,6 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires HTTP basic authentication - if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { - $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -416,6 +427,13 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] ); } + /** + // this endpoint requires HTTP basic authentication + if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { + $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -563,9 +581,6 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -577,6 +592,7 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ ['*/*'] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 6b6d3fed5cd..61bc149536c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -34,6 +34,7 @@ use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; +use Swagger\Client\AuthConfig; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -57,16 +58,35 @@ class PetApi */ protected $serializer; + /** + * @var AuthConfig + */ + protected $authConfig; + /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer + * @param AuthConfig $authConfig */ - public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) - { + public function __construct( + HttpClient $client, + AuthConfig $authConfig = null, + HeaderSelector $selector = null, + ObjectSerializer $serializer = null + ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); + $this->authConfig = $authConfig ?: new AuthConfig(); + } + + /** + * @return AuthConfig + */ + public function getAuthConfig() + { + return $this->authConfig; } /** @@ -135,13 +155,6 @@ public function addPetWithHttpInfo($body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -153,6 +166,13 @@ public function addPetWithHttpInfo($body) ['application/json', 'application/xml'] ); } + /** + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -260,13 +280,6 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -278,6 +291,13 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) [] ); } + /** + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -381,13 +401,6 @@ public function findPetsByStatusWithHttpInfo($status) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -399,6 +412,13 @@ public function findPetsByStatusWithHttpInfo($status) [] ); } + /** + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -514,13 +534,6 @@ public function findPetsByTagsWithHttpInfo($tags) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -532,6 +545,13 @@ public function findPetsByTagsWithHttpInfo($tags) [] ); } + /** + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -644,14 +664,6 @@ public function getPetByIdWithHttpInfo($pet_id) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -663,6 +675,14 @@ public function getPetByIdWithHttpInfo($pet_id) [] ); } + // this endpoint requires API key authentication + $apiKey = $this->authConfig->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + /** + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -775,13 +795,6 @@ public function updatePetWithHttpInfo($body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -793,6 +806,13 @@ public function updatePetWithHttpInfo($body) ['application/json', 'application/xml'] ); } + /** + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -904,13 +924,6 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -922,6 +935,13 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n ['application/x-www-form-urlencoded'] ); } + /** + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -1035,13 +1055,6 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -1053,6 +1066,13 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi ['multipart/form-data'] ); } + /** + // this endpoint requires OAuth (access token) + if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { + $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + } + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index afe282b8d8b..c0f2e4f7300 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -34,6 +34,7 @@ use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; +use Swagger\Client\AuthConfig; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -57,16 +58,35 @@ class StoreApi */ protected $serializer; + /** + * @var AuthConfig + */ + protected $authConfig; + /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer + * @param AuthConfig $authConfig */ - public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) - { + public function __construct( + HttpClient $client, + AuthConfig $authConfig = null, + HeaderSelector $selector = null, + ObjectSerializer $serializer = null + ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); + $this->authConfig = $authConfig ?: new AuthConfig(); + } + + /** + * @return AuthConfig + */ + public function getAuthConfig() + { + return $this->authConfig; } /** @@ -141,9 +161,6 @@ public function deleteOrderWithHttpInfo($order_id) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -155,6 +172,7 @@ public function deleteOrderWithHttpInfo($order_id) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -245,14 +263,6 @@ public function getInventoryWithHttpInfo() $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** - // this endpoint requires API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -264,6 +274,14 @@ public function getInventoryWithHttpInfo() [] ); } + // this endpoint requires API key authentication + $apiKey = $this->authConfig->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + /** + */ + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -390,9 +408,6 @@ public function getOrderByIdWithHttpInfo($order_id) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -404,6 +419,7 @@ public function getOrderByIdWithHttpInfo($order_id) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -517,9 +533,6 @@ public function placeOrderWithHttpInfo($body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -531,6 +544,7 @@ public function placeOrderWithHttpInfo($body) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 7e1e39b57ce..11996e6af73 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -34,6 +34,7 @@ use Http\Client\Exception; use Http\Client\HttpClient; use Swagger\Client\ApiException; +use Swagger\Client\AuthConfig; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -57,16 +58,35 @@ class UserApi */ protected $serializer; + /** + * @var AuthConfig + */ + protected $authConfig; + /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer + * @param AuthConfig $authConfig */ - public function __construct(HttpClient $client, HeaderSelector $selector = null, ObjectSerializer $serializer = null) - { + public function __construct( + HttpClient $client, + AuthConfig $authConfig = null, + HeaderSelector $selector = null, + ObjectSerializer $serializer = null + ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); + $this->authConfig = $authConfig ?: new AuthConfig(); + } + + /** + * @return AuthConfig + */ + public function getAuthConfig() + { + return $this->authConfig; } /** @@ -135,9 +155,6 @@ public function createUserWithHttpInfo($body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -149,6 +166,7 @@ public function createUserWithHttpInfo($body) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -249,9 +267,6 @@ public function createUsersWithArrayInputWithHttpInfo($body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -263,6 +278,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -363,9 +379,6 @@ public function createUsersWithListInputWithHttpInfo($body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -377,6 +390,7 @@ public function createUsersWithListInputWithHttpInfo($body) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -476,9 +490,6 @@ public function deleteUserWithHttpInfo($username) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -490,6 +501,7 @@ public function deleteUserWithHttpInfo($username) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -590,9 +602,6 @@ public function getUserByNameWithHttpInfo($username) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -604,6 +613,7 @@ public function getUserByNameWithHttpInfo($username) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -726,9 +736,6 @@ public function loginUserWithHttpInfo($username, $password) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -740,6 +747,7 @@ public function loginUserWithHttpInfo($username, $password) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -841,9 +849,6 @@ public function logoutUserWithHttpInfo() $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -855,6 +860,7 @@ public function logoutUserWithHttpInfo() [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( @@ -965,9 +971,6 @@ public function updateUserWithHttpInfo($username, $body) $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) } } -/** -*/ - $query = \GuzzleHttp\Psr7\build_query($queryParams); if ($httpBody instanceof MultipartStream) { $headers = $this->headerSelector->selectHeadersForMultipart( @@ -979,6 +982,7 @@ public function updateUserWithHttpInfo($username, $body) [] ); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php new file mode 100644 index 00000000000..b8add9f133c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -0,0 +1,367 @@ +config = $config; + $this->serializer = new ObjectSerializer(); + } + + /** + * Get the config + * + * @return Configuration + */ + public function getConfig() + { + return $this->config; + } + + /** + * Get the serializer + * + * @return ObjectSerializer + */ + public function getSerializer() + { + return $this->serializer; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->config->getApiKey($apiKeyIdentifier); + + if (!isset($apiKey)) { + return null; + } + + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; + } else { + $keyWithPrefix = $apiKey; + } + + return $keyWithPrefix; + } + + /** + * Make the HTTP call (Sync) + * + * @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 + * @param string $responseType expected response type of the endpoint + * @param string $endpointPath path to method endpoint before expanding parameters + * + * @throws \Swagger\Client\ApiException on a non 2xx response + * @return mixed + */ + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) + { + $headers = []; + + // construct the http header + $headerParams = array_merge( + (array)$this->config->getDefaultHeaders(), + (array)$headerParams + ); + + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + } + + // form data + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { + $postData = http_build_query($postData); + } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model + $postData = json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($postData)); + } + + $url = $this->config->getHost() . $resourcePath; + + $curl = curl_init(); + // set timeout, if needed + if ($this->config->getCurlTimeout() !== 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); + } + // set connect timeout, if needed + if ($this->config->getCurlConnectTimeout() != 0) { + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); + } + + // return the result on success, rather than just true + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + + // disable SSL verification, if needed + if ($this->config->getSSLVerification() === false) { + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); + } + + if ($this->config->getCurlProxyHost()) { + curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); + } + + if ($this->config->getCurlProxyPort()) { + curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); + } + + if ($this->config->getCurlProxyType()) { + curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); + } + + if ($this->config->getCurlProxyUser()) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); + } + + 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); + } elseif ($method === self::$HEAD) { + curl_setopt($curl, CURLOPT_NOBODY, true); + } elseif ($method === self::$OPTIONS) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } elseif ($method === self::$PATCH) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } elseif ($method === self::$PUT) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } elseif ($method === self::$DELETE) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } elseif ($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->config->getUserAgent()); + + // debugging for curl + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); + + curl_setopt($curl, CURLOPT_VERBOSE, 1); + curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), '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 = $this->httpParseHeaders(substr($response, 0, $http_header_size)); + $http_body = substr($response, $http_header_size); + $response_info = curl_getinfo($curl); + + // debug HTTP response body + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); + } + + // Handle the response + if ($response_info['http_code'] === 0) { + $curl_error_message = curl_error($curl); + + // curl_exec can sometimes fail but still return a blank message from curl_error(). + if (!empty($curl_error_message)) { + $error_message = "API call to $url failed: $curl_error_message"; + } else { + $error_message = "API call to $url failed, but for an unknown reason. " . + "This could happen if you are disconnected from the network."; + } + + $exception = new ApiException($error_message, 0, null, null); + $exception->setResponseObject($response_info); + throw $exception; + } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { + // return raw body if response is a file + if ($responseType === '\SplFileObject' || $responseType === 'string') { + return [$http_body, $response_info['http_code'], $http_header]; + } + + $data = json_decode($http_body); + if (json_last_error() > 0) { // if response is a string + $data = $http_body; + } + } else { + $data = json_decode($http_body); + if (json_last_error() > 0) { // if response is a string + $data = $http_body; + } + + throw new ApiException( + "[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], + $http_header, + $data + ); + } + return [$data, $response_info['http_code'], $http_header]; + } + + /** + * Return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * + * @return string Accept (e.g. application/json) + */ + public 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 string[] $content_type Array fo content-type + * + * @return string Content-Type (e.g. application/json) + */ + public 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); + } + } + + /** + * Return an array of HTTP response headers + * + * @param string $raw_headers A string of raw HTTP response headers + * + * @return string[] Array of HTTP response heaers + */ + protected function httpParseHeaders($raw_headers) + { + // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 + $headers = []; + $key = ''; + + foreach (explode("\n", $raw_headers) as $h) { + $h = explode(':', $h, 2); + + if (isset($h[1])) { + if (!isset($headers[$h[0]])) { + $headers[$h[0]] = trim($h[1]); + } elseif (is_array($headers[$h[0]])) { + $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); + } else { + $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); + } + + $key = $h[0]; + } else { + if (substr($h[0], 0, 1) === "\t") { + $headers[$key] .= "\r\n\t".trim($h[0]); + } elseif (!$key) { + $headers[0] = trim($h[0]); + } + trim($h[0]); + } + } + + return $headers; + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/AuthConfig.php b/samples/client/petstore/php/SwaggerClient-php/lib/AuthConfig.php new file mode 100644 index 00000000000..94a18982872 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/AuthConfig.php @@ -0,0 +1,222 @@ +apiKeys[$apiKeyIdentifier] = $key; + return $this; + } + + /** + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return $this + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string + */ + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; + } + + /** + * Sets the access token for OAuth + * + * @param string $accessToken Token for OAuth + * + * @return $this + */ + public function setAccessToken($accessToken) + { + $this->accessToken = $accessToken; + return $this; + } + + /** + * Gets the access token for OAuth + * + * @return string Access token for OAuth + */ + public function getAccessToken() + { + return $this->accessToken; + } + + /** + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * + * @return $this + */ + public function setUsername($username) + { + $this->username = $username; + return $this; + } + + /** + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication + */ + public function getUsername() + { + return $this->username; + } + + /** + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * + * @return $this + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication + */ + public function getPassword() + { + return $this->password; + } + + /** + * Get API key (with prefix if set) + * + * @param string $apiKeyIdentifier name of apikey + * + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) + { + $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->getApiKey($apiKeyIdentifier); + + if ($apiKey === null) { + return null; + } + + if ($prefix === null) { + $keyWithPrefix = $apiKey; + } else { + $keyWithPrefix = $prefix . ' ' . $apiKey; + } + + return $keyWithPrefix; + } +} + diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php b/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php new file mode 100644 index 00000000000..533030cf4b7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php @@ -0,0 +1,38 @@ +request = $request; + return new Response(200); + } + + /** + * @return null|RequestInterface + */ + public function getLastRequest() + { + return $this->request; + } +} \ No newline at end of file diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 53e909edacd..0ce7c81b583 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -7,6 +7,8 @@ use Swagger\Client\Model\ApiResponse; use Swagger\Client\Model\Pet; +require_once __DIR__ . '/FakeHttpClient.php'; + class PetApiTest extends \PHPUnit_Framework_TestCase { @@ -390,4 +392,20 @@ public function testDefaultValues() $this->assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } + + // test addPet and verify by the "id" and "name" of the response + public function testCustomApiKeyHeader() + { + $authConfig = new AuthConfig(); + $authConfig->setApiKey('api_key', '123qwe'); + + $fakeHttpClient = new FakeHttpClient(); + $api = new PetApi($fakeHttpClient, $authConfig); + $api->getPetById(123); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('api_key', $headers); + $this->assertEquals(['123qwe'], $headers['api_key']); + } } From caa7f8bb4422d50b6ab10f9acb60cb3f68e009df Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Tue, 21 Mar 2017 13:31:22 +0000 Subject: [PATCH 20/37] readded support for oauth tokens --- .../src/main/resources/php/api.mustache | 6 +-- .../php/SwaggerClient-php/lib/Api/PetApi.php | 42 +++++++++---------- .../SwaggerClient-php/tests/PetApiTest.php | 15 +++++++ 3 files changed, 39 insertions(+), 24 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 489de599eed..608579ceb77 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -277,13 +277,13 @@ use {{invokerPackage}}\ObjectSerializer; $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); } {{/isBasic}} + */ {{#isOAuth}} // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } {{/isOAuth}} - */ {{/authMethods}} $query = \GuzzleHttp\Psr7\build_query($queryParams); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 61bc149536c..8fc15671cdc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -167,11 +167,11 @@ public function addPetWithHttpInfo($body) ); } /** + */ // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { @@ -292,11 +292,11 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) ); } /** + */ // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { @@ -413,11 +413,11 @@ public function findPetsByStatusWithHttpInfo($status) ); } /** + */ // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { @@ -546,11 +546,11 @@ public function findPetsByTagsWithHttpInfo($tags) ); } /** + */ // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { @@ -807,11 +807,11 @@ public function updatePetWithHttpInfo($body) ); } /** + */ // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { @@ -936,11 +936,11 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n ); } /** + */ // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { @@ -1067,11 +1067,11 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi ); } /** + */ // this endpoint requires OAuth (access token) - if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->authConfig->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 0ce7c81b583..a59f7c2dd75 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -408,4 +408,19 @@ public function testCustomApiKeyHeader() $this->assertArrayHasKey('api_key', $headers); $this->assertEquals(['123qwe'], $headers['api_key']); } + + public function testApiToken() + { + $authConfig = new AuthConfig(); + $authConfig->setAccessToken('asd123'); + + $fakeHttpClient = new FakeHttpClient(); + $api = new PetApi($fakeHttpClient, $authConfig); + $api->addPet(new Pet()); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('Authorization', $headers); + $this->assertEquals(['Bearer asd123'], $headers['Authorization']); + } } From 696df631e907a86ec58c2690d2567ebb17763005 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Tue, 21 Mar 2017 13:46:46 +0000 Subject: [PATCH 21/37] readded basic auth; moved auth tests to separate test class --- .../src/main/resources/php/api.mustache | 8 +-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 10 ++- .../php/SwaggerClient-php/lib/Api/PetApi.php | 16 ----- .../SwaggerClient-php/lib/Api/StoreApi.php | 2 - .../php/SwaggerClient-php/tests/AuthTest.php | 62 +++++++++++++++++++ .../SwaggerClient-php/tests/PetApiTest.php | 34 +--------- 6 files changed, 70 insertions(+), 62 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 608579ceb77..55fa97d7b33 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -149,7 +149,7 @@ use {{invokerPackage}}\ObjectSerializer; } {{/minimum}} {{#pattern}} - if ({{^required}}${{paramName}} !== null && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}}) { + if ({{^required}}${{paramName}} !== null && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) { throw new \InvalidArgumentException("invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); } {{/pattern}} @@ -270,14 +270,12 @@ use {{invokerPackage}}\ObjectSerializer; {{#isKeyInHeader}}$headers['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} } {{/isApiKey}} - /** {{#isBasic}} // this endpoint requires HTTP basic authentication - if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { - $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); + if ($this->authConfig->getUsername() !== null || $this->authConfig->getPassword() !== null) { + $headers['Authorization'] = 'Basic ' . base64_encode($this->authConfig->getUsername() . ":" . $this->authConfig->getPassword()); } {{/isBasic}} - */ {{#isOAuth}} // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 0c24cceb470..2ce83ed4524 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -293,7 +293,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if ($pattern_without_delimiter === null) { throw new \InvalidArgumentException('Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters'); } - if (!preg_match("/^[A-Z].*_/", $pattern_without_delimiter) { + if (!preg_match("/^[A-Z].*_/", $pattern_without_delimiter)) { throw new \InvalidArgumentException("invalid value for \"pattern_without_delimiter\" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*_/."); } @@ -319,7 +319,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi throw new \InvalidArgumentException('invalid value for "$float" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 987.6.'); } - if ($string !== null && !preg_match("/[a-z]/i", $string) { + if ($string !== null && !preg_match("/[a-z]/i", $string)) { throw new \InvalidArgumentException("invalid value for \"string\" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i."); } @@ -427,12 +427,10 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] ); } - /** // this endpoint requires HTTP basic authentication - if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { - $headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); + if ($this->authConfig->getUsername() !== null || $this->authConfig->getPassword() !== null) { + $headers['Authorization'] = 'Basic ' . base64_encode($this->authConfig->getUsername() . ":" . $this->authConfig->getPassword()); } - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 8fc15671cdc..59a4210f6b6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -166,8 +166,6 @@ public function addPetWithHttpInfo($body) ['application/json', 'application/xml'] ); } - /** - */ // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); @@ -291,8 +289,6 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) [] ); } - /** - */ // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); @@ -412,8 +408,6 @@ public function findPetsByStatusWithHttpInfo($status) [] ); } - /** - */ // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); @@ -545,8 +539,6 @@ public function findPetsByTagsWithHttpInfo($tags) [] ); } - /** - */ // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); @@ -680,8 +672,6 @@ public function getPetByIdWithHttpInfo($pet_id) if ($apiKey !== null) { $headers['api_key'] = $apiKey; } - /** - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { @@ -806,8 +796,6 @@ public function updatePetWithHttpInfo($body) ['application/json', 'application/xml'] ); } - /** - */ // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); @@ -935,8 +923,6 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n ['application/x-www-form-urlencoded'] ); } - /** - */ // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); @@ -1066,8 +1052,6 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi ['multipart/form-data'] ); } - /** - */ // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index c0f2e4f7300..597bc8a9489 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -279,8 +279,6 @@ public function getInventoryWithHttpInfo() if ($apiKey !== null) { $headers['api_key'] = $apiKey; } - /** - */ $query = \GuzzleHttp\Psr7\build_query($queryParams); try { diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php new file mode 100644 index 00000000000..d30d82feb69 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php @@ -0,0 +1,62 @@ +setApiKey('api_key', '123qwe'); + + $fakeHttpClient = new FakeHttpClient(); + $api = new PetApi($fakeHttpClient, $authConfig); + $api->getPetById(123); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('api_key', $headers); + $this->assertEquals(['123qwe'], $headers['api_key']); + } + + public function testApiToken() + { + $authConfig = new AuthConfig(); + $authConfig->setAccessToken('asd123'); + + $fakeHttpClient = new FakeHttpClient(); + $api = new PetApi($fakeHttpClient, $authConfig); + $api->addPet(new Pet()); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('Authorization', $headers); + $this->assertEquals(['Bearer asd123'], $headers['Authorization']); + } + + public function testBasicAuth() + { + $username = 'user'; + $password = 'password'; + + $authConfig = new AuthConfig(); + $authConfig->setUsername($username); + $authConfig->setPassword($password); + + $fakeHttpClient = new FakeHttpClient(); + $api = new FakeApi($fakeHttpClient, $authConfig); + $api->testEndpointParameters(123, 100.1, 'ASD_', 'ASD'); + + $headers = $fakeHttpClient->getLastRequest()->getHeaders(); + + $this->assertArrayHasKey('Authorization', $headers); + $encodedCredentials = base64_encode("$username:$password"); + $this->assertEquals(["Basic $encodedCredentials"], $headers['Authorization']); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index a59f7c2dd75..ad2ef76f330 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -3,12 +3,11 @@ namespace Swagger\Client; use Http\Adapter\Guzzle6\Client; +use Swagger\Client\Api\FakeApi; use Swagger\Client\Api\PetApi; use Swagger\Client\Model\ApiResponse; use Swagger\Client\Model\Pet; -require_once __DIR__ . '/FakeHttpClient.php'; - class PetApiTest extends \PHPUnit_Framework_TestCase { @@ -392,35 +391,4 @@ public function testDefaultValues() $this->assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } - - // test addPet and verify by the "id" and "name" of the response - public function testCustomApiKeyHeader() - { - $authConfig = new AuthConfig(); - $authConfig->setApiKey('api_key', '123qwe'); - - $fakeHttpClient = new FakeHttpClient(); - $api = new PetApi($fakeHttpClient, $authConfig); - $api->getPetById(123); - - $headers = $fakeHttpClient->getLastRequest()->getHeaders(); - - $this->assertArrayHasKey('api_key', $headers); - $this->assertEquals(['123qwe'], $headers['api_key']); - } - - public function testApiToken() - { - $authConfig = new AuthConfig(); - $authConfig->setAccessToken('asd123'); - - $fakeHttpClient = new FakeHttpClient(); - $api = new PetApi($fakeHttpClient, $authConfig); - $api->addPet(new Pet()); - - $headers = $fakeHttpClient->getLastRequest()->getHeaders(); - - $this->assertArrayHasKey('Authorization', $headers); - $this->assertEquals(['Bearer asd123'], $headers['Authorization']); - } } From e7b8448082bf0ca66ac039a44a4d3cf00b0d4356 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Tue, 21 Mar 2017 14:19:11 +0000 Subject: [PATCH 22/37] readded header params --- .../src/main/resources/php/api.mustache | 12 +++-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 6 ++- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 28 ++++++---- .../php/SwaggerClient-php/lib/Api/PetApi.php | 52 +++++++++++++++---- .../SwaggerClient-php/lib/Api/StoreApi.php | 24 +++++++-- .../php/SwaggerClient-php/lib/Api/UserApi.php | 48 ++++++++++++++--- .../SwaggerClient-php/tests/FakeApiTest.php | 44 ++++++++++++++++ 7 files changed, 175 insertions(+), 39 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/FakeApiTest.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 55fa97d7b33..9858791953a 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -170,6 +170,7 @@ use {{invokerPackage}}\ObjectSerializer; $resourcePath = substr('{{{path}}}', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '{{returnType}}'; @@ -186,17 +187,15 @@ use {{invokerPackage}}\ObjectSerializer; } {{/queryParams}} {{#headerParams}} -/** // header params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}'); + ${{paramName}} = $this->serializer->serializeCollection(${{paramName}}, '{{collectionFormat}}'); } {{/collectionFormat}} if (${{paramName}} !== null) { - $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); + $headerParams['{{baseName}}'] = $this->serializer->toHeaderValue(${{paramName}}); } -*/ {{/headerParams}} {{#pathParams}} @@ -253,7 +252,7 @@ use {{invokerPackage}}\ObjectSerializer; } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] ); } else { @@ -262,6 +261,7 @@ use {{invokerPackage}}\ObjectSerializer; [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] ); } + {{#authMethods}} {{#isApiKey}} // this endpoint requires API key authentication @@ -283,7 +283,9 @@ use {{invokerPackage}}\ObjectSerializer; } {{/isOAuth}} {{/authMethods}} + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index bc81a545148..fee46903994 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -120,6 +120,7 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn $resourcePath = substr('/fake', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -152,7 +153,7 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/json', '*_/ \" =end --'] ); } else { @@ -161,7 +162,10 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn ['application/json', '*_/ \" =end --'] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 2ce83ed4524..df81482dcca 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -125,6 +125,7 @@ public function testClientModelWithHttpInfo($body) $resourcePath = substr('/fake', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\Client'; @@ -158,7 +159,7 @@ public function testClientModelWithHttpInfo($body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/json'] ); } else { @@ -167,7 +168,10 @@ public function testClientModelWithHttpInfo($body) ['application/json'] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -334,6 +338,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $resourcePath = substr('/fake', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -418,7 +423,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] ); } else { @@ -427,11 +432,14 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] ); } + // this endpoint requires HTTP basic authentication if ($this->authConfig->getUsername() !== null || $this->authConfig->getPassword() !== null) { $headers['Authorization'] = 'Basic ' . base64_encode($this->authConfig->getUsername() . ":" . $this->authConfig->getPassword()); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -511,6 +519,7 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $resourcePath = substr('/fake', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -530,21 +539,17 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ if ($enum_query_integer !== null) { $queryParams['enum_query_integer'] = $this->serializer->toQueryValue($enum_query_integer); } -/** // header params if (is_array($enum_header_string_array)) { - $enum_header_string_array = $this->apiClient->getSerializer()->serializeCollection($enum_header_string_array, 'csv'); + $enum_header_string_array = $this->serializer->serializeCollection($enum_header_string_array, 'csv'); } if ($enum_header_string_array !== null) { - $headerParams['enum_header_string_array'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string_array); + $headerParams['enum_header_string_array'] = $this->serializer->toHeaderValue($enum_header_string_array); } -*/ -/** // header params if ($enum_header_string !== null) { - $headerParams['enum_header_string'] = $this->apiClient->getSerializer()->toHeaderValue($enum_header_string); + $headerParams['enum_header_string'] = $this->serializer->toHeaderValue($enum_header_string); } -*/ // form params @@ -581,7 +586,7 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['*/*'] ); } else { @@ -590,7 +595,10 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ ['*/*'] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 59a4210f6b6..044194d33a3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -124,6 +124,7 @@ public function addPetWithHttpInfo($body) $resourcePath = substr('/pet', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -157,7 +158,7 @@ public function addPetWithHttpInfo($body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -166,11 +167,14 @@ public function addPetWithHttpInfo($body) ['application/json', 'application/xml'] ); } + // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -242,16 +246,15 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $resourcePath = substr('/pet/{petId}', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; -/** // header params if ($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); + $headerParams['api_key'] = $this->serializer->toHeaderValue($api_key); } -*/ // path params if ($pet_id !== null) { @@ -280,7 +283,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -289,11 +292,14 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) [] ); } + // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -364,6 +370,7 @@ public function findPetsByStatusWithHttpInfo($status) $resourcePath = substr('/pet/findByStatus', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\Pet[]'; @@ -399,7 +406,7 @@ public function findPetsByStatusWithHttpInfo($status) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -408,11 +415,14 @@ public function findPetsByStatusWithHttpInfo($status) [] ); } + // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -495,6 +505,7 @@ public function findPetsByTagsWithHttpInfo($tags) $resourcePath = substr('/pet/findByTags', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\Pet[]'; @@ -530,7 +541,7 @@ public function findPetsByTagsWithHttpInfo($tags) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -539,11 +550,14 @@ public function findPetsByTagsWithHttpInfo($tags) [] ); } + // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -626,6 +640,7 @@ public function getPetByIdWithHttpInfo($pet_id) $resourcePath = substr('/pet/{petId}', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\Pet'; @@ -658,7 +673,7 @@ public function getPetByIdWithHttpInfo($pet_id) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -667,12 +682,15 @@ public function getPetByIdWithHttpInfo($pet_id) [] ); } + // this endpoint requires API key authentication $apiKey = $this->authConfig->getApiKeyWithPrefix('api_key'); if ($apiKey !== null) { $headers['api_key'] = $apiKey; } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -754,6 +772,7 @@ public function updatePetWithHttpInfo($body) $resourcePath = substr('/pet', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -787,7 +806,7 @@ public function updatePetWithHttpInfo($body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -796,11 +815,14 @@ public function updatePetWithHttpInfo($body) ['application/json', 'application/xml'] ); } + // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -874,6 +896,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $resourcePath = substr('/pet/{petId}', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -914,7 +937,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -923,11 +946,14 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n ['application/x-www-form-urlencoded'] ); } + // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -1002,6 +1028,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $resourcePath = substr('/pet/{petId}/uploadImage', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\ApiResponse'; @@ -1043,7 +1070,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/json'] ); } else { @@ -1052,11 +1079,14 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi ['multipart/form-data'] ); } + // this endpoint requires OAuth (access token) if ($this->authConfig->getAccessToken() !== null) { $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 597bc8a9489..33b41e5076a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -127,6 +127,7 @@ public function deleteOrderWithHttpInfo($order_id) $headerParams = []; $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -163,7 +164,7 @@ public function deleteOrderWithHttpInfo($order_id) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -172,7 +173,10 @@ public function deleteOrderWithHttpInfo($order_id) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -237,6 +241,7 @@ public function getInventoryWithHttpInfo() $resourcePath = substr('/store/inventory', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = 'map[string,int]'; @@ -265,7 +270,7 @@ public function getInventoryWithHttpInfo() } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/json'] ); } else { @@ -274,12 +279,15 @@ public function getInventoryWithHttpInfo() [] ); } + // this endpoint requires API key authentication $apiKey = $this->authConfig->getApiKeyWithPrefix('api_key'); if ($apiKey !== null) { $headers['api_key'] = $apiKey; } + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -372,6 +380,7 @@ public function getOrderByIdWithHttpInfo($order_id) $headerParams = []; $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\Order'; @@ -408,7 +417,7 @@ public function getOrderByIdWithHttpInfo($order_id) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -417,7 +426,10 @@ public function getOrderByIdWithHttpInfo($order_id) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -500,6 +512,7 @@ public function placeOrderWithHttpInfo($body) $resourcePath = substr('/store/order', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\Order'; @@ -533,7 +546,7 @@ public function placeOrderWithHttpInfo($body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -542,7 +555,10 @@ public function placeOrderWithHttpInfo($body) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 11996e6af73..68d0a815b60 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -124,6 +124,7 @@ public function createUserWithHttpInfo($body) $resourcePath = substr('/user', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -157,7 +158,7 @@ public function createUserWithHttpInfo($body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -166,7 +167,10 @@ public function createUserWithHttpInfo($body) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -236,6 +240,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) $resourcePath = substr('/user/createWithArray', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -269,7 +274,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -278,7 +283,10 @@ public function createUsersWithArrayInputWithHttpInfo($body) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -348,6 +356,7 @@ public function createUsersWithListInputWithHttpInfo($body) $resourcePath = substr('/user/createWithList', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -381,7 +390,7 @@ public function createUsersWithListInputWithHttpInfo($body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -390,7 +399,10 @@ public function createUsersWithListInputWithHttpInfo($body) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -460,6 +472,7 @@ public function deleteUserWithHttpInfo($username) $resourcePath = substr('/user/{username}', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -492,7 +505,7 @@ public function deleteUserWithHttpInfo($username) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -501,7 +514,10 @@ public function deleteUserWithHttpInfo($username) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -572,6 +588,7 @@ public function getUserByNameWithHttpInfo($username) $resourcePath = substr('/user/{username}', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = '\Swagger\Client\Model\User'; @@ -604,7 +621,7 @@ public function getUserByNameWithHttpInfo($username) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -613,7 +630,10 @@ public function getUserByNameWithHttpInfo($username) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -702,6 +722,7 @@ public function loginUserWithHttpInfo($username, $password) $resourcePath = substr('/user/login', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = 'string'; @@ -738,7 +759,7 @@ public function loginUserWithHttpInfo($username, $password) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -747,7 +768,10 @@ public function loginUserWithHttpInfo($username, $password) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -823,6 +847,7 @@ public function logoutUserWithHttpInfo() $resourcePath = substr('/user/logout', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -851,7 +876,7 @@ public function logoutUserWithHttpInfo() } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -860,7 +885,10 @@ public function logoutUserWithHttpInfo() [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( @@ -936,6 +964,7 @@ public function updateUserWithHttpInfo($username, $body) $resourcePath = substr('/user/{username}', 1); $formParams = []; $queryParams = []; + $headerParams = []; $httpBody = ''; $multipart = false; $returnType = ''; @@ -973,7 +1002,7 @@ public function updateUserWithHttpInfo($username, $body) } if ($httpBody instanceof MultipartStream) { - $headers = $this->headerSelector->selectHeadersForMultipart( + $headers= $this->headerSelector->selectHeadersForMultipart( ['application/xml', 'application/json'] ); } else { @@ -982,7 +1011,10 @@ public function updateUserWithHttpInfo($username, $body) [] ); } + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $headers = array_merge($headerParams, $headers); try { $request = new Request( diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/FakeApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/FakeApiTest.php new file mode 100644 index 00000000000..bf1cac7f9f3 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/FakeApiTest.php @@ -0,0 +1,44 @@ +fakeHttpClient = new FakeHttpClient(); + $this->api = new Api\FakeApi($this->fakeHttpClient); + } + + public function testHeaderParam() + { + $this->api->testEnumParameters([], [], [], 'something'); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('enum_header_string', $headers); + $this->assertEquals(['something'], $headers['enum_header_string']); + } + + public function testHeaderParamCollection() + { + $this->api->testEnumParameters([], [], ['string1', 'string2']); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('enum_header_string_array', $headers); + $this->assertEquals(['string1,string2'], $headers['enum_header_string_array']); + } +} From dbad22ca383f467ba2072f1eeeeae53e593488b6 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Tue, 21 Mar 2017 14:35:43 +0000 Subject: [PATCH 23/37] readded support for collections in paths --- .../src/main/resources/php/api.mustache | 4 +--- .../{FakeApiTest.php => ParametersTest.php} | 23 ++++++++++++++----- 2 files changed, 18 insertions(+), 9 deletions(-) rename samples/client/petstore/php/SwaggerClient-php/tests/{FakeApiTest.php => ParametersTest.php} (54%) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 9858791953a..3cd5bd2ff41 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -201,11 +201,9 @@ use {{invokerPackage}}\ObjectSerializer; {{#pathParams}} // path params {{#collectionFormat}} - /** if (is_array(${{paramName}})) { - ${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}'); + ${{paramName}} = $this->serializer->serializeCollection(${{paramName}}, '{{collectionFormat}}'); } - */ {{/collectionFormat}} if (${{paramName}} !== null) { $resourcePath = str_replace('{' . '{{baseName}}' . '}', $this->serializer->toPathValue(${{paramName}}), $resourcePath); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/FakeApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php similarity index 54% rename from samples/client/petstore/php/SwaggerClient-php/tests/FakeApiTest.php rename to samples/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php index bf1cac7f9f3..25e18742ed3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/FakeApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php @@ -3,26 +3,29 @@ namespace Swagger\Client; use Swagger\Client\Api\FakeApi; +use Swagger\Client\Api\UserApi; require_once __DIR__ . '/FakeHttpClient.php'; -class FakeApiTest extends \PHPUnit_Framework_TestCase +class ParametersTest extends \PHPUnit_Framework_TestCase { - /** @var FakeHttpClient */ private $fakeHttpClient; /** @var FakeApi */ - private $api; + private $fakeApi; + /** @var UserApi */ + private $userApi; public function setUp() { $this->fakeHttpClient = new FakeHttpClient(); - $this->api = new Api\FakeApi($this->fakeHttpClient); + $this->fakeApi = new Api\FakeApi($this->fakeHttpClient); + $this->userApi = new Api\UserApi($this->fakeHttpClient); } public function testHeaderParam() { - $this->api->testEnumParameters([], [], [], 'something'); + $this->fakeApi->testEnumParameters([], [], [], 'something'); $request = $this->fakeHttpClient->getLastRequest(); $headers = $request->getHeaders(); @@ -33,7 +36,7 @@ public function testHeaderParam() public function testHeaderParamCollection() { - $this->api->testEnumParameters([], [], ['string1', 'string2']); + $this->fakeApi->testEnumParameters([], [], ['string1', 'string2']); $request = $this->fakeHttpClient->getLastRequest(); $headers = $request->getHeaders(); @@ -41,4 +44,12 @@ public function testHeaderParamCollection() $this->assertArrayHasKey('enum_header_string_array', $headers); $this->assertEquals(['string1,string2'], $headers['enum_header_string_array']); } + +// missing example for collection path param in config +// public function testPathParamCollection() +// { +// $this->userApi->getUserByNameWithHttpInfo(['aa', 'bb']); +// $request = $this->fakeHttpClient->getLastRequest(); +// $this->assertEquals('user/aa,bb', urldecode($request->getUri()->getPath())); +// } } From 2b318812701c3de5ec03ff7d8c6b93adbca2cf87 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Wed, 22 Mar 2017 10:04:36 +0000 Subject: [PATCH 24/37] readded config option; readded exception handling --- .../codegen/languages/PhpClientCodegen.java | 2 +- ...Config.mustache => Configuration.mustache} | 34 +- .../src/main/resources/php/api.mustache | 81 +++-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 47 +-- .../SwaggerClient-php/lib/Configuration.php} | 42 ++- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 121 ++++--- .../php/SwaggerClient-php/lib/Api/PetApi.php | 330 ++++++++++-------- .../SwaggerClient-php/lib/Api/StoreApi.php | 200 ++++++----- .../php/SwaggerClient-php/lib/Api/UserApi.php | 268 ++++++++------ .../SwaggerClient-php/lib/Configuration.php | 2 +- .../php/SwaggerClient-php/tests/AuthTest.php | 6 +- .../SwaggerClient-php/tests/ExceptionTest.php | 39 +++ .../SwaggerClient-php/tests/PetApiTest.php | 10 +- .../SwaggerClient-php/tests/StoreApiTest.php | 4 +- .../SwaggerClient-php/tests/UserApiTest.php | 10 +- 15 files changed, 698 insertions(+), 498 deletions(-) rename modules/swagger-codegen/src/main/resources/php/{AuthConfig.mustache => Configuration.mustache} (90%) rename samples/client/{petstore/php/SwaggerClient-php/lib/AuthConfig.php => petstore-security-test/php/SwaggerClient-php/lib/Configuration.php} (85%) create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 62ea2eed56a..b834271fb9a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -302,7 +302,7 @@ public void processOpts() { additionalProperties.put("testBasePath", testBasePath); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiException.php")); - supportingFiles.add(new SupportingFile("AuthConfig.mustache", toPackagePath(invokerPackage, srcBasePath), "AuthConfig.php")); + supportingFiles.add(new SupportingFile("Configuration.mustache", toPackagePath(invokerPackage, srcBasePath), "Configuration.php")); supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); supportingFiles.add(new SupportingFile("HeaderSelector.mustache", toPackagePath(invokerPackage, srcBasePath), "HeaderSelector.php")); supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); diff --git a/modules/swagger-codegen/src/main/resources/php/AuthConfig.mustache b/modules/swagger-codegen/src/main/resources/php/Configuration.mustache similarity index 90% rename from modules/swagger-codegen/src/main/resources/php/AuthConfig.mustache rename to modules/swagger-codegen/src/main/resources/php/Configuration.mustache index 5ca5113d6a2..d6fa2cd2ab4 100644 --- a/modules/swagger-codegen/src/main/resources/php/AuthConfig.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Configuration.mustache @@ -1,6 +1,6 @@ host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + /** * Sets API key * diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 3cd5bd2ff41..a9fded3afb1 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -21,10 +21,10 @@ namespace {{apiPackage}}; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; -use Http\Client\Exception; +use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use {{invokerPackage}}\ApiException; -use {{invokerPackage}}\AuthConfig; +use {{invokerPackage}}\Configuration; use {{invokerPackage}}\HeaderSelector; use {{invokerPackage}}\ObjectSerializer; @@ -49,34 +49,34 @@ use {{invokerPackage}}\ObjectSerializer; protected $serializer; /** - * @var AuthConfig + * @var Configuration */ - protected $authConfig; + protected $config; /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer - * @param AuthConfig $authConfig + * @param Configuration $config */ public function __construct( HttpClient $client, - AuthConfig $authConfig = null, + Configuration $config = null, HeaderSelector $selector = null, ObjectSerializer $serializer = null ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); - $this->authConfig = $authConfig ?: new AuthConfig(); + $this->config = $config ?: new Configuration(); } /** - * @return AuthConfig + * @return Config */ - public function getAuthConfig() + public function getConfig() { - return $this->authConfig; + return $this->config; } {{#operation}} @@ -167,7 +167,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/hasValidation}} {{/allParams}} - $resourcePath = substr('{{{path}}}', 1); + $resourcePath = '{{{path}}}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -263,53 +263,58 @@ use {{invokerPackage}}\ObjectSerializer; {{#authMethods}} {{#isApiKey}} // this endpoint requires API key authentication - $apiKey = $this->authConfig->getApiKeyWithPrefix('{{keyParamName}}'); + $apiKey = $this->config->getApiKeyWithPrefix('{{keyParamName}}'); if ($apiKey !== null) { {{#isKeyInHeader}}$headers['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} } {{/isApiKey}} {{#isBasic}} // this endpoint requires HTTP basic authentication - if ($this->authConfig->getUsername() !== null || $this->authConfig->getPassword() !== null) { - $headers['Authorization'] = 'Basic ' . base64_encode($this->authConfig->getUsername() . ":" . $this->authConfig->getPassword()); + if ($this->config->getUsername() !== null || $this->config->getPassword() !== null) { + $headers['Authorization'] = 'Basic ' . base64_encode($this->config->getUsername() . ":" . $this->config->getPassword()); } {{/isBasic}} {{#isOAuth}} // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } {{/isOAuth}} {{/authMethods}} $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $request = new Request( + '{{httpMethod}}', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - '{{httpMethod}}', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - {{#returnType}} - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '{{returnType}}', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - {{/returnType}} - {{^returnType}} - return [null, $response->getStatusCode(), $response->getHeaders()]; - {{/returnType}} - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + {{#returnType}} + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); } + return [ + ObjectSerializer::deserialize($content, '{{returnType}}', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + {{/returnType}} + {{^returnType}} + return [null, $response->getStatusCode(), $response->getHeaders()]; + {{/returnType}} /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index fee46903994..081f1844ddf 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -31,10 +31,10 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; -use Http\Client\Exception; +use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; -use Swagger\Client\AuthConfig; +use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -59,34 +59,34 @@ class FakeApi protected $serializer; /** - * @var AuthConfig + * @var Configuration */ - protected $authConfig; + protected $config; /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer - * @param AuthConfig $authConfig + * @param Configuration $config */ public function __construct( HttpClient $client, - AuthConfig $authConfig = null, + Configuration $config = null, HeaderSelector $selector = null, ObjectSerializer $serializer = null ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); - $this->authConfig = $authConfig ?: new AuthConfig(); + $this->config = $config ?: new Configuration(); } /** - * @return AuthConfig + * @return Config */ - public function getAuthConfig() + public function getConfig() { - return $this->authConfig; + return $this->config; } /** @@ -117,7 +117,7 @@ public function testCodeInjectEndRnNR($test_code_inject____end____rn_n_r = null) public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r = null) { - $resourcePath = substr('/fake', 1); + $resourcePath = '/fake'; $formParams = []; $queryParams = []; $headerParams = []; @@ -166,19 +166,24 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'PUT', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'PUT', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/AuthConfig.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php similarity index 85% rename from samples/client/petstore/php/SwaggerClient-php/lib/AuthConfig.php rename to samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index 94a18982872..1578eb976f7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/AuthConfig.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -1,6 +1,6 @@ host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + /** * Sets API key * diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index df81482dcca..bf524295849 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -31,10 +31,10 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; -use Http\Client\Exception; +use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; -use Swagger\Client\AuthConfig; +use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -59,34 +59,34 @@ class FakeApi protected $serializer; /** - * @var AuthConfig + * @var Configuration */ - protected $authConfig; + protected $config; /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer - * @param AuthConfig $authConfig + * @param Configuration $config */ public function __construct( HttpClient $client, - AuthConfig $authConfig = null, + Configuration $config = null, HeaderSelector $selector = null, ObjectSerializer $serializer = null ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); - $this->authConfig = $authConfig ?: new AuthConfig(); + $this->config = $config ?: new Configuration(); } /** - * @return AuthConfig + * @return Config */ - public function getAuthConfig() + public function getConfig() { - return $this->authConfig; + return $this->config; } /** @@ -122,7 +122,7 @@ public function testClientModelWithHttpInfo($body) throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); } - $resourcePath = substr('/fake', 1); + $resourcePath = '/fake'; $formParams = []; $queryParams = []; $headerParams = []; @@ -172,27 +172,32 @@ public function testClientModelWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'PATCH', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'PATCH', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Client', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Client', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -335,7 +340,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi } - $resourcePath = substr('/fake', 1); + $resourcePath = '/fake'; $formParams = []; $queryParams = []; $headerParams = []; @@ -434,25 +439,30 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi } // this endpoint requires HTTP basic authentication - if ($this->authConfig->getUsername() !== null || $this->authConfig->getPassword() !== null) { - $headers['Authorization'] = 'Basic ' . base64_encode($this->authConfig->getUsername() . ":" . $this->authConfig->getPassword()); + if ($this->config->getUsername() !== null || $this->config->getPassword() !== null) { + $headers['Authorization'] = 'Basic ' . base64_encode($this->config->getUsername() . ":" . $this->config->getPassword()); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -516,7 +526,7 @@ public function testEnumParameters($enum_form_string_array = null, $enum_form_st public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null) { - $resourcePath = substr('/fake', 1); + $resourcePath = '/fake'; $formParams = []; $queryParams = []; $headerParams = []; @@ -599,19 +609,24 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 044194d33a3..3bc71517e1c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -31,10 +31,10 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; -use Http\Client\Exception; +use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; -use Swagger\Client\AuthConfig; +use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -59,34 +59,34 @@ class PetApi protected $serializer; /** - * @var AuthConfig + * @var Configuration */ - protected $authConfig; + protected $config; /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer - * @param AuthConfig $authConfig + * @param Configuration $config */ public function __construct( HttpClient $client, - AuthConfig $authConfig = null, + Configuration $config = null, HeaderSelector $selector = null, ObjectSerializer $serializer = null ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); - $this->authConfig = $authConfig ?: new AuthConfig(); + $this->config = $config ?: new Configuration(); } /** - * @return AuthConfig + * @return Config */ - public function getAuthConfig() + public function getConfig() { - return $this->authConfig; + return $this->config; } /** @@ -121,7 +121,7 @@ public function addPetWithHttpInfo($body) throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); } - $resourcePath = substr('/pet', 1); + $resourcePath = '/pet'; $formParams = []; $queryParams = []; $headerParams = []; @@ -169,25 +169,30 @@ public function addPetWithHttpInfo($body) } // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -243,7 +248,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - $resourcePath = substr('/pet/{petId}', 1); + $resourcePath = '/pet/{petId}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -294,25 +299,30 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) } // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'DELETE', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'DELETE', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -367,7 +377,7 @@ public function findPetsByStatusWithHttpInfo($status) throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); } - $resourcePath = substr('/pet/findByStatus', 1); + $resourcePath = '/pet/findByStatus'; $formParams = []; $queryParams = []; $headerParams = []; @@ -417,33 +427,38 @@ public function findPetsByStatusWithHttpInfo($status) } // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -502,7 +517,7 @@ public function findPetsByTagsWithHttpInfo($tags) throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); } - $resourcePath = substr('/pet/findByTags', 1); + $resourcePath = '/pet/findByTags'; $formParams = []; $queryParams = []; $headerParams = []; @@ -552,33 +567,38 @@ public function findPetsByTagsWithHttpInfo($tags) } // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -637,7 +657,7 @@ public function getPetByIdWithHttpInfo($pet_id) throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - $resourcePath = substr('/pet/{petId}', 1); + $resourcePath = '/pet/{petId}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -684,34 +704,39 @@ public function getPetByIdWithHttpInfo($pet_id) } // this endpoint requires API key authentication - $apiKey = $this->authConfig->getApiKeyWithPrefix('api_key'); + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); if ($apiKey !== null) { $headers['api_key'] = $apiKey; } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -769,7 +794,7 @@ public function updatePetWithHttpInfo($body) throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); } - $resourcePath = substr('/pet', 1); + $resourcePath = '/pet'; $formParams = []; $queryParams = []; $headerParams = []; @@ -817,25 +842,30 @@ public function updatePetWithHttpInfo($body) } // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'PUT', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'PUT', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -893,7 +923,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - $resourcePath = substr('/pet/{petId}', 1); + $resourcePath = '/pet/{petId}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -948,25 +978,30 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n } // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -1025,7 +1060,7 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - $resourcePath = substr('/pet/{petId}/uploadImage', 1); + $resourcePath = '/pet/{petId}/uploadImage'; $formParams = []; $queryParams = []; $headerParams = []; @@ -1081,33 +1116,38 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } // this endpoint requires OAuth (access token) - if ($this->authConfig->getAccessToken() !== null) { - $headers['Authorization'] = 'Bearer ' . $this->authConfig->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\ApiResponse', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\ApiResponse', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 33b41e5076a..003993e0ea8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -31,10 +31,10 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; -use Http\Client\Exception; +use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; -use Swagger\Client\AuthConfig; +use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -59,34 +59,34 @@ class StoreApi protected $serializer; /** - * @var AuthConfig + * @var Configuration */ - protected $authConfig; + protected $config; /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer - * @param AuthConfig $authConfig + * @param Configuration $config */ public function __construct( HttpClient $client, - AuthConfig $authConfig = null, + Configuration $config = null, HeaderSelector $selector = null, ObjectSerializer $serializer = null ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); - $this->authConfig = $authConfig ?: new AuthConfig(); + $this->config = $config ?: new Configuration(); } /** - * @return AuthConfig + * @return Config */ - public function getAuthConfig() + public function getConfig() { - return $this->authConfig; + return $this->config; } /** @@ -120,11 +120,8 @@ public function deleteOrderWithHttpInfo($order_id) if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } - // parse inputs - $resourcePath = "/store/order/{order_id}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = '/store/order/{order_id}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -135,11 +132,7 @@ public function deleteOrderWithHttpInfo($order_id) // path params if ($order_id !== null) { - $resourcePath = str_replace( - "{" . "order_id" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'order_id' . '}', $this->serializer->toPathValue($order_id), $resourcePath); } @@ -177,19 +170,24 @@ public function deleteOrderWithHttpInfo($order_id) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'DELETE', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'DELETE', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -238,7 +236,7 @@ public function getInventory() public function getInventoryWithHttpInfo() { - $resourcePath = substr('/store/inventory', 1); + $resourcePath = '/store/inventory'; $formParams = []; $queryParams = []; $headerParams = []; @@ -281,34 +279,39 @@ public function getInventoryWithHttpInfo() } // this endpoint requires API key authentication - $apiKey = $this->authConfig->getApiKeyWithPrefix('api_key'); + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); if ($apiKey !== null) { $headers['api_key'] = $apiKey; } $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, 'map[string,int]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } + return [ + ObjectSerializer::deserialize($content, 'map[string,int]', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -373,11 +376,8 @@ public function getOrderByIdWithHttpInfo($order_id) throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.'); } - // parse inputs - $resourcePath = "/store/order/{order_id}"; - $httpBody = ''; - $queryParams = []; - $headerParams = []; + + $resourcePath = '/store/order/{order_id}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -388,11 +388,7 @@ public function getOrderByIdWithHttpInfo($order_id) // path params if ($order_id !== null) { - $resourcePath = str_replace( - "{" . "order_id" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'order_id' . '}', $this->serializer->toPathValue($order_id), $resourcePath); } @@ -430,27 +426,32 @@ public function getOrderByIdWithHttpInfo($order_id) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -509,7 +510,7 @@ public function placeOrderWithHttpInfo($body) throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder'); } - $resourcePath = substr('/store/order', 1); + $resourcePath = '/store/order'; $formParams = []; $queryParams = []; $headerParams = []; @@ -559,27 +560,32 @@ public function placeOrderWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 68d0a815b60..dc491c65d5e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -31,10 +31,10 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; -use Http\Client\Exception; +use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; -use Swagger\Client\AuthConfig; +use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; use Swagger\Client\ObjectSerializer; @@ -59,34 +59,34 @@ class UserApi protected $serializer; /** - * @var AuthConfig + * @var Configuration */ - protected $authConfig; + protected $config; /** * @param HttpClient $client * @param HeaderSelector $selector * @param ObjectSerializer $serializer - * @param AuthConfig $authConfig + * @param Configuration $config */ public function __construct( HttpClient $client, - AuthConfig $authConfig = null, + Configuration $config = null, HeaderSelector $selector = null, ObjectSerializer $serializer = null ) { $this->client = $client; $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); - $this->authConfig = $authConfig ?: new AuthConfig(); + $this->config = $config ?: new Configuration(); } /** - * @return AuthConfig + * @return Config */ - public function getAuthConfig() + public function getConfig() { - return $this->authConfig; + return $this->config; } /** @@ -121,7 +121,7 @@ public function createUserWithHttpInfo($body) throw new \InvalidArgumentException('Missing the required parameter $body when calling createUser'); } - $resourcePath = substr('/user', 1); + $resourcePath = '/user'; $formParams = []; $queryParams = []; $headerParams = []; @@ -171,19 +171,24 @@ public function createUserWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -237,7 +242,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithArrayInput'); } - $resourcePath = substr('/user/createWithArray', 1); + $resourcePath = '/user/createWithArray'; $formParams = []; $queryParams = []; $headerParams = []; @@ -287,19 +292,24 @@ public function createUsersWithArrayInputWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -353,7 +363,7 @@ public function createUsersWithListInputWithHttpInfo($body) throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithListInput'); } - $resourcePath = substr('/user/createWithList', 1); + $resourcePath = '/user/createWithList'; $formParams = []; $queryParams = []; $headerParams = []; @@ -403,19 +413,24 @@ public function createUsersWithListInputWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'POST', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -469,7 +484,7 @@ public function deleteUserWithHttpInfo($username) throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - $resourcePath = substr('/user/{username}', 1); + $resourcePath = '/user/{username}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -518,19 +533,24 @@ public function deleteUserWithHttpInfo($username) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'DELETE', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'DELETE', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -585,7 +605,7 @@ public function getUserByNameWithHttpInfo($username) throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - $resourcePath = substr('/user/{username}', 1); + $resourcePath = '/user/{username}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -634,27 +654,32 @@ public function getUserByNameWithHttpInfo($username) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\User', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); + } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); } + return [ + ObjectSerializer::deserialize($content, '\Swagger\Client\Model\User', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -719,7 +744,7 @@ public function loginUserWithHttpInfo($username, $password) throw new \InvalidArgumentException('Missing the required parameter $password when calling loginUser'); } - $resourcePath = substr('/user/login', 1); + $resourcePath = '/user/login'; $formParams = []; $queryParams = []; $headerParams = []; @@ -772,27 +797,32 @@ public function loginUserWithHttpInfo($username, $password) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); - } - return [ - ObjectSerializer::deserialize($content, 'string', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + $content = $response->getBody()->getContents(); + if ($returnType !== 'string') { //TODO return type file + $content = json_decode($content); + } + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -844,7 +874,7 @@ public function logoutUser() public function logoutUserWithHttpInfo() { - $resourcePath = substr('/user/logout', 1); + $resourcePath = '/user/logout'; $formParams = []; $queryParams = []; $headerParams = []; @@ -889,19 +919,24 @@ public function logoutUserWithHttpInfo() $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'GET', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( @@ -961,7 +996,7 @@ public function updateUserWithHttpInfo($username, $body) throw new \InvalidArgumentException('Missing the required parameter $body when calling updateUser'); } - $resourcePath = substr('/user/{username}', 1); + $resourcePath = '/user/{username}'; $formParams = []; $queryParams = []; $headerParams = []; @@ -1015,19 +1050,24 @@ public function updateUserWithHttpInfo($username, $body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $headers = array_merge($headerParams, $headers); - + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $request = new Request( + 'PUT', + $url, + $headers, + $httpBody + ); try { - $request = new Request( - 'PUT', - Uri::composeComponents('', '', $resourcePath, $query, ''), - $headers, - $httpBody - ); $response = $this->client->sendRequest($request); - return [null, $response->getStatusCode(), $response->getHeaders()]; - } catch (Exception $exception) { - throw new ApiException($exception->getMessage(), null, $exception); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), null, $e); + } + + if ($response->getStatusCode() >= 400) { + throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 2a252b39448..e277c5c18b7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -41,7 +41,7 @@ class Configuration /** * @var string */ - protected $host; + protected $host = 'http://petstore.swagger.io/v2'; /** * Associate array to store API key(s) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php index d30d82feb69..d0204352558 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/AuthTest.php @@ -12,7 +12,7 @@ class AuthTest extends \PHPUnit_Framework_TestCase { public function testCustomApiKeyHeader() { - $authConfig = new AuthConfig(); + $authConfig = new Configuration(); $authConfig->setApiKey('api_key', '123qwe'); $fakeHttpClient = new FakeHttpClient(); @@ -27,7 +27,7 @@ public function testCustomApiKeyHeader() public function testApiToken() { - $authConfig = new AuthConfig(); + $authConfig = new Configuration(); $authConfig->setAccessToken('asd123'); $fakeHttpClient = new FakeHttpClient(); @@ -45,7 +45,7 @@ public function testBasicAuth() $username = 'user'; $password = 'password'; - $authConfig = new AuthConfig(); + $authConfig = new Configuration(); $authConfig->setUsername($username); $authConfig->setPassword($password); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php new file mode 100644 index 00000000000..a7eefab0d34 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php @@ -0,0 +1,39 @@ +expectException(ApiException::class); + $this->expectExceptionCode(404); + $this->expectExceptionMessage('[404] Error connecting to the API (http://petstore.swagger.io/INVALID_URL/store/inventory)'); + + $config = new Configuration(); + $config->setHost('http://petstore.swagger.io/INVALID_URL'); + + $api = new Api\StoreApi( + new Client(), + $config + ); + $api->getInventory(); + } + + public function testWrongHost() + { + $this->expectException(ApiException::class); + $this->expectExceptionMessage('Could not resolve host'); + + $config = new Configuration(); + $config->setHost('http://wrong_host.zxc'); + + $api = new Api\StoreApi( + new Client(), + $config + ); + $api->getInventory(); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index ad2ef76f330..a4e7cec4e8b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -53,9 +53,9 @@ public static function setUpBeforeClass() $newPet->setTags(array($tag)); $newPet->setCategory($category); - $petApi = new Api\PetApi(new Client(new \GuzzleHttp\Client([ - 'base_uri' => 'http://petstore.swagger.io/v2/' - ]))); + $config = new Configuration(); + $petApi = new Api\PetApi(new Client(), $config); + // add a new pet (model) list(, $status) = $petApi->addPetWithHttpInfo($newPet); \PHPUnit_Framework_Assert::assertEquals(200, $status); @@ -64,9 +64,7 @@ public static function setUpBeforeClass() public function setUp() { $this->api = new Api\PetApi( - Client::createWithConfig([ - 'base_uri' => 'http://petstore.swagger.io/v2/' - ]) + new Client() ); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index bb6e1a18a06..4b492cf9d34 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -13,9 +13,7 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function setUp() { $this->api = new Api\StoreApi( - Client::createWithConfig([ - 'base_uri' => 'http://petstore.swagger.io/v2/' - ]) + new Client() ); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index eb487ce9335..b9a17bab2ee 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -21,9 +21,7 @@ public static function setUpBeforeClass() public function setUp() { $this->api = new Api\UserApi( - Client::createWithConfig([ - 'base_uri' => 'http://petstore.swagger.io/v2/' - ]) + new Client() ); } @@ -32,11 +30,11 @@ public function testLoginUser() { // initialize the API client // login - $response = $this->api->loginUser("xxxxx", "yyyyyyyy"); + $response = $this->api->loginUser('xxxxx', 'yyyyyyyy'); - $this->assertInternalType("string", $response); + $this->assertInternalType('string', $response); $this->assertRegExp( - "/^logged in user session/", + '/^logged in user session/', $response, "response string starts with 'logged in user session'" ); From 29a95165913f0cc7cf310e658e3b291aa4ee631d Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Wed, 22 Mar 2017 18:50:20 +0000 Subject: [PATCH 25/37] file downloading; readded some Configuration properties removed earlier --- .../main/resources/php/Configuration.mustache | 269 ++++++++++++++++-- .../resources/php/ObjectSerializer.mustache | 13 +- .../src/main/resources/php/api.mustache | 13 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 1 + .../SwaggerClient-php/lib/Configuration.php | 266 +++++++++++++++-- .../lib/ObjectSerializer.php | 13 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 15 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 56 +++- .../SwaggerClient-php/lib/Api/StoreApi.php | 40 ++- .../php/SwaggerClient-php/lib/Api/UserApi.php | 32 ++- .../SwaggerClient-php/lib/Configuration.php | 266 +++++++++++++++-- .../lib/ObjectSerializer.php | 13 +- .../SwaggerClient-php/tests/PetApiTest.php | 18 ++ .../SwaggerClient-php/tests/UserApiTest.php | 2 +- 14 files changed, 911 insertions(+), 106 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/Configuration.mustache b/modules/swagger-codegen/src/main/resources/php/Configuration.mustache index d6fa2cd2ab4..fe4c420fc49 100644 --- a/modules/swagger-codegen/src/main/resources/php/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Configuration.mustache @@ -20,6 +20,7 @@ namespace {{invokerPackage}}; /** * Configuration Class Doc Comment + * PHP version 5 * * @category Class * @package {{invokerPackage}} @@ -28,10 +29,7 @@ namespace {{invokerPackage}}; */ class Configuration { - /** - * @var string - */ - protected $host = '{{basePath}}'; + private static $defaultConfiguration; /** * Associate array to store API key(s) @@ -69,33 +67,60 @@ class Configuration protected $password = ''; /** - * Sets the host + * The default header(s) * - * @param string $host Host + * @var array + */ + protected $defaultHeaders = []; + + /** + * The host * - * @return $this + * @var string */ - public function setHost($host) - { - $this->host = $host; - return $this; - } + protected $host = '{{basePath}}'; /** - * Gets the host + * User agent of the HTTP request, set to "PHP-Swagger" by default * - * @return string Host + * @var string */ - public function getHost() + protected $userAgent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}'; + + /** + * Debug switch (default set to false) + * + * @var bool + */ + protected $debug = false; + + /** + * Debug file location (log to STDOUT by default) + * + * @var string + */ + protected $debugFile = 'php://output'; + + /** + * Debug file location (log to STDOUT by default) + * + * @var string + */ + protected $tempFolderPath; + + /** + * Constructor + */ + public function __construct() { - return $this->host; + $this->tempFolderPath = sys_get_temp_dir(); } /** * Sets API key * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $key API key or token + * @param string $key API key or token * * @return $this */ @@ -121,7 +146,7 @@ class Configuration * Sets the prefix for API key (e.g. Bearer) * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer + * @param string $prefix API key prefix, e.g. Bearer * * @return $this */ @@ -212,6 +237,213 @@ class Configuration return $this->password; } + /** + * Adds a default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * + * @throws \InvalidArgumentException + * @return $this + */ + public function addDefaultHeader($headerName, $headerValue) + { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * Gets the default header + * + * @return array An array of default header(s) + */ + public function getDefaultHeaders() + { + return $this->defaultHeaders; + } + + /** + * Deletes a default header + * + * @param string $headerName the header to delete + * + * @return $this + */ + public function deleteDefaultHeader($headerName) + { + unset($this->defaultHeaders[$headerName]); + return $this; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the detault configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK ({{invokerPackage}}) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' OpenAPI Spec Version: {{version}}' . PHP_EOL; + {{#artifactVersion}} + $report .= ' SDK Package Version: {{artifactVersion}}' . PHP_EOL; + {{/artifactVersion}} + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + /** * Get API key (with prefix if set) * @@ -237,4 +469,3 @@ class Configuration return $keyWithPrefix; } } - diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 2014eab8a99..e4c4dc8471b 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -251,6 +251,8 @@ class ObjectSerializer settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { + /** @var \Psr\Http\Message\StreamInterface $data */ + // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { @@ -258,13 +260,14 @@ class ObjectSerializer } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } - $deserialized = new \SplFileObject($filename, "w"); - $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->getDebug()) { - error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); } + fclose($file); - return $deserialized; + return new \SplFileObject($filename, 'r'); } elseif (method_exists($class, 'getAllowableEnumValues')) { if (!in_array($data, $class::getAllowableEnumValues())) { $imploded = implode("', '", $class::getAllowableEnumValues()); diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index a9fded3afb1..d8ba63b706e 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -301,11 +301,18 @@ use {{invokerPackage}}\ObjectSerializer; if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + {{#returnType}} - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '{{returnType}}', []), $response->getStatusCode(), diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 081f1844ddf..c2df91cff0e 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -183,6 +183,7 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index 1578eb976f7..3bcefa612d6 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -30,6 +30,7 @@ /** * Configuration Class Doc Comment + * PHP version 5 * * @category Class * @package Swagger\Client @@ -38,10 +39,7 @@ */ class Configuration { - /** - * @var string - */ - protected $host = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'; + private static $defaultConfiguration; /** * Associate array to store API key(s) @@ -79,33 +77,60 @@ class Configuration protected $password = ''; /** - * Sets the host + * The default header(s) * - * @param string $host Host + * @var array + */ + protected $defaultHeaders = []; + + /** + * The host * - * @return $this + * @var string */ - public function setHost($host) - { - $this->host = $host; - return $this; - } + protected $host = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'; /** - * Gets the host + * User agent of the HTTP request, set to "PHP-Swagger" by default * - * @return string Host + * @var string */ - public function getHost() + protected $userAgent = 'Swagger-Codegen/1.0.0/php'; + + /** + * Debug switch (default set to false) + * + * @var bool + */ + protected $debug = false; + + /** + * Debug file location (log to STDOUT by default) + * + * @var string + */ + protected $debugFile = 'php://output'; + + /** + * Debug file location (log to STDOUT by default) + * + * @var string + */ + protected $tempFolderPath; + + /** + * Constructor + */ + public function __construct() { - return $this->host; + $this->tempFolderPath = sys_get_temp_dir(); } /** * Sets API key * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $key API key or token + * @param string $key API key or token * * @return $this */ @@ -131,7 +156,7 @@ public function getApiKey($apiKeyIdentifier) * Sets the prefix for API key (e.g. Bearer) * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer + * @param string $prefix API key prefix, e.g. Bearer * * @return $this */ @@ -222,6 +247,210 @@ public function getPassword() return $this->password; } + /** + * Adds a default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * + * @throws \InvalidArgumentException + * @return $this + */ + public function addDefaultHeader($headerName, $headerValue) + { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * Gets the default header + * + * @return array An array of default header(s) + */ + public function getDefaultHeaders() + { + return $this->defaultHeaders; + } + + /** + * Deletes a default header + * + * @param string $headerName the header to delete + * + * @return $this + */ + public function deleteDefaultHeader($headerName) + { + unset($this->defaultHeaders[$headerName]); + return $this; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the detault configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' OpenAPI Spec Version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r' . PHP_EOL; + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + /** * Get API key (with prefix if set) * @@ -247,4 +476,3 @@ public function getApiKeyWithPrefix($apiKeyIdentifier) return $keyWithPrefix; } } - diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index 759790e17e3..6fa46c2f696 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -261,6 +261,8 @@ public static function deserialize($data, $class, $httpHeaders = null) settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { + /** @var \Psr\Http\Message\StreamInterface $data */ + // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { @@ -268,13 +270,14 @@ public static function deserialize($data, $class, $httpHeaders = null) } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } - $deserialized = new \SplFileObject($filename, "w"); - $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->getDebug()) { - error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); } + fclose($file); - return $deserialized; + return new \SplFileObject($filename, 'r'); } elseif (method_exists($class, 'getAllowableEnumValues')) { if (!in_array($data, $class::getAllowableEnumValues())) { $imploded = implode("', '", $class::getAllowableEnumValues()); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index bf524295849..83e590dbe88 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -189,10 +189,17 @@ public function testClientModelWithHttpInfo($body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Client', []), $response->getStatusCode(), @@ -462,6 +469,7 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -626,6 +634,7 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 3bc71517e1c..3aca1a019a7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -192,6 +192,7 @@ public function addPetWithHttpInfo($body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -322,6 +323,7 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -450,10 +452,17 @@ public function findPetsByStatusWithHttpInfo($status) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), $response->getStatusCode(), @@ -590,10 +599,17 @@ public function findPetsByTagsWithHttpInfo($tags) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), $response->getStatusCode(), @@ -728,10 +744,17 @@ public function getPetByIdWithHttpInfo($pet_id) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet', []), $response->getStatusCode(), @@ -865,6 +888,7 @@ public function updatePetWithHttpInfo($body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -1001,6 +1025,7 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -1139,10 +1164,17 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\ApiResponse', []), $response->getStatusCode(), diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 003993e0ea8..d0463507747 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -187,6 +187,7 @@ public function deleteOrderWithHttpInfo($order_id) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -303,10 +304,17 @@ public function getInventoryWithHttpInfo() if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, 'map[string,int]', []), $response->getStatusCode(), @@ -443,10 +451,17 @@ public function getOrderByIdWithHttpInfo($order_id) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), $response->getStatusCode(), @@ -577,10 +592,17 @@ public function placeOrderWithHttpInfo($body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), $response->getStatusCode(), diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index dc491c65d5e..3aad76db8fd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -188,6 +188,7 @@ public function createUserWithHttpInfo($body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -309,6 +310,7 @@ public function createUsersWithArrayInputWithHttpInfo($body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -430,6 +432,7 @@ public function createUsersWithListInputWithHttpInfo($body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -550,6 +553,7 @@ public function deleteUserWithHttpInfo($username) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -671,10 +675,17 @@ public function getUserByNameWithHttpInfo($username) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, '\Swagger\Client\Model\User', []), $response->getStatusCode(), @@ -814,10 +825,17 @@ public function loginUserWithHttpInfo($username, $password) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } - $content = $response->getBody()->getContents(); - if ($returnType !== 'string') { //TODO return type file - $content = json_decode($content); + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string' ) { + $content = json_decode($content); + } } + return [ ObjectSerializer::deserialize($content, 'string', []), $response->getStatusCode(), @@ -936,6 +954,7 @@ public function logoutUserWithHttpInfo() if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { @@ -1067,6 +1086,7 @@ public function updateUserWithHttpInfo($username, $body) if ($response->getStatusCode() >= 400) { throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); } + return [null, $response->getStatusCode(), $response->getHeaders()]; /** try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index e277c5c18b7..92b9ec0d009 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -30,6 +30,7 @@ /** * Configuration Class Doc Comment + * PHP version 5 * * @category Class * @package Swagger\Client @@ -38,10 +39,7 @@ */ class Configuration { - /** - * @var string - */ - protected $host = 'http://petstore.swagger.io/v2'; + private static $defaultConfiguration; /** * Associate array to store API key(s) @@ -79,33 +77,60 @@ class Configuration protected $password = ''; /** - * Sets the host + * The default header(s) * - * @param string $host Host + * @var array + */ + protected $defaultHeaders = []; + + /** + * The host * - * @return $this + * @var string */ - public function setHost($host) - { - $this->host = $host; - return $this; - } + protected $host = 'http://petstore.swagger.io/v2'; /** - * Gets the host + * User agent of the HTTP request, set to "PHP-Swagger" by default * - * @return string Host + * @var string */ - public function getHost() + protected $userAgent = 'Swagger-Codegen/1.0.0/php'; + + /** + * Debug switch (default set to false) + * + * @var bool + */ + protected $debug = false; + + /** + * Debug file location (log to STDOUT by default) + * + * @var string + */ + protected $debugFile = 'php://output'; + + /** + * Debug file location (log to STDOUT by default) + * + * @var string + */ + protected $tempFolderPath; + + /** + * Constructor + */ + public function __construct() { - return $this->host; + $this->tempFolderPath = sys_get_temp_dir(); } /** * Sets API key * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $key API key or token + * @param string $key API key or token * * @return $this */ @@ -131,7 +156,7 @@ public function getApiKey($apiKeyIdentifier) * Sets the prefix for API key (e.g. Bearer) * * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer + * @param string $prefix API key prefix, e.g. Bearer * * @return $this */ @@ -222,6 +247,210 @@ public function getPassword() return $this->password; } + /** + * Adds a default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * + * @throws \InvalidArgumentException + * @return $this + */ + public function addDefaultHeader($headerName, $headerValue) + { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * Gets the default header + * + * @return array An array of default header(s) + */ + public function getDefaultHeaders() + { + return $this->defaultHeaders; + } + + /** + * Deletes a default header + * + * @param string $headerName the header to delete + * + * @return $this + */ + public function deleteDefaultHeader($headerName) + { + unset($this->defaultHeaders[$headerName]); + return $this; + } + + /** + * Sets the host + * + * @param string $host Host + * + * @return $this + */ + public function setHost($host) + { + $this->host = $host; + return $this; + } + + /** + * Gets the host + * + * @return string Host + */ + public function getHost() + { + return $this->host; + } + + /** + * Sets the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * + * @throws \InvalidArgumentException + * @return $this + */ + public function setUserAgent($userAgent) + { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * Gets the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Sets debug flag + * + * @param bool $debug Debug flag + * + * @return $this + */ + public function setDebug($debug) + { + $this->debug = $debug; + return $this; + } + + /** + * Gets the debug flag + * + * @return bool + */ + public function getDebug() + { + return $this->debug; + } + + /** + * Sets the debug file + * + * @param string $debugFile Debug file + * + * @return $this + */ + public function setDebugFile($debugFile) + { + $this->debugFile = $debugFile; + return $this; + } + + /** + * Gets the debug file + * + * @return string + */ + public function getDebugFile() + { + return $this->debugFile; + } + + /** + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * + * @return $this + */ + public function setTempFolderPath($tempFolderPath) + { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * Gets the temp folder path + * + * @return string Temp folder path + */ + public function getTempFolderPath() + { + return $this->tempFolderPath; + } + + /** + * Gets the default configuration instance + * + * @return Configuration + */ + public static function getDefaultConfiguration() + { + if (self::$defaultConfiguration === null) { + self::$defaultConfiguration = new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * Sets the detault configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void + */ + public static function setDefaultConfiguration(Configuration $config) + { + self::$defaultConfiguration = $config; + } + + /** + * Gets the essential information for debugging + * + * @return string The report for debugging + */ + public static function toDebugReport() + { + $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; + $report .= ' OS: ' . php_uname() . PHP_EOL; + $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; + $report .= ' OpenAPI Spec Version: 1.0.0' . PHP_EOL; + $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; + + return $report; + } + /** * Get API key (with prefix if set) * @@ -247,4 +476,3 @@ public function getApiKeyWithPrefix($apiKeyIdentifier) return $keyWithPrefix; } } - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 281e51143b6..a9ef28e79f0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -261,6 +261,8 @@ public static function deserialize($data, $class, $httpHeaders = null) settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { + /** @var \Psr\Http\Message\StreamInterface $data */ + // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { @@ -268,13 +270,14 @@ public static function deserialize($data, $class, $httpHeaders = null) } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } - $deserialized = new \SplFileObject($filename, "w"); - $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->getDebug()) { - error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); + + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); } + fclose($file); - return $deserialized; + return new \SplFileObject($filename, 'r'); } elseif (method_exists($class, 'getAllowableEnumValues')) { if (!in_array($data, $class::getAllowableEnumValues())) { $imploded = implode("', '", $class::getAllowableEnumValues()); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index a4e7cec4e8b..68e13feb774 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -389,4 +389,22 @@ public function testDefaultValues() $this->assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } + +// Disabled as currently we don't have any endpoint that would return file +// For testing I just replaced url and return type in Api method. +// public function testDownloadingLargeFile() +// { +// $petId = 10005; +// $config = new Configuration(); +// $config->setHost('https://getcomposer.org'); +// $api = new PetApi(new Client(), $config); +// $result = $api->getPetById($petId); +// $this->assertInstanceOf(\SplFileObject::class, $result); +// var_dump([ +// 'peak mem (MiB)' => memory_get_peak_usage(true)/1024/1024, +// 'file size (MiB)' => $result->getSize()/1024/1024, +// 'path' => sys_get_temp_dir() . '/' . $result->getFilename() +// ]); +// } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index b9a17bab2ee..e6539ac1338 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -25,7 +25,7 @@ public function setUp() ); } - // test login user + // test login use public function testLoginUser() { // initialize the API client From b536efd1dfab0f541a5a15f855a50d4b5e3fd768 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 23 Mar 2017 08:34:31 +0000 Subject: [PATCH 26/37] readded default headers --- .../src/main/resources/php/api.mustache | 6 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 6 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 18 +++++- .../php/SwaggerClient-php/lib/Api/PetApi.php | 48 +++++++++++++--- .../SwaggerClient-php/lib/Api/StoreApi.php | 24 ++++++-- .../php/SwaggerClient-php/lib/Api/UserApi.php | 48 +++++++++++++--- .../SwaggerClient-php/tests/HeadersTest.php | 57 +++++++++++++++++++ 7 files changed, 182 insertions(+), 25 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index d8ba63b706e..bb998053fc4 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -283,8 +283,12 @@ use {{invokerPackage}}\ObjectSerializer; {{/authMethods}} $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( '{{httpMethod}}', diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index c2df91cff0e..dd991e3b009 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -165,8 +165,12 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'PUT', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 83e590dbe88..8bef0e9649a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -171,8 +171,12 @@ public function testClientModelWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'PATCH', @@ -451,8 +455,12 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', @@ -616,8 +624,12 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 3aca1a019a7..d33c6f77f2a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -174,8 +174,12 @@ public function addPetWithHttpInfo($body) } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', @@ -305,8 +309,12 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'DELETE', @@ -434,8 +442,12 @@ public function findPetsByStatusWithHttpInfo($status) } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -581,8 +593,12 @@ public function findPetsByTagsWithHttpInfo($tags) } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -726,8 +742,12 @@ public function getPetByIdWithHttpInfo($pet_id) } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -870,8 +890,12 @@ public function updatePetWithHttpInfo($body) } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'PUT', @@ -1007,8 +1031,12 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', @@ -1146,8 +1174,12 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index d0463507747..26b367bad6f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -169,8 +169,12 @@ public function deleteOrderWithHttpInfo($order_id) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'DELETE', @@ -286,8 +290,12 @@ public function getInventoryWithHttpInfo() } $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -433,8 +441,12 @@ public function getOrderByIdWithHttpInfo($order_id) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -574,8 +586,12 @@ public function placeOrderWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 3aad76db8fd..38825aa50f3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -170,8 +170,12 @@ public function createUserWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', @@ -292,8 +296,12 @@ public function createUsersWithArrayInputWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', @@ -414,8 +422,12 @@ public function createUsersWithListInputWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'POST', @@ -535,8 +547,12 @@ public function deleteUserWithHttpInfo($username) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'DELETE', @@ -657,8 +673,12 @@ public function getUserByNameWithHttpInfo($username) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -807,8 +827,12 @@ public function loginUserWithHttpInfo($username, $password) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -936,8 +960,12 @@ public function logoutUserWithHttpInfo() $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'GET', @@ -1068,8 +1096,12 @@ public function updateUserWithHttpInfo($username, $body) $query = \GuzzleHttp\Psr7\build_query($queryParams); - $headers = array_merge($headerParams, $headers); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); $request = new Request( 'PUT', diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php new file mode 100644 index 00000000000..b316451a196 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php @@ -0,0 +1,57 @@ +fakeHttpClient = new FakeHttpClient(); + } + + public function testDefaultHeaders() + { + $config = new Configuration(); + $config->addDefaultHeader('someHeader', 'someValue'); + $api = new Api\PetApi($this->fakeHttpClient, $config); + + $api->getPetById(3); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('someHeader', $headers); + $this->assertEquals(['someValue'], $headers['someHeader']); + } + + public function testDefaultHeadersMayBeOverwritten() + { + $config = new Configuration(); + $config->addDefaultHeader('Accept', 'text/plain'); + $config->addDefaultHeader('Content-Type', 'text/plain'); + $config->addDefaultHeader('Something-Else', 'text/plain'); + $api = new Api\PetApi($this->fakeHttpClient, $config); + + $api->getPetById(3); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('Accept', $headers); + $this->assertEquals(['application/json'], $headers['Accept']); + + $this->assertArrayHasKey('Content-Type', $headers); + $this->assertEquals(['application/json'], $headers['Content-Type']); + + $this->assertArrayHasKey('Something-Else', $headers); + $this->assertEquals(['text/plain'], $headers['Something-Else']); + } +} From 78f192a172976eea6e2275a3c1d2bff02951c130 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 24 Mar 2017 09:24:32 +0000 Subject: [PATCH 27/37] made responses and return types work same way as earlier --- .../src/main/resources/php/api.mustache | 87 ++-- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 39 +- .../docs/Model/DefaultError.md | 11 + .../php/SwaggerClient-php/docs/Model/Error.md | 11 + .../php/SwaggerClient-php/lib/Api/FakeApi.php | 143 +++--- .../php/SwaggerClient-php/lib/Api/PetApi.php | 416 ++++++++---------- .../SwaggerClient-php/lib/Api/StoreApi.php | 234 +++++----- .../php/SwaggerClient-php/lib/Api/UserApi.php | 364 +++++++-------- .../lib/Model/DefaultError.php | 256 +++++++++++ .../php/SwaggerClient-php/lib/Model/Error.php | 256 +++++++++++ .../test/Model/DefaultErrorTest.php | 101 +++++ .../test/Model/ErrorTest.php | 101 +++++ .../tests/FakeHttpClient.php | 12 +- .../tests/ResponseTypesTest.php | 93 ++++ 14 files changed, 1414 insertions(+), 710 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Model/DefaultError.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Model/Error.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/test/Model/DefaultErrorTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/test/Model/ErrorTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index bb998053fc4..28a21446c89 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -296,74 +296,59 @@ use {{invokerPackage}}\ObjectSerializer; $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - {{#returnType}} - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - - return [ - ObjectSerializer::deserialize($content, '{{returnType}}', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - {{/returnType}} - {{^returnType}} - return [null, $response->getStatusCode(), $response->getHeaders()]; - {{/returnType}} -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - '{{httpMethod}}', - $queryParams, - $httpBody, - $headerParams, - {{#returnType}} - '{{returnType}}', - {{/returnType}} - {{^returnType}} - null, - {{/returnType}} - '{{{path}}}' - ); {{#returnType}} - return [$this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader), $statusCode, $httpHeader]; + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; {{/returnType}} {{^returnType}} - return [null, $statusCode, $httpHeader]; + return [null, $statusCode, $response->getHeaders()]; {{/returnType}} + } catch (ApiException $e) { switch ($e->getCode()) { - {{#responses}} - {{#dataType}} + {{#responses}} + {{#dataType}} {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); $e->setResponseObject($data); break; - {{/dataType}} - {{/responses}} + {{/dataType}} + {{/responses}} } - throw $e; } -*/ } {{/operation}} } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index dd991e3b009..f5f31598c53 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -178,36 +178,31 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/fake' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/DefaultError.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/DefaultError.md new file mode 100644 index 00000000000..5ed20691fdc --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/DefaultError.md @@ -0,0 +1,11 @@ +# DefaultError + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**error** | **string** | | [optional] +**code** | **float** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/Error.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Error.md new file mode 100644 index 00000000000..5cf4ee67d0e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Error.md @@ -0,0 +1,11 @@ +# Error + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**error** | **string** | | [optional] +**code** | **float** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 8bef0e9649a..f384d74a0f8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -184,55 +184,50 @@ public function testClientModelWithHttpInfo($body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Client', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PATCH', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Client', - '/fake' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Client', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Client', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Client', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation testEndpointParameters @@ -468,37 +463,32 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/fake' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation testEnumParameters @@ -637,36 +627,31 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - null, - '/fake' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index d33c6f77f2a..723779f86f4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -187,37 +187,32 @@ public function addPetWithHttpInfo($body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation deletePet @@ -322,37 +317,32 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'DELETE', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet/{petId}' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation findPetsByStatus @@ -455,55 +445,50 @@ public function findPetsByStatusWithHttpInfo($status) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet[]', - '/pet/findByStatus' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation findPetsByTags @@ -606,55 +591,50 @@ public function findPetsByTagsWithHttpInfo($tags) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet[]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet[]', - '/pet/findByTags' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation getPetById @@ -755,55 +735,50 @@ public function getPetByIdWithHttpInfo($pet_id) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Pet', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet', - '/pet/{petId}' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation updatePet @@ -903,37 +878,32 @@ public function updatePetWithHttpInfo($body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation updatePetWithForm @@ -1044,37 +1014,32 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet/{petId}' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation uploadFile @@ -1187,54 +1152,49 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\ApiResponse', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\ApiResponse', - '/pet/{petId}/uploadImage' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\ApiResponse', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 26b367bad6f..2850dcf9236 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -182,37 +182,32 @@ public function deleteOrderWithHttpInfo($order_id) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'DELETE', - $queryParams, - $httpBody, - $headerParams, - null, - '/store/order/{order_id}' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation getInventory @@ -303,55 +298,50 @@ public function getInventoryWithHttpInfo() $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, 'map[string,int]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - 'map[string,int]', - '/store/inventory' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation getOrderById @@ -454,55 +444,50 @@ public function getOrderByIdWithHttpInfo($order_id) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Order', - '/store/order/{order_id}' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation placeOrder @@ -599,54 +584,49 @@ public function placeOrderWithHttpInfo($body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\Order', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Order', - '/store/order' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 38825aa50f3..d3fa892c9e5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -183,37 +183,32 @@ public function createUserWithHttpInfo($body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/user' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation createUsersWithArrayInput @@ -309,37 +304,32 @@ public function createUsersWithArrayInputWithHttpInfo($body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/createWithArray' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation createUsersWithListInput @@ -435,37 +425,32 @@ public function createUsersWithListInputWithHttpInfo($body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/createWithList' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation deleteUser @@ -560,37 +545,32 @@ public function deleteUserWithHttpInfo($username) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'DELETE', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/{username}' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation getUserByName @@ -686,55 +666,50 @@ public function getUserByNameWithHttpInfo($username) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, '\Swagger\Client\Model\User', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\User', - '/user/{username}' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation loginUser @@ -840,55 +815,50 @@ public function loginUserWithHttpInfo($username, $password) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - $responseBody = $response->getBody(); - if ($returnType === '\SplFileObject') { - $content = $responseBody; //stream goes to serializer - } else { - $content = $responseBody->getContents(); - if ($returnType !== 'string' ) { - $content = json_decode($content); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); } - } - return [ - ObjectSerializer::deserialize($content, 'string', []), - $response->getStatusCode(), - $response->getHeaders() - ]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - 'string', - '/user/login' - ); + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } -*/ } /** * Operation logoutUser @@ -973,37 +943,32 @@ public function logoutUserWithHttpInfo() $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/logout' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } /** * Operation updateUser @@ -1109,36 +1074,31 @@ public function updateUserWithHttpInfo($username, $body) $headers, $httpBody ); + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), null, $e); - } + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } - if ($response->getStatusCode() >= 400) { - throw new ApiException("[{$response->getStatusCode()}] Error connecting to the API ($url)", $response->getStatusCode()); - } + $statusCode = $response->getStatusCode(); - return [null, $response->getStatusCode(), $response->getHeaders()]; -/** - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/{username}' - ); + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; - return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } -*/ } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php new file mode 100644 index 00000000000..dfe1553ce38 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php @@ -0,0 +1,256 @@ + 'string', + 'code' => 'float' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'error' => 'error', + 'code' => 'code' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'error' => 'setError', + 'code' => 'setCode' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'error' => 'getError', + 'code' => 'getCode' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['error'] = isset($data['error']) ? $data['error'] : null; + $this->container['code'] = isset($data['code']) ? $data['code'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets error + * @return string + */ + public function getError() + { + return $this->container['error']; + } + + /** + * Sets error + * @param string $error + * @return $this + */ + public function setError($error) + { + $this->container['error'] = $error; + + return $this; + } + + /** + * Gets code + * @return float + */ + public function getCode() + { + return $this->container['code']; + } + + /** + * Sets code + * @param float $code + * @return $this + */ + public function setCode($code) + { + $this->container['code'] = $code; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php new file mode 100644 index 00000000000..243ee31c101 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php @@ -0,0 +1,256 @@ + 'string', + 'code' => 'float' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'error' => 'error', + 'code' => 'code' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'error' => 'setError', + 'code' => 'setCode' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'error' => 'getError', + 'code' => 'getCode' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['error'] = isset($data['error']) ? $data['error'] : null; + $this->container['code'] = isset($data['code']) ? $data['code'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets error + * @return string + */ + public function getError() + { + return $this->container['error']; + } + + /** + * Sets error + * @param string $error + * @return $this + */ + public function setError($error) + { + $this->container['error'] = $error; + + return $this; + } + + /** + * Gets code + * @return float + */ + public function getCode() + { + return $this->container['code']; + } + + /** + * Sets code + * @param float $code + * @return $this + */ + public function setCode($code) + { + $this->container['code'] = $code; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/DefaultErrorTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/DefaultErrorTest.php new file mode 100644 index 00000000000..b41fbe327a0 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/DefaultErrorTest.php @@ -0,0 +1,101 @@ +request = $request; - return new Response(200); + return $this->response ?: new Response(200); } /** @@ -35,4 +37,12 @@ public function getLastRequest() { return $this->request; } + + /** + * @param null|ResponseInterface $response + */ + public function setResponse(ResponseInterface $response = null) + { + $this->response = $response; + } } \ No newline at end of file diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.php new file mode 100644 index 00000000000..7c6281aec5c --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.php @@ -0,0 +1,93 @@ +fakeHttpClient = new FakeHttpClient(); + $this->api = new PetApi($this->fakeHttpClient); + } + + public function testDefined200ReturnType() + { + $this->fakeHttpClient->setResponse(new Response(200, [], json_encode([]))); + $result = $this->api->getPetById(123); + + $this->assertInstanceOf(Pet::class, $result); + } + + public function testDefault2xxReturnType() + { + $this->fakeHttpClient->setResponse(new Response(255, [], json_encode([]))); + $result = $this->api->getPetById(123); + + $this->assertInstanceOf(Pet::class, $result); + } + + public function testDefinedErrorException() + { + $statusCode = 400; + + $this->expectException(ApiException::class); + $this->expectExceptionCode($statusCode); + + $this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}')); + $this->api->getPetById(123); + } + +// missing case in spec: +// responses: +// '400': +// description: failure +// schema: +// $ref: '#/definitions/Error' +// public function testDefinedErrorResponseObject() +// { +// $result = null; +// try { +// $this->fakeHttpClient->setResponse(new Response(400, [], '{}')); +// $this->api->getPetById(123); +// } catch (ApiException $e) { +// $result = $e->getResponseObject(); +// } +// +// $this->assertInstanceOf(Error::class, $result); +// } + + public function testDefaultErrorException() + { + $statusCode = 404; + + $this->expectException(ApiException::class); + $this->expectExceptionCode($statusCode); + + $this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}')); + $this->api->getPetById(123); + } + + public function testDefaultErrorResponseObject() + { + $result = null; + try { + $this->fakeHttpClient->setResponse(new Response(404, [], '{}')); + $this->api->getPetById(123); + } catch (ApiException $e) { + $result = $e->getResponseObject(); + } + + $this->assertNull($result); + } +} From cea26931c3c9d1dbfa697074389f3fbfe4ec6cfb Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 24 Mar 2017 09:50:19 +0000 Subject: [PATCH 28/37] made all methods static in ObjectSerializer --- .../resources/php/ObjectSerializer.mustache | 22 +++---- .../src/main/resources/php/api.mustache | 29 +++------ .../php/SwaggerClient-php/lib/Api/FakeApi.php | 15 +---- .../lib/ObjectSerializer.php | 22 +++---- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 61 ++++++++----------- .../php/SwaggerClient-php/lib/Api/PetApi.php | 39 +++++------- .../SwaggerClient-php/lib/Api/StoreApi.php | 17 ++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 23 +++---- .../lib/ObjectSerializer.php | 22 +++---- 9 files changed, 98 insertions(+), 152 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index e4c4dc8471b..d1eef963ab2 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -75,7 +75,7 @@ class ObjectSerializer * * @return string the sanitized filename */ - public function sanitizeFilename($filename) + public static function sanitizeFilename($filename) { if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { return $match[1]; @@ -92,9 +92,9 @@ class ObjectSerializer * * @return string the serialized object */ - public function toPathValue($value) + public static function toPathValue($value) { - return rawurlencode($this->toString($value)); + return rawurlencode(self::toString($value)); } /** @@ -107,12 +107,12 @@ class ObjectSerializer * * @return string the serialized object */ - public function toQueryValue($object) + public static function toQueryValue($object) { if (is_array($object)) { return implode(',', $object); } else { - return $this->toString($object); + return self::toString($object); } } @@ -125,9 +125,9 @@ class ObjectSerializer * * @return string the header string */ - public function toHeaderValue($value) + public static function toHeaderValue($value) { - return $this->toString($value); + return self::toString($value); } /** @@ -139,12 +139,12 @@ class ObjectSerializer * * @return string the form string */ - public function toFormValue($value) + public static function toFormValue($value) { if ($value instanceof \SplFileObject) { return $value->getRealPath(); } else { - return $this->toString($value); + return self::toString($value); } } @@ -157,7 +157,7 @@ class ObjectSerializer * * @return string the header string */ - public function toString($value) + public static function toString($value) { if ($value instanceof \DateTime) { // datetime in ISO8601 format return $value->format(\DateTime::ATOM); @@ -176,7 +176,7 @@ class ObjectSerializer * * @return string */ - public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) + public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { // http_build_query() almost does the job for us. We just diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 28a21446c89..326db84b5c3 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -20,7 +20,6 @@ namespace {{apiPackage}}; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use GuzzleHttp\Psr7\Uri; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use {{invokerPackage}}\ApiException; @@ -43,11 +42,6 @@ use {{invokerPackage}}\ObjectSerializer; */ protected $client; - /** - * @var ObjectSerializer - */ - protected $serializer; - /** * @var Configuration */ @@ -56,23 +50,20 @@ use {{invokerPackage}}\ObjectSerializer; /** * @param HttpClient $client * @param HeaderSelector $selector - * @param ObjectSerializer $serializer * @param Configuration $config */ public function __construct( HttpClient $client, Configuration $config = null, - HeaderSelector $selector = null, - ObjectSerializer $serializer = null + HeaderSelector $selector = null ) { $this->client = $client; - $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); $this->config = $config ?: new Configuration(); } /** - * @return Config + * @return Configuration */ public function getConfig() { @@ -179,22 +170,22 @@ use {{invokerPackage}}\ObjectSerializer; // query params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->serializer->serializeCollection(${{paramName}}, '{{collectionFormat}}', true); + ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}', true); } {{/collectionFormat}} if (${{paramName}} !== null) { - $queryParams['{{baseName}}'] = $this->serializer->toQueryValue(${{paramName}}); + $queryParams['{{baseName}}'] = ObjectSerializer::toQueryValue(${{paramName}}); } {{/queryParams}} {{#headerParams}} // header params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->serializer->serializeCollection(${{paramName}}, '{{collectionFormat}}'); + ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}'); } {{/collectionFormat}} if (${{paramName}} !== null) { - $headerParams['{{baseName}}'] = $this->serializer->toHeaderValue(${{paramName}}); + $headerParams['{{baseName}}'] = ObjectSerializer::toHeaderValue(${{paramName}}); } {{/headerParams}} @@ -202,11 +193,11 @@ use {{invokerPackage}}\ObjectSerializer; // path params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->serializer->serializeCollection(${{paramName}}, '{{collectionFormat}}'); + ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}'); } {{/collectionFormat}} if (${{paramName}} !== null) { - $resourcePath = str_replace('{' . '{{baseName}}' . '}', $this->serializer->toPathValue(${{paramName}}), $resourcePath); + $resourcePath = str_replace('{' . '{{baseName}}' . '}', ObjectSerializer::toPathValue(${{paramName}}), $resourcePath); } {{/pathParams}} @@ -215,10 +206,10 @@ use {{invokerPackage}}\ObjectSerializer; if (${{paramName}} !== null) { {{#isFile}} $multipart = true; - $formParams['file'] = \GuzzleHttp\Psr7\try_fopen($this->serializer->toFormValue($file), 'rb'); + $formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb'); {{/isFile}} {{^isFile}} - $formParams['{{baseName}}'] = $this->serializer->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = ObjectSerializer::toFormValue(${{paramName}}); {{/isFile}} } {{/formParams}} diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index f5f31598c53..b10f5d1fe5e 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -30,7 +30,6 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use GuzzleHttp\Psr7\Uri; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -53,11 +52,6 @@ class FakeApi */ protected $client; - /** - * @var ObjectSerializer - */ - protected $serializer; - /** * @var Configuration */ @@ -66,23 +60,20 @@ class FakeApi /** * @param HttpClient $client * @param HeaderSelector $selector - * @param ObjectSerializer $serializer * @param Configuration $config */ public function __construct( HttpClient $client, Configuration $config = null, - HeaderSelector $selector = null, - ObjectSerializer $serializer = null + HeaderSelector $selector = null ) { $this->client = $client; - $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); $this->config = $config ?: new Configuration(); } /** - * @return Config + * @return Configuration */ public function getConfig() { @@ -129,7 +120,7 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn // form params if ($test_code_inject____end____rn_n_r !== null) { - $formParams['test code inject */ ' " =end -- \r\n \n \r'] = $this->serializer->toFormValue($test_code_inject____end____rn_n_r); + $formParams['test code inject */ ' " =end -- \r\n \n \r'] = ObjectSerializer::toFormValue($test_code_inject____end____rn_n_r); } // for model (json/xml) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index 6fa46c2f696..9ab68d2e4a7 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -85,7 +85,7 @@ public static function sanitizeForSerialization($data) * * @return string the sanitized filename */ - public function sanitizeFilename($filename) + public static function sanitizeFilename($filename) { if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { return $match[1]; @@ -102,9 +102,9 @@ public function sanitizeFilename($filename) * * @return string the serialized object */ - public function toPathValue($value) + public static function toPathValue($value) { - return rawurlencode($this->toString($value)); + return rawurlencode(self::toString($value)); } /** @@ -117,12 +117,12 @@ public function toPathValue($value) * * @return string the serialized object */ - public function toQueryValue($object) + public static function toQueryValue($object) { if (is_array($object)) { return implode(',', $object); } else { - return $this->toString($object); + return self::toString($object); } } @@ -135,9 +135,9 @@ public function toQueryValue($object) * * @return string the header string */ - public function toHeaderValue($value) + public static function toHeaderValue($value) { - return $this->toString($value); + return self::toString($value); } /** @@ -149,12 +149,12 @@ public function toHeaderValue($value) * * @return string the form string */ - public function toFormValue($value) + public static function toFormValue($value) { if ($value instanceof \SplFileObject) { return $value->getRealPath(); } else { - return $this->toString($value); + return self::toString($value); } } @@ -167,7 +167,7 @@ public function toFormValue($value) * * @return string the header string */ - public function toString($value) + public static function toString($value) { if ($value instanceof \DateTime) { // datetime in ISO8601 format return $value->format(\DateTime::ATOM); @@ -186,7 +186,7 @@ public function toString($value) * * @return string */ - public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) + public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { // http_build_query() almost does the job for us. We just diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index f384d74a0f8..08c6426b831 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -30,7 +30,6 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use GuzzleHttp\Psr7\Uri; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -53,11 +52,6 @@ class FakeApi */ protected $client; - /** - * @var ObjectSerializer - */ - protected $serializer; - /** * @var Configuration */ @@ -66,23 +60,20 @@ class FakeApi /** * @param HttpClient $client * @param HeaderSelector $selector - * @param ObjectSerializer $serializer * @param Configuration $config */ public function __construct( HttpClient $client, Configuration $config = null, - HeaderSelector $selector = null, - ObjectSerializer $serializer = null + HeaderSelector $selector = null ) { $this->client = $client; - $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); $this->config = $config ?: new Configuration(); } /** - * @return Config + * @return Configuration */ public function getConfig() { @@ -358,59 +349,59 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi // form params if ($integer !== null) { - $formParams['integer'] = $this->serializer->toFormValue($integer); + $formParams['integer'] = ObjectSerializer::toFormValue($integer); } // form params if ($int32 !== null) { - $formParams['int32'] = $this->serializer->toFormValue($int32); + $formParams['int32'] = ObjectSerializer::toFormValue($int32); } // form params if ($int64 !== null) { - $formParams['int64'] = $this->serializer->toFormValue($int64); + $formParams['int64'] = ObjectSerializer::toFormValue($int64); } // form params if ($number !== null) { - $formParams['number'] = $this->serializer->toFormValue($number); + $formParams['number'] = ObjectSerializer::toFormValue($number); } // form params if ($float !== null) { - $formParams['float'] = $this->serializer->toFormValue($float); + $formParams['float'] = ObjectSerializer::toFormValue($float); } // form params if ($double !== null) { - $formParams['double'] = $this->serializer->toFormValue($double); + $formParams['double'] = ObjectSerializer::toFormValue($double); } // form params if ($string !== null) { - $formParams['string'] = $this->serializer->toFormValue($string); + $formParams['string'] = ObjectSerializer::toFormValue($string); } // form params if ($pattern_without_delimiter !== null) { - $formParams['pattern_without_delimiter'] = $this->serializer->toFormValue($pattern_without_delimiter); + $formParams['pattern_without_delimiter'] = ObjectSerializer::toFormValue($pattern_without_delimiter); } // form params if ($byte !== null) { - $formParams['byte'] = $this->serializer->toFormValue($byte); + $formParams['byte'] = ObjectSerializer::toFormValue($byte); } // form params if ($binary !== null) { - $formParams['binary'] = $this->serializer->toFormValue($binary); + $formParams['binary'] = ObjectSerializer::toFormValue($binary); } // form params if ($date !== null) { - $formParams['date'] = $this->serializer->toFormValue($date); + $formParams['date'] = ObjectSerializer::toFormValue($date); } // form params if ($date_time !== null) { - $formParams['dateTime'] = $this->serializer->toFormValue($date_time); + $formParams['dateTime'] = ObjectSerializer::toFormValue($date_time); } // form params if ($password !== null) { - $formParams['password'] = $this->serializer->toFormValue($password); + $formParams['password'] = ObjectSerializer::toFormValue($password); } // form params if ($callback !== null) { - $formParams['callback'] = $this->serializer->toFormValue($callback); + $formParams['callback'] = ObjectSerializer::toFormValue($callback); } // for model (json/xml) @@ -542,43 +533,43 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ // query params if (is_array($enum_query_string_array)) { - $enum_query_string_array = $this->serializer->serializeCollection($enum_query_string_array, 'csv', true); + $enum_query_string_array = ObjectSerializer::serializeCollection($enum_query_string_array, 'csv', true); } if ($enum_query_string_array !== null) { - $queryParams['enum_query_string_array'] = $this->serializer->toQueryValue($enum_query_string_array); + $queryParams['enum_query_string_array'] = ObjectSerializer::toQueryValue($enum_query_string_array); } // query params if ($enum_query_string !== null) { - $queryParams['enum_query_string'] = $this->serializer->toQueryValue($enum_query_string); + $queryParams['enum_query_string'] = ObjectSerializer::toQueryValue($enum_query_string); } // query params if ($enum_query_integer !== null) { - $queryParams['enum_query_integer'] = $this->serializer->toQueryValue($enum_query_integer); + $queryParams['enum_query_integer'] = ObjectSerializer::toQueryValue($enum_query_integer); } // header params if (is_array($enum_header_string_array)) { - $enum_header_string_array = $this->serializer->serializeCollection($enum_header_string_array, 'csv'); + $enum_header_string_array = ObjectSerializer::serializeCollection($enum_header_string_array, 'csv'); } if ($enum_header_string_array !== null) { - $headerParams['enum_header_string_array'] = $this->serializer->toHeaderValue($enum_header_string_array); + $headerParams['enum_header_string_array'] = ObjectSerializer::toHeaderValue($enum_header_string_array); } // header params if ($enum_header_string !== null) { - $headerParams['enum_header_string'] = $this->serializer->toHeaderValue($enum_header_string); + $headerParams['enum_header_string'] = ObjectSerializer::toHeaderValue($enum_header_string); } // form params if ($enum_form_string_array !== null) { - $formParams['enum_form_string_array'] = $this->serializer->toFormValue($enum_form_string_array); + $formParams['enum_form_string_array'] = ObjectSerializer::toFormValue($enum_form_string_array); } // form params if ($enum_form_string !== null) { - $formParams['enum_form_string'] = $this->serializer->toFormValue($enum_form_string); + $formParams['enum_form_string'] = ObjectSerializer::toFormValue($enum_form_string); } // form params if ($enum_query_double !== null) { - $formParams['enum_query_double'] = $this->serializer->toFormValue($enum_query_double); + $formParams['enum_query_double'] = ObjectSerializer::toFormValue($enum_query_double); } // for model (json/xml) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 723779f86f4..ad608c547b6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -30,7 +30,6 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use GuzzleHttp\Psr7\Uri; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -53,11 +52,6 @@ class PetApi */ protected $client; - /** - * @var ObjectSerializer - */ - protected $serializer; - /** * @var Configuration */ @@ -66,23 +60,20 @@ class PetApi /** * @param HttpClient $client * @param HeaderSelector $selector - * @param ObjectSerializer $serializer * @param Configuration $config */ public function __construct( HttpClient $client, Configuration $config = null, - HeaderSelector $selector = null, - ObjectSerializer $serializer = null + HeaderSelector $selector = null ) { $this->client = $client; - $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); $this->config = $config ?: new Configuration(); } /** - * @return Config + * @return Configuration */ public function getConfig() { @@ -258,12 +249,12 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) // header params if ($api_key !== null) { - $headerParams['api_key'] = $this->serializer->toHeaderValue($api_key); + $headerParams['api_key'] = ObjectSerializer::toHeaderValue($api_key); } // path params if ($pet_id !== null) { - $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::toPathValue($pet_id), $resourcePath); } @@ -387,10 +378,10 @@ public function findPetsByStatusWithHttpInfo($status) // query params if (is_array($status)) { - $status = $this->serializer->serializeCollection($status, 'csv', true); + $status = ObjectSerializer::serializeCollection($status, 'csv', true); } if ($status !== null) { - $queryParams['status'] = $this->serializer->toQueryValue($status); + $queryParams['status'] = ObjectSerializer::toQueryValue($status); } @@ -533,10 +524,10 @@ public function findPetsByTagsWithHttpInfo($tags) // query params if (is_array($tags)) { - $tags = $this->serializer->serializeCollection($tags, 'csv', true); + $tags = ObjectSerializer::serializeCollection($tags, 'csv', true); } if ($tags !== null) { - $queryParams['tags'] = $this->serializer->toQueryValue($tags); + $queryParams['tags'] = ObjectSerializer::toQueryValue($tags); } @@ -680,7 +671,7 @@ public function getPetByIdWithHttpInfo($pet_id) // path params if ($pet_id !== null) { - $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::toPathValue($pet_id), $resourcePath); } @@ -952,16 +943,16 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n // path params if ($pet_id !== null) { - $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::toPathValue($pet_id), $resourcePath); } // form params if ($name !== null) { - $formParams['name'] = $this->serializer->toFormValue($name); + $formParams['name'] = ObjectSerializer::toFormValue($name); } // form params if ($status !== null) { - $formParams['status'] = $this->serializer->toFormValue($status); + $formParams['status'] = ObjectSerializer::toFormValue($status); } // for model (json/xml) @@ -1089,17 +1080,17 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi // path params if ($pet_id !== null) { - $resourcePath = str_replace('{' . 'petId' . '}', $this->serializer->toPathValue($pet_id), $resourcePath); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::toPathValue($pet_id), $resourcePath); } // form params if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = $this->serializer->toFormValue($additional_metadata); + $formParams['additionalMetadata'] = ObjectSerializer::toFormValue($additional_metadata); } // form params if ($file !== null) { $multipart = true; - $formParams['file'] = \GuzzleHttp\Psr7\try_fopen($this->serializer->toFormValue($file), 'rb'); + $formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb'); } // for model (json/xml) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 2850dcf9236..709b0e942fe 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -30,7 +30,6 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use GuzzleHttp\Psr7\Uri; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -53,11 +52,6 @@ class StoreApi */ protected $client; - /** - * @var ObjectSerializer - */ - protected $serializer; - /** * @var Configuration */ @@ -66,23 +60,20 @@ class StoreApi /** * @param HttpClient $client * @param HeaderSelector $selector - * @param ObjectSerializer $serializer * @param Configuration $config */ public function __construct( HttpClient $client, Configuration $config = null, - HeaderSelector $selector = null, - ObjectSerializer $serializer = null + HeaderSelector $selector = null ) { $this->client = $client; - $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); $this->config = $config ?: new Configuration(); } /** - * @return Config + * @return Configuration */ public function getConfig() { @@ -132,7 +123,7 @@ public function deleteOrderWithHttpInfo($order_id) // path params if ($order_id !== null) { - $resourcePath = str_replace('{' . 'order_id' . '}', $this->serializer->toPathValue($order_id), $resourcePath); + $resourcePath = str_replace('{' . 'order_id' . '}', ObjectSerializer::toPathValue($order_id), $resourcePath); } @@ -394,7 +385,7 @@ public function getOrderByIdWithHttpInfo($order_id) // path params if ($order_id !== null) { - $resourcePath = str_replace('{' . 'order_id' . '}', $this->serializer->toPathValue($order_id), $resourcePath); + $resourcePath = str_replace('{' . 'order_id' . '}', ObjectSerializer::toPathValue($order_id), $resourcePath); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index d3fa892c9e5..93c8cbcd95f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -30,7 +30,6 @@ use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use GuzzleHttp\Psr7\Uri; use Http\Client\Exception\NetworkException; use Http\Client\HttpClient; use Swagger\Client\ApiException; @@ -53,11 +52,6 @@ class UserApi */ protected $client; - /** - * @var ObjectSerializer - */ - protected $serializer; - /** * @var Configuration */ @@ -66,23 +60,20 @@ class UserApi /** * @param HttpClient $client * @param HeaderSelector $selector - * @param ObjectSerializer $serializer * @param Configuration $config */ public function __construct( HttpClient $client, Configuration $config = null, - HeaderSelector $selector = null, - ObjectSerializer $serializer = null + HeaderSelector $selector = null ) { $this->client = $client; - $this->serializer = $serializer ?: new ObjectSerializer(); $this->headerSelector = $selector ?: new HeaderSelector(); $this->config = $config ?: new Configuration(); } /** - * @return Config + * @return Configuration */ public function getConfig() { @@ -495,7 +486,7 @@ public function deleteUserWithHttpInfo($username) // path params if ($username !== null) { - $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); + $resourcePath = str_replace('{' . 'username' . '}', ObjectSerializer::toPathValue($username), $resourcePath); } @@ -616,7 +607,7 @@ public function getUserByNameWithHttpInfo($username) // path params if ($username !== null) { - $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); + $resourcePath = str_replace('{' . 'username' . '}', ObjectSerializer::toPathValue($username), $resourcePath); } @@ -760,11 +751,11 @@ public function loginUserWithHttpInfo($username, $password) // query params if ($username !== null) { - $queryParams['username'] = $this->serializer->toQueryValue($username); + $queryParams['username'] = ObjectSerializer::toQueryValue($username); } // query params if ($password !== null) { - $queryParams['password'] = $this->serializer->toQueryValue($password); + $queryParams['password'] = ObjectSerializer::toQueryValue($password); } @@ -1019,7 +1010,7 @@ public function updateUserWithHttpInfo($username, $body) // path params if ($username !== null) { - $resourcePath = str_replace('{' . 'username' . '}', $this->serializer->toPathValue($username), $resourcePath); + $resourcePath = str_replace('{' . 'username' . '}', ObjectSerializer::toPathValue($username), $resourcePath); } // body params diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index a9ef28e79f0..f9313e26780 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -85,7 +85,7 @@ public static function sanitizeForSerialization($data) * * @return string the sanitized filename */ - public function sanitizeFilename($filename) + public static function sanitizeFilename($filename) { if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { return $match[1]; @@ -102,9 +102,9 @@ public function sanitizeFilename($filename) * * @return string the serialized object */ - public function toPathValue($value) + public static function toPathValue($value) { - return rawurlencode($this->toString($value)); + return rawurlencode(self::toString($value)); } /** @@ -117,12 +117,12 @@ public function toPathValue($value) * * @return string the serialized object */ - public function toQueryValue($object) + public static function toQueryValue($object) { if (is_array($object)) { return implode(',', $object); } else { - return $this->toString($object); + return self::toString($object); } } @@ -135,9 +135,9 @@ public function toQueryValue($object) * * @return string the header string */ - public function toHeaderValue($value) + public static function toHeaderValue($value) { - return $this->toString($value); + return self::toString($value); } /** @@ -149,12 +149,12 @@ public function toHeaderValue($value) * * @return string the form string */ - public function toFormValue($value) + public static function toFormValue($value) { if ($value instanceof \SplFileObject) { return $value->getRealPath(); } else { - return $this->toString($value); + return self::toString($value); } } @@ -167,7 +167,7 @@ public function toFormValue($value) * * @return string the header string */ - public function toString($value) + public static function toString($value) { if ($value instanceof \DateTime) { // datetime in ISO8601 format return $value->format(\DateTime::ATOM); @@ -186,7 +186,7 @@ public function toString($value) * * @return string */ - public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) + public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { // http_build_query() almost does the job for us. We just From 4355ec901415c07c87e5a8465ca51f67d6afb4be Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 24 Mar 2017 18:03:34 +0000 Subject: [PATCH 29/37] updated test.php, replaced autoload.php with composer's autoloader --- .../codegen/languages/PhpClientCodegen.java | 1 - .../src/main/resources/php/README.mustache | 2 +- .../src/main/resources/php/autoload.mustache | 44 ------------------- .../php/SwaggerClient-php/README.md | 2 +- .../petstore/php/SwaggerClient-php/README.md | 2 +- samples/client/petstore/php/test.php | 31 ++++++------- 6 files changed, 19 insertions(+), 63 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/php/autoload.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index b834271fb9a..8020dd5fada 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -306,7 +306,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); supportingFiles.add(new SupportingFile("HeaderSelector.mustache", toPackagePath(invokerPackage, srcBasePath), "HeaderSelector.php")); supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); - supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); supportingFiles.add(new SupportingFile("README.mustache", getPackagePath(), "README.md")); supportingFiles.add(new SupportingFile("phpunit.xml.mustache", getPackagePath(), "phpunit.xml.dist")); supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index ab0da1711f2..e6459091e67 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -47,7 +47,7 @@ Then run `composer install` Download the files and include `autoload.php`: ```php - require_once('/path/to/{{packagePath}}/autoload.php'); + require_once('/path/to/{{packagePath}}/vendor/autoload.php'); ``` ## Tests diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache deleted file mode 100644 index 28ce32ae50a..00000000000 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ /dev/null @@ -1,44 +0,0 @@ -partial_header}} -/** - * An example of a project-specific implementation. - * - * After registering this autoload function with SPL, the following line - * would cause the function to attempt to load the \{{invokerPackage}}\Baz\Qux class - * from /path/to/project/{{srcBasePath}}/Baz/Qux.php: - * - * new \{{invokerPackage}}\Baz\Qux; - * - * @param string $class The fully-qualified class name. - * - * @return void - */ -spl_autoload_register(function ($class) { - - // project-specific namespace prefix - $prefix = '{{escapedInvokerPackage}}\\'; - - // base directory for the namespace prefix - $base_dir = __DIR__ . '/{{srcBasePath}}/'; - - // does the class use the namespace prefix? - $len = strlen($prefix); - if (strncmp($prefix, $class, $len) !== 0) { - // no, move to the next registered autoloader - return; - } - - // get the relative class name - $relative_class = substr($class, $len); - - // replace the namespace prefix with the base directory, replace namespace - // separators with directory separators in the relative class name, append - // with .php - $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php'; - - // if the file exists, require it - if (file_exists($file)) { - require $file; - } -}); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index 975d73429f4..f94cc5ffb2b 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -36,7 +36,7 @@ Then run `composer install` Download the files and include `autoload.php`: ```php - require_once('/path/to/SwaggerClient-php/autoload.php'); + require_once('/path/to/SwaggerClient-php/vendor/autoload.php'); ``` ## Tests diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 1b2dc553326..ce04b16d530 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -36,7 +36,7 @@ Then run `composer install` Download the files and include `autoload.php`: ```php - require_once('/path/to/SwaggerClient-php/autoload.php'); + require_once('/path/to/SwaggerClient-php/vendor/autoload.php'); ``` ## Tests diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 5c27e3d7ae9..ba7da2c5757 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -1,5 +1,5 @@ getConfig()->addDefaultHeader("test1", "value1"); //$pet_api = new Swagger\Client\PetAPI($api_client); - $pet_api = new Swagger\Client\Api\PetApi(); - $pet_api->getApiClient()->getConfig()->setTempFolderPath('/var/tmp/php/'); + $config = new \Swagger\Client\Configuration(); + $petApi = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client(), $config); + $config->setTempFolderPath('/var/tmp/php/'); // test default header //$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); // return Pet (model) - $response = $pet_api->getPetById($petId); + $response = $petApi->getPetById($petId); // to test __toString() print ($response); // add pet (post json) - $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test"); + $newPetId = 10005; + $newPet = new Swagger\Client\Model\Pet; + $newPet->setId($newPetId); + $newPet->setName("PHP Unit Test"); // new tag - $tag= new Swagger\Client\Model\Tag; - $tag->setId($new_pet_id); // use the same id as pet + $tag = new Swagger\Client\Model\Tag; + $tag->setId($newPetId); // use the same id as pet //$tag->name = "test php tag"; // new category $category = new Swagger\Client\Model\Category; $category->setId(10005); // use the same id as pet //$category->name = "test php category"; - $new_pet->setTags(array($tag)); - $new_pet->setCategory($category); + $newPet->setTags(array($tag)); + $newPet->setCategory($category); - $pet_api = new Swagger\Client\Api\PetApi(); + $petApi = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client(), $config); // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); + $add_response = $petApi->addPet($newPet); // test upload file (should return exception) - $upload_response = $pet_api->uploadFile($petId, "test meta", NULL); + $upload_response = $petApi->uploadFile($petId, "test meta", NULL); } catch (Swagger\Client\ApiException $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; From aef17cf89960d5478bc6adb46d18b4f36645de0f Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Fri, 24 Mar 2017 18:21:36 +0000 Subject: [PATCH 30/37] updated api doc template --- .../src/main/resources/php/api_doc.mustache | 2 +- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 2 +- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 6 +++--- .../php/SwaggerClient-php/docs/Api/PetApi.md | 16 ++++++++-------- .../php/SwaggerClient-php/docs/Api/StoreApi.md | 8 ++++---- .../php/SwaggerClient-php/docs/Api/UserApi.md | 16 ++++++++-------- 6 files changed, 25 insertions(+), 25 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache index 75ec5f8acd8..6d0ad8ebbb4 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_doc.mustache @@ -33,7 +33,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} -$api_instance = new {{invokerPackage}}\Api\{{classname}}(); +$api_instance = new {{invokerPackage}}\Api\{{classname}}(new \Http\Adapter\Guzzle6\Client()); {{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md index 5aa5737f677..445abaf0855 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -17,7 +17,7 @@ To test code injection *_/ ' \" =end -- \\r\\n \\n \\r setUsername('YOUR_USERNAME'); Swagger\Client\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); -$api_instance = new Swagger\Client\Api\FakeApi(); +$api_instance = new Swagger\Client\Api\FakeApi(new \Http\Adapter\Guzzle6\Client()); $number = 3.4; // float | None $double = 1.2; // double | None $pattern_without_delimiter = "pattern_without_delimiter_example"; // string | None @@ -140,7 +140,7 @@ To test enum parameters setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store try { @@ -76,7 +76,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $pet_id = 789; // int | Pet id to delete $api_key = "api_key_example"; // string | @@ -125,7 +125,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $status = array("status_example"); // string[] | Status values that need to be considered for filter try { @@ -173,7 +173,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $tags = array("tags_example"); // string[] | Tags to filter by try { @@ -223,7 +223,7 @@ Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'Y // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $pet_id = 789; // int | ID of pet to return try { @@ -271,7 +271,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store try { @@ -318,7 +318,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $pet_id = 789; // int | ID of pet that needs to be updated $name = "name_example"; // string | Updated name of the pet $status = "status_example"; // string | Updated status of the pet @@ -369,7 +369,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); // Configure OAuth2 access token for authorization: petstore_auth Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); -$api_instance = new Swagger\Client\Api\PetApi(); +$api_instance = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client()); $pet_id = 789; // int | ID of pet to update $additional_metadata = "additional_metadata_example"; // string | Additional data to pass to server $file = "/path/to/file.txt"; // \SplFileObject | file to upload diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md index d959d6141d0..2f90e4165ec 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/StoreApi.md @@ -22,7 +22,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non setApiKey('api_key', 'Y // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); -$api_instance = new Swagger\Client\Api\StoreApi(); +$api_instance = new Swagger\Client\Api\StoreApi(new \Http\Adapter\Guzzle6\Client()); try { $result = $api_instance->getInventory(); @@ -112,7 +112,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge logoutUser(); @@ -334,7 +334,7 @@ This can only be done by the logged in user. Date: Fri, 24 Mar 2017 19:02:51 +0000 Subject: [PATCH 31/37] removed classes used for testing; regenerated Fake_classname_tags123Api --- .../php/SwaggerClient-php/lib/AuthConfig.php | 222 ----------- .../docs/Api/Fake_classname_tags123Api.md | 2 +- .../lib/Api/Fake_classname_tags123Api.php | 167 +++++--- .../php/SwaggerClient-php/lib/ApiClient.php | 367 ------------------ .../lib/Model/DefaultError.php | 256 ------------ .../php/SwaggerClient-php/lib/Model/Error.php | 256 ------------ 6 files changed, 112 insertions(+), 1158 deletions(-) delete mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php deleted file mode 100644 index 2880ade430c..00000000000 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/AuthConfig.php +++ /dev/null @@ -1,222 +0,0 @@ -apiKeys[$apiKeyIdentifier] = $key; - return $this; - } - - /** - * Gets API key - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return string API key or token - */ - public function getApiKey($apiKeyIdentifier) - { - return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; - } - - /** - * Sets the prefix for API key (e.g. Bearer) - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer - * - * @return $this - */ - public function setApiKeyPrefix($apiKeyIdentifier, $prefix) - { - $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; - return $this; - } - - /** - * Gets API key prefix - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return string - */ - public function getApiKeyPrefix($apiKeyIdentifier) - { - return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; - } - - /** - * Sets the access token for OAuth - * - * @param string $accessToken Token for OAuth - * - * @return $this - */ - public function setAccessToken($accessToken) - { - $this->accessToken = $accessToken; - return $this; - } - - /** - * Gets the access token for OAuth - * - * @return string Access token for OAuth - */ - public function getAccessToken() - { - return $this->accessToken; - } - - /** - * Sets the username for HTTP basic authentication - * - * @param string $username Username for HTTP basic authentication - * - * @return $this - */ - public function setUsername($username) - { - $this->username = $username; - return $this; - } - - /** - * Gets the username for HTTP basic authentication - * - * @return string Username for HTTP basic authentication - */ - public function getUsername() - { - return $this->username; - } - - /** - * Sets the password for HTTP basic authentication - * - * @param string $password Password for HTTP basic authentication - * - * @return $this - */ - public function setPassword($password) - { - $this->password = $password; - return $this; - } - - /** - * Gets the password for HTTP basic authentication - * - * @return string Password for HTTP basic authentication - */ - public function getPassword() - { - return $this->password; - } - - /** - * Get API key (with prefix if set) - * - * @param string $apiKeyIdentifier name of apikey - * - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKeyIdentifier) - { - $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); - $apiKey = $this->getApiKey($apiKeyIdentifier); - - if ($apiKey === null) { - return null; - } - - if ($prefix === null) { - $keyWithPrefix = $apiKey; - } else { - $keyWithPrefix = $prefix . ' ' . $apiKey; - } - - return $keyWithPrefix; - } -} - diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md index da2e15359f2..6fe5bb8975b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md @@ -17,7 +17,7 @@ To test class name in snake case apiClient = $apiClient; - } + protected $config; /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @param HttpClient $client + * @param HeaderSelector $selector + * @param Configuration $config */ - public function getApiClient() - { - return $this->apiClient; + public function __construct( + HttpClient $client, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client; + $this->headerSelector = $selector ?: new HeaderSelector(); + $this->config = $config ?: new Configuration(); } /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return Fake_classname_tags123Api + * @return Configuration */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) + public function getConfig() { - $this->apiClient = $apiClient; - return $this; + return $this->config; } /** @@ -94,6 +87,7 @@ public function setApiClient(\Swagger\Client\ApiClient $apiClient) * * @param \Swagger\Client\Model\Client $body client model (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return \Swagger\Client\Model\Client */ public function testClassname($body) @@ -109,6 +103,7 @@ public function testClassname($body) * * @param \Swagger\Client\Model\Client $body client model (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ public function testClassnameWithHttpInfo($body) @@ -117,17 +112,16 @@ public function testClassnameWithHttpInfo($body) if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling testClassname'); } - // parse inputs - $resourcePath = "/fake_classname_test"; - $httpBody = ''; + + $resourcePath = '/fake_classname_test'; + $formParams = []; $queryParams = []; $headerParams = []; - $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); + $httpBody = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\Client'; + + // body params $_tempBody = null; @@ -138,30 +132,91 @@ public function testClassnameWithHttpInfo($body) // for model (json/xml) if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { - $httpBody = $formParams; // for HTTP post (form) + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValue + ]; + } + $httpBody = new MultipartStream($multipartContents); // for HTTP post (form) + + } else { + $httpBody = \GuzzleHttp\Psr7\build_query($formParams); // for HTTP post (form) + } } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PATCH', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Client', - '/fake_classname_test' + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['application/json'] ); + } + + + $query = \GuzzleHttp\Psr7\build_query($queryParams); + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + $headers = array_merge( + $this->config->getDefaultHeaders(), + $headerParams, + $headers + ); + + $request = new Request( + 'PATCH', + $url, + $headers, + $httpBody + ); + + try { + try { + $response = $this->client->sendRequest($request); + } catch (NetworkException $e) { + throw new ApiException($e->getMessage(), 0); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + $responseBody = $response->getBody(); + if ($returnType === '\SplFileObject') { + $content = $responseBody; //stream goes to serializer + } else { + $content = $responseBody->getContents(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Client', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Client', $e->getResponseHeaders()); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '\Swagger\Client\Model\Client', $e->getResponseHeaders()); $e->setResponseObject($data); break; } - throw $e; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php deleted file mode 100644 index b8add9f133c..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ /dev/null @@ -1,367 +0,0 @@ -config = $config; - $this->serializer = new ObjectSerializer(); - } - - /** - * Get the config - * - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Get the serializer - * - * @return ObjectSerializer - */ - public function getSerializer() - { - return $this->serializer; - } - - /** - * Get API key (with prefix if set) - * - * @param string $apiKeyIdentifier name of apikey - * - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKeyIdentifier) - { - $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); - $apiKey = $this->config->getApiKey($apiKeyIdentifier); - - if (!isset($apiKey)) { - return null; - } - - if (isset($prefix)) { - $keyWithPrefix = $prefix." ".$apiKey; - } else { - $keyWithPrefix = $apiKey; - } - - return $keyWithPrefix; - } - - /** - * Make the HTTP call (Sync) - * - * @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 - * @param string $responseType expected response type of the endpoint - * @param string $endpointPath path to method endpoint before expanding parameters - * - * @throws \Swagger\Client\ApiException on a non 2xx response - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) - { - $headers = []; - - // construct the http header - $headerParams = array_merge( - (array)$this->config->getDefaultHeaders(), - (array)$headerParams - ); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { - $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model - $postData = json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($postData)); - } - - $url = $this->config->getHost() . $resourcePath; - - $curl = curl_init(); - // set timeout, if needed - if ($this->config->getCurlTimeout() !== 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); - } - // set connect timeout, if needed - if ($this->config->getCurlConnectTimeout() != 0) { - curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); - } - - // return the result on success, rather than just true - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - // disable SSL verification, if needed - if ($this->config->getSSLVerification() === false) { - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); - } - - if ($this->config->getCurlProxyHost()) { - curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); - } - - if ($this->config->getCurlProxyPort()) { - curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); - } - - if ($this->config->getCurlProxyType()) { - curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); - } - - if ($this->config->getCurlProxyUser()) { - curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); - } - - 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); - } elseif ($method === self::$HEAD) { - curl_setopt($curl, CURLOPT_NOBODY, true); - } elseif ($method === self::$OPTIONS) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PATCH) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method === self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($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->config->getUserAgent()); - - // debugging for curl - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~".PHP_EOL.print_r($postData, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), '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 = $this->httpParseHeaders(substr($response, 0, $http_header_size)); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); - - // debug HTTP response body - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~".PHP_EOL.print_r($http_body, true).PHP_EOL."~END~".PHP_EOL, 3, $this->config->getDebugFile()); - } - - // Handle the response - if ($response_info['http_code'] === 0) { - $curl_error_message = curl_error($curl); - - // curl_exec can sometimes fail but still return a blank message from curl_error(). - if (!empty($curl_error_message)) { - $error_message = "API call to $url failed: $curl_error_message"; - } else { - $error_message = "API call to $url failed, but for an unknown reason. " . - "This could happen if you are disconnected from the network."; - } - - $exception = new ApiException($error_message, 0, null, null); - $exception->setResponseObject($response_info); - throw $exception; - } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { - // return raw body if response is a file - if ($responseType === '\SplFileObject' || $responseType === 'string') { - return [$http_body, $response_info['http_code'], $http_header]; - } - - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - } else { - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - - throw new ApiException( - "[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], - $http_header, - $data - ); - } - return [$data, $response_info['http_code'], $http_header]; - } - - /** - * Return the header 'Accept' based on an array of Accept provided - * - * @param string[] $accept Array of header - * - * @return string Accept (e.g. application/json) - */ - public 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 string[] $content_type Array fo content-type - * - * @return string Content-Type (e.g. application/json) - */ - public 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); - } - } - - /** - * Return an array of HTTP response headers - * - * @param string $raw_headers A string of raw HTTP response headers - * - * @return string[] Array of HTTP response heaers - */ - protected function httpParseHeaders($raw_headers) - { - // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 - $headers = []; - $key = ''; - - foreach (explode("\n", $raw_headers) as $h) { - $h = explode(':', $h, 2); - - if (isset($h[1])) { - if (!isset($headers[$h[0]])) { - $headers[$h[0]] = trim($h[1]); - } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); - } else { - $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); - } - - $key = $h[0]; - } else { - if (substr($h[0], 0, 1) === "\t") { - $headers[$key] .= "\r\n\t".trim($h[0]); - } elseif (!$key) { - $headers[0] = trim($h[0]); - } - trim($h[0]); - } - } - - return $headers; - } -} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php deleted file mode 100644 index dfe1553ce38..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/DefaultError.php +++ /dev/null @@ -1,256 +0,0 @@ - 'string', - 'code' => 'float' - ]; - - public static function swaggerTypes() - { - return self::$swaggerTypes; - } - - /** - * Array of attributes where the key is the local name, and the value is the original name - * @var string[] - */ - protected static $attributeMap = [ - 'error' => 'error', - 'code' => 'code' - ]; - - - /** - * Array of attributes to setter functions (for deserialization of responses) - * @var string[] - */ - protected static $setters = [ - 'error' => 'setError', - 'code' => 'setCode' - ]; - - - /** - * Array of attributes to getter functions (for serialization of requests) - * @var string[] - */ - protected static $getters = [ - 'error' => 'getError', - 'code' => 'getCode' - ]; - - public static function attributeMap() - { - return self::$attributeMap; - } - - public static function setters() - { - return self::$setters; - } - - public static function getters() - { - return self::$getters; - } - - - - - - /** - * Associative array for storing property values - * @var mixed[] - */ - protected $container = []; - - /** - * Constructor - * @param mixed[] $data Associated array of property values initializing the model - */ - public function __construct(array $data = null) - { - $this->container['error'] = isset($data['error']) ? $data['error'] : null; - $this->container['code'] = isset($data['code']) ? $data['code'] : null; - } - - /** - * show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalid_properties = []; - - return $invalid_properties; - } - - /** - * validate all the properties in the model - * return true if all passed - * - * @return bool True if all properties are valid - */ - public function valid() - { - - return true; - } - - - /** - * Gets error - * @return string - */ - public function getError() - { - return $this->container['error']; - } - - /** - * Sets error - * @param string $error - * @return $this - */ - public function setError($error) - { - $this->container['error'] = $error; - - return $this; - } - - /** - * Gets code - * @return float - */ - public function getCode() - { - return $this->container['code']; - } - - /** - * Sets code - * @param float $code - * @return $this - */ - public function setCode($code) - { - $this->container['code'] = $code; - - return $this; - } - /** - * Returns true if offset exists. False otherwise. - * @param integer $offset Offset - * @return boolean - */ - public function offsetExists($offset) - { - return isset($this->container[$offset]); - } - - /** - * Gets offset. - * @param integer $offset Offset - * @return mixed - */ - public function offsetGet($offset) - { - return isset($this->container[$offset]) ? $this->container[$offset] : null; - } - - /** - * Sets value based on offset. - * @param integer $offset Offset - * @param mixed $value Value to be set - * @return void - */ - public function offsetSet($offset, $value) - { - if (is_null($offset)) { - $this->container[] = $value; - } else { - $this->container[$offset] = $value; - } - } - - /** - * Unsets offset. - * @param integer $offset Offset - * @return void - */ - public function offsetUnset($offset) - { - unset($this->container[$offset]); - } - - /** - * Gets the string presentation of the object - * @return string - */ - public function __toString() - { - if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } - - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); - } -} - - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php deleted file mode 100644 index 243ee31c101..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Error.php +++ /dev/null @@ -1,256 +0,0 @@ - 'string', - 'code' => 'float' - ]; - - public static function swaggerTypes() - { - return self::$swaggerTypes; - } - - /** - * Array of attributes where the key is the local name, and the value is the original name - * @var string[] - */ - protected static $attributeMap = [ - 'error' => 'error', - 'code' => 'code' - ]; - - - /** - * Array of attributes to setter functions (for deserialization of responses) - * @var string[] - */ - protected static $setters = [ - 'error' => 'setError', - 'code' => 'setCode' - ]; - - - /** - * Array of attributes to getter functions (for serialization of requests) - * @var string[] - */ - protected static $getters = [ - 'error' => 'getError', - 'code' => 'getCode' - ]; - - public static function attributeMap() - { - return self::$attributeMap; - } - - public static function setters() - { - return self::$setters; - } - - public static function getters() - { - return self::$getters; - } - - - - - - /** - * Associative array for storing property values - * @var mixed[] - */ - protected $container = []; - - /** - * Constructor - * @param mixed[] $data Associated array of property values initializing the model - */ - public function __construct(array $data = null) - { - $this->container['error'] = isset($data['error']) ? $data['error'] : null; - $this->container['code'] = isset($data['code']) ? $data['code'] : null; - } - - /** - * show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalid_properties = []; - - return $invalid_properties; - } - - /** - * validate all the properties in the model - * return true if all passed - * - * @return bool True if all properties are valid - */ - public function valid() - { - - return true; - } - - - /** - * Gets error - * @return string - */ - public function getError() - { - return $this->container['error']; - } - - /** - * Sets error - * @param string $error - * @return $this - */ - public function setError($error) - { - $this->container['error'] = $error; - - return $this; - } - - /** - * Gets code - * @return float - */ - public function getCode() - { - return $this->container['code']; - } - - /** - * Sets code - * @param float $code - * @return $this - */ - public function setCode($code) - { - $this->container['code'] = $code; - - return $this; - } - /** - * Returns true if offset exists. False otherwise. - * @param integer $offset Offset - * @return boolean - */ - public function offsetExists($offset) - { - return isset($this->container[$offset]); - } - - /** - * Gets offset. - * @param integer $offset Offset - * @return mixed - */ - public function offsetGet($offset) - { - return isset($this->container[$offset]) ? $this->container[$offset] : null; - } - - /** - * Sets value based on offset. - * @param integer $offset Offset - * @param mixed $value Value to be set - * @return void - */ - public function offsetSet($offset, $value) - { - if (is_null($offset)) { - $this->container[] = $value; - } else { - $this->container[$offset] = $value; - } - } - - /** - * Unsets offset. - * @param integer $offset Offset - * @return void - */ - public function offsetUnset($offset) - { - unset($this->container[$offset]); - } - - /** - * Gets the string presentation of the object - * @return string - */ - public function __toString() - { - if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } - - return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); - } -} - - From f8fe1d9c780b125bb3fa873baf68c60e7aaf3fb6 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 30 Mar 2017 16:58:56 +0100 Subject: [PATCH 32/37] replaced httplug with guzzle6 --- .../src/main/resources/php/api.mustache | 28 +++-- .../src/main/resources/php/composer.mustache | 7 +- .../php/SwaggerClient-php/composer.json | 7 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 28 +++-- .../php/SwaggerClient-php/composer.json | 7 +- .../docs/Api/Fake_classname_tags123Api.md | 2 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 50 ++++++--- .../lib/Api/Fake_classname_tags123Api.php | 28 +++-- .../php/SwaggerClient-php/lib/Api/PetApi.php | 105 ++++++++++++------ .../SwaggerClient-php/lib/Api/StoreApi.php | 61 ++++++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 105 ++++++++++++------ .../SwaggerClient-php/lib/Configuration.php | 2 +- .../SwaggerClient-php/tests/ExceptionTest.php | 4 +- .../tests/FakeHttpClient.php | 57 +++++++--- .../SwaggerClient-php/tests/PetApiTest.php | 3 +- .../SwaggerClient-php/tests/StoreApiTest.php | 2 +- .../SwaggerClient-php/tests/UserApiTest.php | 2 +- 17 files changed, 323 insertions(+), 175 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 326db84b5c3..181faa85f3d 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -18,10 +18,11 @@ namespace {{apiPackage}}; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use Http\Client\Exception\NetworkException; -use Http\Client\HttpClient; use {{invokerPackage}}\ApiException; use {{invokerPackage}}\Configuration; use {{invokerPackage}}\HeaderSelector; @@ -38,7 +39,7 @@ use {{invokerPackage}}\ObjectSerializer; {{#operations}}class {{classname}} { /** - * @var HttpClient + * @var ClientInterface */ protected $client; @@ -48,18 +49,18 @@ use {{invokerPackage}}\ObjectSerializer; protected $config; /** - * @param HttpClient $client - * @param HeaderSelector $selector + * @param ClientInterface $client * @param Configuration $config + * @param HeaderSelector $selector */ public function __construct( - HttpClient $client, + ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { - $this->client = $client; - $this->headerSelector = $selector ?: new HeaderSelector(); + $this->client = $client ?: new Client(); $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -289,10 +290,15 @@ use {{invokerPackage}}\ObjectSerializer; ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index c49cc1dcbe9..0a16941cbdc 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -23,15 +23,12 @@ "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", - "php-http/httplug": "^1.1", - "guzzlehttp/psr7": "^1.4" + "guzzlehttp/guzzle": "^6.2" }, "require-dev": { "phpunit/phpunit": "^5.0", "squizlabs/php_codesniffer": "~2.6", - "friendsofphp/php-cs-fixer": "~1.12", - "php-http/guzzle6-adapter": "^1.1", - "php-http/curl-client": "^1.7" + "friendsofphp/php-cs-fixer": "~1.12" }, "autoload": { "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json index bf27b85e1e8..0e1f59a1550 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json @@ -20,15 +20,12 @@ "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", - "php-http/httplug": "^1.1", - "guzzlehttp/psr7": "^1.4" + "guzzlehttp/guzzle": "^6.2" }, "require-dev": { "phpunit/phpunit": "^5.0", "squizlabs/php_codesniffer": "~2.6", - "friendsofphp/php-cs-fixer": "~1.12", - "php-http/guzzle6-adapter": "^1.1", - "php-http/curl-client": "^1.7" + "friendsofphp/php-cs-fixer": "~1.12" }, "autoload": { "psr-4": { "Swagger\\Client\\" : "lib/" } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index b10f5d1fe5e..666580abc98 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -28,10 +28,11 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use Http\Client\Exception\NetworkException; -use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -48,7 +49,7 @@ class FakeApi { /** - * @var HttpClient + * @var ClientInterface */ protected $client; @@ -58,18 +59,18 @@ class FakeApi protected $config; /** - * @param HttpClient $client - * @param HeaderSelector $selector + * @param ClientInterface $client * @param Configuration $config + * @param HeaderSelector $selector */ public function __construct( - HttpClient $client, + ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { - $this->client = $client; - $this->headerSelector = $selector ?: new HeaderSelector(); + $this->client = $client ?: new Client(); $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -171,10 +172,15 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index bf27b85e1e8..0e1f59a1550 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -20,15 +20,12 @@ "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", - "php-http/httplug": "^1.1", - "guzzlehttp/psr7": "^1.4" + "guzzlehttp/guzzle": "^6.2" }, "require-dev": { "phpunit/phpunit": "^5.0", "squizlabs/php_codesniffer": "~2.6", - "friendsofphp/php-cs-fixer": "~1.12", - "php-http/guzzle6-adapter": "^1.1", - "php-http/curl-client": "^1.7" + "friendsofphp/php-cs-fixer": "~1.12" }, "autoload": { "psr-4": { "Swagger\\Client\\" : "lib/" } diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md index 6fe5bb8975b..868fb1e11c2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/Fake_classname_tags123Api.md @@ -1,6 +1,6 @@ # Swagger\Client\Fake_classname_tags123Api -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to *http://petstore.swagger.io:80/v2* Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 08c6426b831..6ce8c0d8e55 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -28,10 +28,11 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use Http\Client\Exception\NetworkException; -use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -48,7 +49,7 @@ class FakeApi { /** - * @var HttpClient + * @var ClientInterface */ protected $client; @@ -58,18 +59,18 @@ class FakeApi protected $config; /** - * @param HttpClient $client - * @param HeaderSelector $selector + * @param ClientInterface $client * @param Configuration $config + * @param HeaderSelector $selector */ public function __construct( - HttpClient $client, + ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { - $this->client = $client; - $this->headerSelector = $selector ?: new HeaderSelector(); + $this->client = $client ?: new Client(); $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -177,10 +178,15 @@ public function testClientModelWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -456,10 +462,15 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -620,10 +631,15 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php index d748f98ef8a..dfb03d24cb9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php @@ -28,10 +28,11 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use Http\Client\Exception\NetworkException; -use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -48,7 +49,7 @@ class Fake_classname_tags123Api { /** - * @var HttpClient + * @var ClientInterface */ protected $client; @@ -58,18 +59,18 @@ class Fake_classname_tags123Api protected $config; /** - * @param HttpClient $client - * @param HeaderSelector $selector + * @param ClientInterface $client * @param Configuration $config + * @param HeaderSelector $selector */ public function __construct( - HttpClient $client, + ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { - $this->client = $client; - $this->headerSelector = $selector ?: new HeaderSelector(); + $this->client = $client ?: new Client(); $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -177,10 +178,15 @@ public function testClassnameWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index ad608c547b6..b1118a5b8fd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -28,10 +28,11 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use Http\Client\Exception\NetworkException; -use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -48,7 +49,7 @@ class PetApi { /** - * @var HttpClient + * @var ClientInterface */ protected $client; @@ -58,18 +59,18 @@ class PetApi protected $config; /** - * @param HttpClient $client - * @param HeaderSelector $selector + * @param ClientInterface $client * @param Configuration $config + * @param HeaderSelector $selector */ public function __construct( - HttpClient $client, + ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { - $this->client = $client; - $this->headerSelector = $selector ?: new HeaderSelector(); + $this->client = $client ?: new Client(); $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -180,10 +181,15 @@ public function addPetWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -310,10 +316,15 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -438,10 +449,15 @@ public function findPetsByStatusWithHttpInfo($status) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -584,10 +600,15 @@ public function findPetsByTagsWithHttpInfo($tags) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -728,10 +749,15 @@ public function getPetByIdWithHttpInfo($pet_id) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -871,10 +897,15 @@ public function updatePetWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -1007,10 +1038,15 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -1145,10 +1181,15 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 709b0e942fe..05d8bd6afd7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -28,10 +28,11 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use Http\Client\Exception\NetworkException; -use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -48,7 +49,7 @@ class StoreApi { /** - * @var HttpClient + * @var ClientInterface */ protected $client; @@ -58,18 +59,18 @@ class StoreApi protected $config; /** - * @param HttpClient $client - * @param HeaderSelector $selector + * @param ClientInterface $client * @param Configuration $config + * @param HeaderSelector $selector */ public function __construct( - HttpClient $client, + ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { - $this->client = $client; - $this->headerSelector = $selector ?: new HeaderSelector(); + $this->client = $client ?: new Client(); $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -175,10 +176,15 @@ public function deleteOrderWithHttpInfo($order_id) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -291,10 +297,15 @@ public function getInventoryWithHttpInfo() ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -437,10 +448,15 @@ public function getOrderByIdWithHttpInfo($order_id) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -577,10 +593,15 @@ public function placeOrderWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 93c8cbcd95f..00b448f4d70 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -28,10 +28,11 @@ namespace Swagger\Client\Api; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Psr7\MultipartStream; use GuzzleHttp\Psr7\Request; -use Http\Client\Exception\NetworkException; -use Http\Client\HttpClient; use Swagger\Client\ApiException; use Swagger\Client\Configuration; use Swagger\Client\HeaderSelector; @@ -48,7 +49,7 @@ class UserApi { /** - * @var HttpClient + * @var ClientInterface */ protected $client; @@ -58,18 +59,18 @@ class UserApi protected $config; /** - * @param HttpClient $client - * @param HeaderSelector $selector + * @param ClientInterface $client * @param Configuration $config + * @param HeaderSelector $selector */ public function __construct( - HttpClient $client, + ClientInterface $client = null, Configuration $config = null, HeaderSelector $selector = null ) { - $this->client = $client; - $this->headerSelector = $selector ?: new HeaderSelector(); + $this->client = $client ?: new Client(); $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** @@ -176,10 +177,15 @@ public function createUserWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -297,10 +303,15 @@ public function createUsersWithArrayInputWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -418,10 +429,15 @@ public function createUsersWithListInputWithHttpInfo($body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -538,10 +554,15 @@ public function deleteUserWithHttpInfo($username) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -659,10 +680,15 @@ public function getUserByNameWithHttpInfo($username) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -808,10 +834,15 @@ public function loginUserWithHttpInfo($username, $password) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -936,10 +967,15 @@ public function logoutUserWithHttpInfo() ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); @@ -1067,10 +1103,15 @@ public function updateUserWithHttpInfo($username, $body) ); try { + try { - $response = $this->client->sendRequest($request); - } catch (NetworkException $e) { - throw new ApiException($e->getMessage(), 0); + $response = $this->client->send($request); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null + ); } $statusCode = $response->getStatusCode(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 92b9ec0d009..368c9cac105 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -88,7 +88,7 @@ class Configuration * * @var string */ - protected $host = 'http://petstore.swagger.io/v2'; + protected $host = 'http://petstore.swagger.io:80/v2'; /** * User agent of the HTTP request, set to "PHP-Swagger" by default diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php index a7eefab0d34..b314b0625e1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php @@ -2,7 +2,7 @@ namespace Swagger\Client; -use Http\Adapter\Guzzle6\Client; +use GuzzleHttp\Client; class ExceptionTest extends \PHPUnit_Framework_TestCase { @@ -10,7 +10,7 @@ public function testNotFound() { $this->expectException(ApiException::class); $this->expectExceptionCode(404); - $this->expectExceptionMessage('[404] Error connecting to the API (http://petstore.swagger.io/INVALID_URL/store/inventory)'); + $this->expectExceptionMessage('http://petstore.swagger.io/INVALID_URL/store/inventory'); $config = new Configuration(); $config->setHost('http://petstore.swagger.io/INVALID_URL'); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php b/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php index 47f4d2bc3bb..abdfa7cf7c2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php @@ -2,34 +2,19 @@ namespace Swagger\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Psr7\Response; -use Http\Client\HttpClient; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; -class FakeHttpClient implements HttpClient +class FakeHttpClient implements ClientInterface { /** @var RequestInterface|null */ private $request; /** @var ResponseInterface|null */ private $response; - /** - * Sends a PSR-7 request. - * - * @param RequestInterface $request - * - * @return ResponseInterface - * - * @throws \Http\Client\Exception If an error happens during processing the request. - * @throws \Exception If processing the request is impossible (eg. bad configuration). - */ - public function sendRequest(RequestInterface $request) - { - $this->request = $request; - return $this->response ?: new Response(200); - } - /** * @return null|RequestInterface */ @@ -45,4 +30,40 @@ public function setResponse(ResponseInterface $response = null) { $this->response = $response; } + + /** + * Send an HTTP request. + * + * @param RequestInterface $request Request to send + * @param array $options Request options to apply to the given + * request and to the transfer. + * + * @return ResponseInterface + * @throws GuzzleException + */ + public function send(RequestInterface $request, array $options = []) + { + $this->request = $request; + return $this->response ?: new Response(200); + } + + public function sendAsync(RequestInterface $request, array $options = []) + { + throw new \RuntimeException('not implemented'); + } + + public function request($method, $uri, array $options = []) + { + throw new \RuntimeException('not implemented'); + } + + public function requestAsync($method, $uri, array $options = []) + { + throw new \RuntimeException('not implemented'); + } + + public function getConfig($option = null) + { + throw new \RuntimeException('not implemented'); + } } \ No newline at end of file diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 68e13feb774..33d48ff879a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -2,8 +2,7 @@ namespace Swagger\Client; -use Http\Adapter\Guzzle6\Client; -use Swagger\Client\Api\FakeApi; +use GuzzleHttp\Client; use Swagger\Client\Api\PetApi; use Swagger\Client\Model\ApiResponse; use Swagger\Client\Model\Pet; diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 4b492cf9d34..85055063844 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -2,7 +2,7 @@ namespace Swagger\Client; -use Http\Adapter\Guzzle6\Client; +use GuzzleHttp\Client; use Swagger\Client\Api\StoreApi; class StoreApiTest extends \PHPUnit_Framework_TestCase diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index e6539ac1338..5f3c95baddc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -2,7 +2,7 @@ namespace Swagger\Client; -use Http\Adapter\Guzzle6\Client; +use GuzzleHttp\Client; use Swagger\Client\Api\UserApi; class UserApiTest extends \PHPUnit_Framework_TestCase From 124d2f40a8475fe4e90cb6568532d127428c71d6 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 30 Mar 2017 17:04:33 +0100 Subject: [PATCH 33/37] updated required php version to 5.5 --- modules/swagger-codegen/src/main/resources/php/README.mustache | 2 +- .../swagger-codegen/src/main/resources/php/composer.mustache | 2 +- .../petstore-security-test/php/SwaggerClient-php/README.md | 2 +- .../petstore-security-test/php/SwaggerClient-php/composer.json | 2 +- samples/client/petstore/php/SwaggerClient-php/README.md | 2 +- samples/client/petstore/php/SwaggerClient-php/composer.json | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index e6459091e67..eeff364b156 100644 --- a/modules/swagger-codegen/src/main/resources/php/README.mustache +++ b/modules/swagger-codegen/src/main/resources/php/README.mustache @@ -19,7 +19,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) ## Requirements -PHP 5.4.0 and later +PHP 5.5 and later ## Installation & Usage ### Composer diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 0a16941cbdc..511ffba85b4 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -19,7 +19,7 @@ } ], "require": { - "php": ">=5.4", + "php": ">=5.5", "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index f94cc5ffb2b..3c73985e40c 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -8,7 +8,7 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git ## Requirements -PHP 5.4.0 and later +PHP 5.5 and later ## Installation & Usage ### Composer diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json index 0e1f59a1550..7b41f990b07 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json @@ -16,7 +16,7 @@ } ], "require": { - "php": ">=5.4", + "php": ">=5.5", "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index ce04b16d530..d1af5fcb964 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -8,7 +8,7 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git ## Requirements -PHP 5.4.0 and later +PHP 5.5 and later ## Installation & Usage ### Composer diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index 0e1f59a1550..7b41f990b07 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -16,7 +16,7 @@ } ], "require": { - "php": ">=5.4", + "php": ">=5.5", "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", From c1f5748b1a0506ebc147c0d23dad4219c3046ab1 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 30 Mar 2017 17:05:01 +0100 Subject: [PATCH 34/37] clean up --- .../SwaggerClient-php/tests/PetApiTest.php | 20 +++---------------- .../SwaggerClient-php/tests/StoreApiTest.php | 5 +---- .../SwaggerClient-php/tests/UserApiTest.php | 12 +---------- 3 files changed, 5 insertions(+), 32 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 33d48ff879a..b6a542990c6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -2,7 +2,6 @@ namespace Swagger\Client; -use GuzzleHttp\Client; use Swagger\Client\Api\PetApi; use Swagger\Client\Model\ApiResponse; use Swagger\Client\Model\Pet; @@ -10,30 +9,19 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { - // add a new pet (id 10005) to ensure the pet object is available for all the tests /** @var PetApi */ private $api; + // add a new pet (id 10005) to ensure the pet object is available for all the tests public static function setUpBeforeClass() { // increase memory limit to avoid fatal error due to findPetByStatus // returning a lot of data ini_set('memory_limit', '256M'); - // for error reporting (need to run with php5.3 to get no warning) - //ini_set('display_errors', 1); - //error_reporting(~0); - // when running with php5.5, comment out below to skip the warning about - // using @ to handle file upload - //ini_set('display_startup_errors',1); - //ini_set('display_errors',1); - //error_reporting(-1); - // enable debugging //Configuration::$debug = true; - // skip initializing the API client as it should be automatic - //$api_client = new ApiClient('http://petstore.swagger.io/v2'); // new pet $newPetId = 10005; $newPet = new Model\Pet; @@ -53,7 +41,7 @@ public static function setUpBeforeClass() $newPet->setCategory($category); $config = new Configuration(); - $petApi = new Api\PetApi(new Client(), $config); + $petApi = new Api\PetApi(null, $config); // add a new pet (model) list(, $status) = $petApi->addPetWithHttpInfo($newPet); @@ -62,9 +50,7 @@ public static function setUpBeforeClass() public function setUp() { - $this->api = new Api\PetApi( - new Client() - ); + $this->api = new Api\PetApi(); } public function testGetPetById() diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 85055063844..f413737461c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -2,7 +2,6 @@ namespace Swagger\Client; -use GuzzleHttp\Client; use Swagger\Client\Api\StoreApi; class StoreApiTest extends \PHPUnit_Framework_TestCase @@ -12,9 +11,7 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase public function setUp() { - $this->api = new Api\StoreApi( - new Client() - ); + $this->api = new Api\StoreApi(); } public function testGetInventory() diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index 5f3c95baddc..b65078ed476 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -2,7 +2,6 @@ namespace Swagger\Client; -use GuzzleHttp\Client; use Swagger\Client\Api\UserApi; class UserApiTest extends \PHPUnit_Framework_TestCase @@ -11,18 +10,9 @@ class UserApiTest extends \PHPUnit_Framework_TestCase /** @var UserApi*/ private $api; - public static function setUpBeforeClass() - { - // for error reporting (need to run with php5.3 to get no warning) - //ini_set('display_errors', 1); - //error_reporting(~0); - } - public function setUp() { - $this->api = new Api\UserApi( - new Client() - ); + $this->api = new Api\UserApi(); } // test login use From 6ce64f98002c9d33eb889bbc8416aeff54fbebbe Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 30 Mar 2017 17:37:31 +0100 Subject: [PATCH 35/37] readded missing userAgent feature; removed default headers from Configuration --- .../main/resources/php/Configuration.mustache | 49 -------------- .../src/main/resources/php/api.mustache | 8 ++- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 8 ++- .../SwaggerClient-php/lib/Configuration.php | 49 -------------- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 24 ++++++- .../lib/Api/Fake_classname_tags123Api.php | 8 ++- .../php/SwaggerClient-php/lib/Api/PetApi.php | 64 ++++++++++++++++--- .../SwaggerClient-php/lib/Api/StoreApi.php | 32 ++++++++-- .../php/SwaggerClient-php/lib/Api/UserApi.php | 64 ++++++++++++++++--- .../SwaggerClient-php/lib/Configuration.php | 49 -------------- .../SwaggerClient-php/tests/HeadersTest.php | 34 ++-------- 11 files changed, 186 insertions(+), 203 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/Configuration.mustache b/modules/swagger-codegen/src/main/resources/php/Configuration.mustache index fe4c420fc49..cdbba93a000 100644 --- a/modules/swagger-codegen/src/main/resources/php/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Configuration.mustache @@ -66,13 +66,6 @@ class Configuration */ protected $password = ''; - /** - * The default header(s) - * - * @var array - */ - protected $defaultHeaders = []; - /** * The host * @@ -237,48 +230,6 @@ class Configuration return $this->password; } - /** - * Adds a default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * - * @throws \InvalidArgumentException - * @return $this - */ - public function addDefaultHeader($headerName, $headerValue) - { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * Gets the default header - * - * @return array An array of default header(s) - */ - public function getDefaultHeaders() - { - return $this->defaultHeaders; - } - - /** - * Deletes a default header - * - * @param string $headerName the header to delete - * - * @return $this - */ - public function deleteDefaultHeader($headerName) - { - unset($this->defaultHeaders[$headerName]); - return $this; - } - /** * Sets the host * diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 181faa85f3d..253b171cefd 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -276,8 +276,14 @@ use {{invokerPackage}}\ObjectSerializer; $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 666580abc98..3ce9e2eb5b1 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -158,8 +158,14 @@ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index 3bcefa612d6..723aedf111d 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -76,13 +76,6 @@ class Configuration */ protected $password = ''; - /** - * The default header(s) - * - * @var array - */ - protected $defaultHeaders = []; - /** * The host * @@ -247,48 +240,6 @@ public function getPassword() return $this->password; } - /** - * Adds a default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * - * @throws \InvalidArgumentException - * @return $this - */ - public function addDefaultHeader($headerName, $headerValue) - { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * Gets the default header - * - * @return array An array of default header(s) - */ - public function getDefaultHeaders() - { - return $this->defaultHeaders; - } - - /** - * Deletes a default header - * - * @param string $headerName the header to delete - * - * @return $this - */ - public function deleteDefaultHeader($headerName) - { - unset($this->defaultHeaders[$headerName]); - return $this; - } - /** * Sets the host * diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 6ce8c0d8e55..3d556753f47 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -164,8 +164,14 @@ public function testClientModelWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -448,8 +454,14 @@ public function testEndpointParametersWithHttpInfo($number, $double, $pattern_wi $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -617,8 +629,14 @@ public function testEnumParametersWithHttpInfo($enum_form_string_array = null, $ $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php index dfb03d24cb9..a587cbd023a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/Fake_classname_tags123Api.php @@ -164,8 +164,14 @@ public function testClassnameWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index b1118a5b8fd..d7085ea8419 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -167,8 +167,14 @@ public function addPetWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -302,8 +308,14 @@ public function deletePetWithHttpInfo($pet_id, $api_key = null) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -435,8 +447,14 @@ public function findPetsByStatusWithHttpInfo($status) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -586,8 +604,14 @@ public function findPetsByTagsWithHttpInfo($tags) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -735,8 +759,14 @@ public function getPetByIdWithHttpInfo($pet_id) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -883,8 +913,14 @@ public function updatePetWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -1024,8 +1060,14 @@ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = n $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -1167,8 +1209,14 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 05d8bd6afd7..775769cf427 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -162,8 +162,14 @@ public function deleteOrderWithHttpInfo($order_id) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -283,8 +289,14 @@ public function getInventoryWithHttpInfo() $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -434,8 +446,14 @@ public function getOrderByIdWithHttpInfo($order_id) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -579,8 +597,14 @@ public function placeOrderWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 00b448f4d70..cea798f65ab 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -163,8 +163,14 @@ public function createUserWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -289,8 +295,14 @@ public function createUsersWithArrayInputWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -415,8 +427,14 @@ public function createUsersWithListInputWithHttpInfo($body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -540,8 +558,14 @@ public function deleteUserWithHttpInfo($username) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -666,8 +690,14 @@ public function getUserByNameWithHttpInfo($username) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -820,8 +850,14 @@ public function loginUserWithHttpInfo($username, $password) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -953,8 +989,14 @@ public function logoutUserWithHttpInfo() $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); @@ -1089,8 +1131,14 @@ public function updateUserWithHttpInfo($username, $body) $query = \GuzzleHttp\Psr7\build_query($queryParams); $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + $headers = array_merge( - $this->config->getDefaultHeaders(), + $defaultHeaders, $headerParams, $headers ); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 368c9cac105..a65232cdf78 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -76,13 +76,6 @@ class Configuration */ protected $password = ''; - /** - * The default header(s) - * - * @var array - */ - protected $defaultHeaders = []; - /** * The host * @@ -247,48 +240,6 @@ public function getPassword() return $this->password; } - /** - * Adds a default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * - * @throws \InvalidArgumentException - * @return $this - */ - public function addDefaultHeader($headerName, $headerValue) - { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * Gets the default header - * - * @return array An array of default header(s) - */ - public function getDefaultHeaders() - { - return $this->defaultHeaders; - } - - /** - * Deletes a default header - * - * @param string $headerName the header to delete - * - * @return $this - */ - public function deleteDefaultHeader($headerName) - { - unset($this->defaultHeaders[$headerName]); - return $this; - } - /** * Sets the host * diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php index b316451a196..5431a912efe 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php @@ -2,9 +2,6 @@ namespace Swagger\Client; -use Swagger\Client\Api\FakeApi; -use Swagger\Client\Api\UserApi; - require_once __DIR__ . '/FakeHttpClient.php'; class HeadersTest extends \PHPUnit_Framework_TestCase @@ -17,27 +14,10 @@ public function setUp() $this->fakeHttpClient = new FakeHttpClient(); } - public function testDefaultHeaders() - { - $config = new Configuration(); - $config->addDefaultHeader('someHeader', 'someValue'); - $api = new Api\PetApi($this->fakeHttpClient, $config); - - $api->getPetById(3); - - $request = $this->fakeHttpClient->getLastRequest(); - $headers = $request->getHeaders(); - - $this->assertArrayHasKey('someHeader', $headers); - $this->assertEquals(['someValue'], $headers['someHeader']); - } - - public function testDefaultHeadersMayBeOverwritten() + public function testUserAgent() { $config = new Configuration(); - $config->addDefaultHeader('Accept', 'text/plain'); - $config->addDefaultHeader('Content-Type', 'text/plain'); - $config->addDefaultHeader('Something-Else', 'text/plain'); + $config->setUserAgent('value'); $api = new Api\PetApi($this->fakeHttpClient, $config); $api->getPetById(3); @@ -45,13 +25,7 @@ public function testDefaultHeadersMayBeOverwritten() $request = $this->fakeHttpClient->getLastRequest(); $headers = $request->getHeaders(); - $this->assertArrayHasKey('Accept', $headers); - $this->assertEquals(['application/json'], $headers['Accept']); - - $this->assertArrayHasKey('Content-Type', $headers); - $this->assertEquals(['application/json'], $headers['Content-Type']); - - $this->assertArrayHasKey('Something-Else', $headers); - $this->assertEquals(['text/plain'], $headers['Something-Else']); + $this->assertArrayHasKey('User-Agent', $headers); + $this->assertEquals(['value'], $headers['User-Agent']); } } From 0a83557f56a729496d4c260c178c8d43f1b8044c Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 30 Mar 2017 17:44:42 +0100 Subject: [PATCH 36/37] updated test.php --- samples/client/petstore/php/test.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index ba7da2c5757..8863c653127 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -21,7 +21,7 @@ //$api_client->getConfig()->addDefaultHeader("test1", "value1"); //$pet_api = new Swagger\Client\PetAPI($api_client); $config = new \Swagger\Client\Configuration(); - $petApi = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client(), $config); + $petApi = new Swagger\Client\Api\PetApi(null, $config); $config->setTempFolderPath('/var/tmp/php/'); // test default header //$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); @@ -47,7 +47,7 @@ $newPet->setTags(array($tag)); $newPet->setCategory($category); - $petApi = new Swagger\Client\Api\PetApi(new \Http\Adapter\Guzzle6\Client(), $config); + $petApi = new Swagger\Client\Api\PetApi(null, $config); // add a new pet (model) $add_response = $petApi->addPet($newPet); From 54b2ee71ec60db1272ef4920693244c7ae53de61 Mon Sep 17 00:00:00 2001 From: Bartosz Bialek Date: Thu, 30 Mar 2017 18:14:30 +0100 Subject: [PATCH 37/37] downgraded phpunit back to 4.8 to work with php5.5; fixed client initialization in some tests --- .../src/main/resources/php/api_test.mustache | 1 - .../src/main/resources/php/composer.mustache | 2 +- .../php/SwaggerClient-php/composer.json | 2 +- .../php/SwaggerClient-php/composer.json | 2 +- .../SwaggerClient-php/test/Api/PetApiTest.php | 164 +++++------------- .../test/Api/StoreApiTest.php | 6 +- .../test/Api/UserApiTest.php | 5 +- 7 files changed, 50 insertions(+), 132 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api_test.mustache b/modules/swagger-codegen/src/main/resources/php/api_test.mustache index c6504437012..1a8bc84872c 100644 --- a/modules/swagger-codegen/src/main/resources/php/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api_test.mustache @@ -19,7 +19,6 @@ namespace {{invokerPackage}}; use \{{invokerPackage}}\Configuration; -use \{{invokerPackage}}\ApiClient; use \{{invokerPackage}}\ApiException; use \{{invokerPackage}}\ObjectSerializer; diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 511ffba85b4..0a7732fafea 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -26,7 +26,7 @@ "guzzlehttp/guzzle": "^6.2" }, "require-dev": { - "phpunit/phpunit": "^5.0", + "phpunit/phpunit": "^4.8", "squizlabs/php_codesniffer": "~2.6", "friendsofphp/php-cs-fixer": "~1.12" }, diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json index 7b41f990b07..2ebbe805eea 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json @@ -23,7 +23,7 @@ "guzzlehttp/guzzle": "^6.2" }, "require-dev": { - "phpunit/phpunit": "^5.0", + "phpunit/phpunit": "^4.8", "squizlabs/php_codesniffer": "~2.6", "friendsofphp/php-cs-fixer": "~1.12" }, diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index 7b41f990b07..2ebbe805eea 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -23,7 +23,7 @@ "guzzlehttp/guzzle": "^6.2" }, "require-dev": { - "phpunit/phpunit": "^5.0", + "phpunit/phpunit": "^4.8", "squizlabs/php_codesniffer": "~2.6", "friendsofphp/php-cs-fixer": "~1.12" }, diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php index afc781e543b..407b6a995ab 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/PetApiTest.php @@ -41,7 +41,6 @@ namespace Swagger\Client; use \Swagger\Client\Configuration; -use \Swagger\Client\ApiClient; use \Swagger\Client\ApiException; use \Swagger\Client\ObjectSerializer; @@ -125,13 +124,11 @@ public function tearDown() public function testAddPet() { // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); $new_pet_id = 10005; $new_pet = new Model\Pet; $new_pet->setId($new_pet_id); $new_pet->setName("PHP Unit Test 2"); - $pet_api = new Api\PetApi($api_client); + $pet_api = new Api\PetApi(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); // return nothing (void) @@ -159,9 +156,7 @@ public function testDeletePet() public function testFindPetByStatus() { // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_api = new Api\PetApi($api_client); + $pet_api = new Api\PetApi(); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); $this->assertGreaterThan(0, count($response)); // at least one object returned @@ -175,34 +170,32 @@ public function testFindPetByStatus() $this->assertSame(count($response), 0); // confirm no object returned } - /** - * Test case for findPetsByStatus - * - * Finds Pets by status with empty response. - * - * Make sure empty arrays from a producer is actually returned as - * an empty array and not some other value. At some point it was - * returned as null because the code stumbled on PHP loose type - * checking (not on empty array is true, same thing could happen - * with careless use of empty()). - * - */ - public function testFindPetsByStatusWithEmptyResponse() - { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $apiClient = new ApiClient($config); - $storeApi = new Api\PetApi($apiClient); - // this call returns and empty array - $response = $storeApi->findPetsByStatus(array()); - - // make sure this is an array as we want it to be - $this->assertInternalType("array", $response); - - // make sure the array is empty just in case the petstore - // server changes its output - $this->assertEmpty($response); - } +// test currently broken, status cannot be empty +// /** +// * Test case for findPetsByStatus +// * +// * Finds Pets by status with empty response. +// * +// * Make sure empty arrays from a producer is actually returned as +// * an empty array and not some other value. At some point it was +// * returned as null because the code stumbled on PHP loose type +// * checking (not on empty array is true, same thing could happen +// * with careless use of empty()). +// * +// */ +// public function testFindPetsByStatusWithEmptyResponse() +// { +// $storeApi = new Api\PetApi(); +// // this call returns and empty array +// $response = $storeApi->findPetsByStatus(array()); +// +// // make sure this is an array as we want it to be +// $this->assertInternalType("array", $response); +// +// // make sure the array is empty just in case the petstore +// // server changes its output +// $this->assertEmpty($response); +// } /** * Test case for findPetsByTags @@ -212,10 +205,7 @@ public function testFindPetsByStatusWithEmptyResponse() */ public function testFindPetsByTags() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_api = new Api\PetApi($api_client); + $pet_api = new Api\PetApi(); // return Pet (model) $response = $pet_api->findPetsByTags("test php tag"); $this->assertGreaterThan(0, count($response)); // at least one object returned @@ -239,8 +229,10 @@ public function testGetPetById() { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + + $config = new Configuration(); + $config->setApiKey('api_key', '111222333444555'); + $pet_api = new Api\PetApi(null, $config); // return Pet (model) $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); @@ -259,8 +251,11 @@ public function testGetPetByIdWithHttpInfo() { // initialize the API client without host $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + + $config = new Configuration(); + $config->setApiKey('api_key', '111222333444555'); + $pet_api = new Api\PetApi(null, $config); + // return Pet (model) list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); $this->assertSame($response->getId(), $pet_id); @@ -270,7 +265,7 @@ public function testGetPetByIdWithHttpInfo() $this->assertSame($response->getTags()[0]->getId(), $pet_id); $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); $this->assertSame($status_code, 200); - $this->assertSame($response_headers['Content-Type'], 'application/json'); + $this->assertSame($response_headers['Content-Type'], ['application/json']); } /** @@ -281,11 +276,8 @@ public function testGetPetByIdWithHttpInfo() */ public function testUpdatePet() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi($api_client); + $pet_api = new Api\PetApi(); // create updated pet object $updated_pet = new Model\Pet; $updated_pet->setId($pet_id); @@ -308,10 +300,8 @@ public function testUpdatePet() public function testUpdatePetWithFormWithHttpInfo() { // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi($api_client); + $pet_api = new Api\PetApi(); // update Pet (form) list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo( $pet_id, @@ -320,7 +310,7 @@ public function testUpdatePetWithFormWithHttpInfo() // return nothing (void) $this->assertNull($update_response); $this->assertSame($status_code, 200); - $this->assertSame($http_headers['Content-Type'], 'application/json'); + $this->assertSame($http_headers['Content-Type'], ['application/json']); $response = $pet_api->getPetById($pet_id); $this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getName(), 'update pet with form with http info'); @@ -334,11 +324,8 @@ public function testUpdatePetWithFormWithHttpInfo() */ public function testUpdatePetWithForm() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Api\PetApi($api_client); + $pet_api = new Api\PetApi(); // update Pet (form) $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) @@ -357,74 +344,11 @@ public function testUpdatePetWithForm() */ public function testUploadFile() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $pet_api = new Api\PetApi($api_client); + $pet_api = new Api\PetApi(); // upload file $pet_id = 10001; $response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); // return ApiResponse $this->assertInstanceOf('Swagger\Client\Model\ApiResponse', $response); } - - /* - * test static functions defined in ApiClient - */ - public function testApiClient() - { - // test selectHeaderAccept - $api_client = new ApiClient(); - $this->assertSame('application/json', $api_client->selectHeaderAccept(array( - 'application/xml', - 'application/json' - ))); - $this->assertSame(null, $api_client->selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array( - 'application/yaml', - 'application/xml' - ))); - - // test selectHeaderContentType - $this->assertSame('application/json', $api_client->selectHeaderContentType(array( - 'application/xml', - 'application/json' - ))); - $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array( - 'application/yaml', - 'application/xml' - ))); - - // test addDefaultHeader and getDefaultHeader - $api_client->getConfig()->addDefaultHeader('test1', 'value1'); - $api_client->getConfig()->addDefaultHeader('test2', 200); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertSame('value1', $defaultHeader['test1']); - $this->assertSame(200, $defaultHeader['test2']); - - // test deleteDefaultHeader - $api_client->getConfig()->deleteDefaultHeader('test2'); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertFalse(isset($defaultHeader['test2'])); - - $pet_api2 = new Api\PetApi(); - $config3 = new Configuration(); - $apiClient3 = new ApiClient($config3); - $apiClient3->getConfig()->setUserAgent('api client 3'); - $config4 = new Configuration(); - $apiClient4 = new ApiClient($config4); - $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Api\PetApi($apiClient3); - - // 2 different api clients are not the same - $this->assertNotEquals($apiClient3, $apiClient4); - // customied pet api not using the old pet api's api client - $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); - - // test access token - $api_client->getConfig()->setAccessToken("testing_only"); - $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); - } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php index c89ff1d23e3..e091e0ca30d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/StoreApiTest.php @@ -86,7 +86,7 @@ public static function setUpBeforeClass() $new_pet->setTags(array($tag)); $new_pet->setCategory($category); - $pet_api = new PetAPI(); + $pet_api = new PetApi(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } @@ -119,9 +119,7 @@ public function testDeleteOrder() public function testGetInventory() { // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $store_api = new StoreApi($api_client); + $store_api = new StoreApi(); // get inventory $get_response = $store_api->getInventory(); diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php index 40259040623..aa312ed6e9f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/test/Api/UserApiTest.php @@ -136,10 +136,7 @@ public function testGetUserByName() */ public function testLoginUser() { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - $user_api = new UserApi($api_client); + $user_api = new UserApi(); // login $response = $user_api->loginUser("xxxxx", "yyyyyyyy");