From 2315ef2a7f11dade1b9ada83d052824141bf374d Mon Sep 17 00:00:00 2001 From: baartosz Date: Mon, 3 Apr 2017 08:47:57 +0100 Subject: [PATCH] Php client using guzzle6 & psr7 instead of curl (#5190) * reimplemented basic requests with httpplug * added returning headers * added query params support * removed constant reference to model class * some extra @throws; form params * form and query params encoding * file upload / form multipart * added missing response headers in WithHttpInfo calls * removed Store test From PetApiTest class * removed configuration overriding test as its now task of client adapters * updated store tests with new client initialization code * updated composer.json template * not using json_decode if response is string * renamed some variables to camelCase * removed ApiClient and Configuration classes * added HeaderSelector template * added ObjectSerializer injection * regenerated all samples * added AuthConfig and readded support for custom api keys * readded support for oauth tokens * readded basic auth; moved auth tests to separate test class * readded header params * readded support for collections in paths * readded config option; readded exception handling * file downloading; readded some Configuration properties removed earlier * readded default headers * made responses and return types work same way as earlier * made all methods static in ObjectSerializer * updated test.php, replaced autoload.php with composer's autoloader * updated api doc template * removed classes used for testing; regenerated Fake_classname_tags123Api * replaced httplug with guzzle6 * updated required php version to 5.5 * clean up * readded missing userAgent feature; removed default headers from Configuration * updated test.php * downgraded phpunit back to 4.8 to work with php5.5; fixed client initialization in some tests --- .../codegen/languages/PhpClientCodegen.java | 5 +- .../src/main/resources/php/ApiClient.mustache | 357 ------ ...ration.mustache => Configuration.mustache} | 330 +---- .../resources/php/HeaderSelector.mustache | 100 ++ .../resources/php/ObjectSerializer.mustache | 37 +- .../src/main/resources/php/README.mustache | 4 +- .../src/main/resources/php/api.mustache | 277 ++-- .../src/main/resources/php/api_doc.mustache | 2 +- .../src/main/resources/php/api_test.mustache | 1 - .../src/main/resources/php/autoload.mustache | 44 - .../src/main/resources/php/composer.mustache | 8 +- .../php/SwaggerClient-php/README.md | 4 +- .../php/SwaggerClient-php/composer.json | 8 +- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 2 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 179 ++- .../php/SwaggerClient-php/lib/ApiClient.php | 367 ------ .../SwaggerClient-php/lib/ApiException.php | 12 +- .../SwaggerClient-php/lib/Configuration.php | 351 +---- .../SwaggerClient-php/lib/HeaderSelector.php | 110 ++ .../lib/ObjectSerializer.php | 55 +- .../petstore/php/SwaggerClient-php/README.md | 4 +- .../php/SwaggerClient-php/composer.json | 8 +- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 6 +- .../docs/Api/Fake_classname_tags123Api.md | 4 +- .../php/SwaggerClient-php/docs/Api/PetApi.md | 16 +- .../SwaggerClient-php/docs/Api/StoreApi.md | 8 +- .../php/SwaggerClient-php/docs/Api/UserApi.md | 16 +- .../docs/Model/DefaultError.md | 11 + .../php/SwaggerClient-php/docs/Model/Error.md | 11 + .../php/SwaggerClient-php/lib/Api/FakeApi.php | 495 ++++--- .../lib/Api/Fake_classname_tags123Api.php | 189 ++- .../php/SwaggerClient-php/lib/Api/PetApi.php | 1134 ++++++++++++----- .../SwaggerClient-php/lib/Api/StoreApi.php | 580 ++++++--- .../php/SwaggerClient-php/lib/Api/UserApi.php | 1015 +++++++++++---- .../php/SwaggerClient-php/lib/ApiClient.php | 367 ------ .../SwaggerClient-php/lib/Configuration.php | 328 +---- .../SwaggerClient-php/lib/HeaderSelector.php | 110 ++ .../lib/ObjectSerializer.php | 37 +- .../SwaggerClient-php/test/Api/PetApiTest.php | 164 +-- .../test/Api/StoreApiTest.php | 6 +- .../test/Api/UserApiTest.php | 5 +- .../test/Model/DefaultErrorTest.php | 101 ++ .../test/Model/ErrorTest.php | 101 ++ .../php/SwaggerClient-php/tests/AuthTest.php | 62 + .../SwaggerClient-php/tests/ExceptionTest.php | 39 + .../tests/FakeHttpClient.php | 69 + .../tests/HeaderSelectorTest.php | 56 + .../SwaggerClient-php/tests/HeadersTest.php | 31 + .../tests/ParametersTest.php | 55 + .../SwaggerClient-php/tests/PetApiTest.php | 409 +++--- .../tests/ResponseTypesTest.php | 93 ++ .../SwaggerClient-php/tests/StoreApiTest.php | 83 +- .../SwaggerClient-php/tests/UserApiTest.php | 23 +- samples/client/petstore/php/test.php | 31 +- 54 files changed, 4137 insertions(+), 3783 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/php/ApiClient.mustache rename modules/swagger-codegen/src/main/resources/php/{configuration.mustache => Configuration.mustache} (57%) create mode 100644 modules/swagger-codegen/src/main/resources/php/HeaderSelector.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/php/autoload.mustache delete mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php create mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/lib/HeaderSelector.php 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 delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.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/AuthTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/ResponseTypesTest.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..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 @@ -301,12 +301,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // 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("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")); - 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/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 similarity index 57% rename from modules/swagger-codegen/src/main/resources/php/configuration.mustache rename to modules/swagger-codegen/src/main/resources/php/Configuration.mustache index 4e10f33823c..cdbba93a000 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/Configuration.mustache @@ -66,33 +66,12 @@ class Configuration */ 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; + protected $host = '{{basePath}}'; /** * User agent of the HTTP request, set to "PHP-Swagger" by default @@ -122,51 +101,6 @@ class Configuration */ 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 */ @@ -296,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 * @@ -389,178 +281,6 @@ class Configuration 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 * @@ -630,29 +350,6 @@ class Configuration 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 * @@ -697,4 +394,29 @@ class Configuration return $report; } + + /** + * 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/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/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 2014eab8a99..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 @@ -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()); - } - return $deserialized; + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + 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/README.mustache b/modules/swagger-codegen/src/main/resources/php/README.mustache index ab0da1711f2..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 @@ -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/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 6619f8da8c1..253b171cefd 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -18,10 +18,15 @@ namespace {{apiPackage}}; -use \{{invokerPackage}}\ApiClient; -use \{{invokerPackage}}\ApiException; -use \{{invokerPackage}}\Configuration; -use \{{invokerPackage}}\ObjectSerializer; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Psr7\MultipartStream; +use GuzzleHttp\Psr7\Request; +use {{invokerPackage}}\ApiException; +use {{invokerPackage}}\Configuration; +use {{invokerPackage}}\HeaderSelector; +use {{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment @@ -34,50 +39,39 @@ use \{{invokerPackage}}\ObjectSerializer; {{#operations}}class {{classname}} { /** - * API Client - * - * @var \{{invokerPackage}}\ApiClient instance of the ApiClient + * @var ClientInterface */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use + * @var Configuration */ - public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } + protected $config; - $this->apiClient = $apiClient; + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** - * Get API client - * - * @return \{{invokerPackage}}\ApiClient get the API client + * @return Configuration */ - public function getApiClient() + public function getConfig() { - return $this->apiClient; + return $this->config; } - /** - * 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}}} * @@ -91,12 +85,13 @@ 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}}); - return $response; + {{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return $response;{{/returnType}} } /** @@ -112,6 +107,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 * @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,106 +121,96 @@ 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 = ''; + + $resourcePath = '{{{path}}}'; + $formParams = []; $queryParams = []; $headerParams = []; - $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 = ''; + $multipart = false; + $returnType = '{{returnType}}'; {{#queryParams}} // query params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}', true); + ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}', true); } {{/collectionFormat}} if (${{paramName}} !== null) { - $queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); + $queryParams['{{baseName}}'] = ObjectSerializer::toQueryValue(${{paramName}}); } {{/queryParams}} {{#headerParams}} // header params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}'); + ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}'); } {{/collectionFormat}} if (${{paramName}} !== null) { - $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); + $headerParams['{{baseName}}'] = ObjectSerializer::toHeaderValue(${{paramName}}); } {{/headerParams}} + {{#pathParams}} // path params {{#collectionFormat}} if (is_array(${{paramName}})) { - ${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}'); + ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}'); } {{/collectionFormat}} if (${{paramName}} !== null) { - $resourcePath = str_replace( - "{" . "{{baseName}}" . "}", - $this->apiClient->getSerializer()->toPathValue(${{paramName}}), - $resourcePath - ); + $resourcePath = str_replace('{' . '{{baseName}}' . '}', ObjectSerializer::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 - 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(ObjectSerializer::toFormValue($file), 'rb'); {{/isFile}} {{^isFile}} - $formParams['{{baseName}}'] = $this->apiClient->getSerializer()->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = ObjectSerializer::toFormValue(${{paramName}}); {{/isFile}} } {{/formParams}} @@ -238,65 +224,132 @@ use \{{invokerPackage}}\ObjectSerializer; // 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) + } } + + 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->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 (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->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 (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); } {{/isOAuth}} {{/authMethods}} - // make the API Call - 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]; - {{/returnType}} - {{^returnType}} - return [null, $statusCode, $httpHeader]; - {{/returnType}} - } catch (ApiException $e) { - switch ($e->getCode()) { - {{#responses}} - {{#dataType}} - {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); - $e->setResponseObject($data); - break; - {{/dataType}} - {{/responses}} + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + '{{httpMethod}}', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + "[$statusCode] Error connecting to the API ($url)", + $statusCode, + $response->getHeaders(), + $response->getBody() + ); + } + + {{#returnType}} + $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, $response->getHeaders()]; + {{/returnType}} + + } catch (ApiException $e) { + switch ($e->getCode()) { + {{#responses}} + {{#dataType}} + {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} + $data = ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + {{/dataType}} + {{/responses}} + } throw $e; } } 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/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/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/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index 51bf2d5e286..0a7732fafea 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -19,14 +19,14 @@ } ], "require": { - "php": ">=5.4", + "php": ">=5.5", "ext-curl": "*", "ext-json": "*", - "ext-mbstring": "*" + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^6.2" }, "require-dev": { - "phpunit/phpunit": "~4.8", - "satooshi/php-coveralls": "~1.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/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index 975d73429f4..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 @@ -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-security-test/php/SwaggerClient-php/composer.json b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json index 7d1a19b4318..2ebbe805eea 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json @@ -16,14 +16,14 @@ } ], "require": { - "php": ">=5.4", + "php": ">=5.5", "ext-curl": "*", "ext-json": "*", - "ext-mbstring": "*" + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^6.2" }, "require-dev": { - "phpunit/phpunit": "~4.8", - "satooshi/php-coveralls": "~1.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/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 apiClient = $apiClient; + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @return Configuration */ - public function getApiClient() + public function getConfig() { - 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; + return $this->config; } /** @@ -94,12 +88,12 @@ class FakeApi * * @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,53 +103,108 @@ class FakeApi * * @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 = ''; + + $resourcePath = '/fake'; + $formParams = []; $queryParams = []; $headerParams = []; - $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 --']); + $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'] = ObjectSerializer::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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/fake' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/json', '*_/ \" =end --'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json', '*_/ \" =end --'], + ['application/json', '*_/ \" =end --'] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'PUT', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - 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/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 @@ class ApiException extends Exception /** * 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/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index d430f0c7717..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 @@ -39,7 +39,7 @@ namespace Swagger\Client; */ class Configuration { - private static $defaultConfiguration = null; + private static $defaultConfiguration; /** * Associate array to store API key(s) @@ -76,13 +76,6 @@ class Configuration */ protected $password = ''; - /** - * The default header(s) - * - * @var array - */ - protected $defaultHeaders = []; - /** * The host * @@ -90,26 +83,12 @@ class Configuration */ protected $host = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'; - /** - * 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"; + protected $userAgent = 'Swagger-Codegen/1.0.0/php'; /** * Debug switch (default set to false) @@ -132,51 +111,6 @@ class Configuration */ 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 */ @@ -191,7 +125,7 @@ class Configuration * @param string $apiKeyIdentifier API key identifier (authentication scheme) * @param string $key API key or token * - * @return Configuration + * @return $this */ public function setApiKey($apiKeyIdentifier, $key) { @@ -217,7 +151,7 @@ class Configuration * @param string $apiKeyIdentifier API key identifier (authentication scheme) * @param string $prefix API key prefix, e.g. Bearer * - * @return Configuration + * @return $this */ public function setApiKeyPrefix($apiKeyIdentifier, $prefix) { @@ -242,7 +176,7 @@ class Configuration * * @param string $accessToken Token for OAuth * - * @return Configuration + * @return $this */ public function setAccessToken($accessToken) { @@ -265,7 +199,7 @@ class Configuration * * @param string $username Username for HTTP basic authentication * - * @return Configuration + * @return $this */ public function setUsername($username) { @@ -288,7 +222,7 @@ class Configuration * * @param string $password Password for HTTP basic authentication * - * @return Configuration + * @return $this */ public function setPassword($password) { @@ -306,52 +240,12 @@ 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) - * - * @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 + * @return $this */ public function setHost($host) { @@ -374,7 +268,8 @@ class Configuration * * @param string $userAgent the user agent of the api client * - * @return Configuration + * @throws \InvalidArgumentException + * @return $this */ public function setUserAgent($userAgent) { @@ -396,182 +291,12 @@ class Configuration 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 + * @return $this */ public function setDebug($debug) { @@ -594,7 +319,7 @@ class Configuration * * @param string $debugFile Debug file * - * @return Configuration + * @return $this */ public function setDebugFile($debugFile) { @@ -617,7 +342,7 @@ class Configuration * * @param string $tempFolderPath Temp folder path * - * @return Configuration + * @return $this */ public function setTempFolderPath($tempFolderPath) { @@ -635,29 +360,6 @@ class Configuration 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 * @@ -693,10 +395,35 @@ class Configuration { $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; $report .= ' OS: ' . php_uname() . PHP_EOL; - $report .= ' PHP Version: ' . phpversion() . 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) + * + * @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-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..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 @@ -59,10 +59,16 @@ class ObjectSerializer 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; @@ -79,7 +85,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]; @@ -96,9 +102,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)); } /** @@ -111,12 +117,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); } } @@ -129,9 +135,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); } /** @@ -143,12 +149,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); } } @@ -161,7 +167,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); @@ -180,7 +186,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 @@ -255,6 +261,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)) { @@ -262,13 +270,20 @@ 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()); - } - return $deserialized; + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + return new \SplFileObject($filename, 'r'); + } 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/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 1b2dc553326..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 @@ -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/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index 7d1a19b4318..2ebbe805eea 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -16,14 +16,14 @@ } ], "require": { - "php": ">=5.4", + "php": ">=5.5", "ext-curl": "*", "ext-json": "*", - "ext-mbstring": "*" + "ext-mbstring": "*", + "guzzlehttp/guzzle": "^6.2" }, "require-dev": { - "phpunit/phpunit": "~4.8", - "satooshi/php-coveralls": "~1.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/docs/Api/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md index 87cf2da9e4d..5692638488d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -21,7 +21,7 @@ To test \"client\" model 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. apiClient = $apiClient; + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @return Configuration */ - public function getApiClient() + public function getConfig() { - 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; + return $this->config; } /** @@ -94,6 +88,7 @@ class FakeApi * * @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) @@ -109,6 +104,7 @@ class FakeApi * * @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 testClientModelWithHttpInfo($body) @@ -117,17 +113,16 @@ class FakeApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); } - // parse inputs - $resourcePath = "/fake"; - $httpBody = ''; + + $resourcePath = '/fake'; + $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,34 +133,105 @@ class FakeApi // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PATCH', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Client', - '/fake' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Client', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + 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 : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'PATCH', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * @@ -186,12 +252,12 @@ class FakeApi * @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); - return $response; + $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); } /** @@ -214,6 +280,7 @@ class FakeApi * @param string $password None (optional) * @param string $callback None (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 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 +289,10 @@ class FakeApi 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 +300,10 @@ class FakeApi 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.'); } @@ -252,135 +319,191 @@ class FakeApi 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 = ''; + + $resourcePath = '/fake'; + $formParams = []; $queryParams = []; $headerParams = []; - $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 = ''; + $multipart = false; + $returnType = ''; + + // form params if ($integer !== null) { - $formParams['integer'] = $this->apiClient->getSerializer()->toFormValue($integer); + $formParams['integer'] = ObjectSerializer::toFormValue($integer); } // form params if ($int32 !== null) { - $formParams['int32'] = $this->apiClient->getSerializer()->toFormValue($int32); + $formParams['int32'] = ObjectSerializer::toFormValue($int32); } // form params if ($int64 !== null) { - $formParams['int64'] = $this->apiClient->getSerializer()->toFormValue($int64); + $formParams['int64'] = ObjectSerializer::toFormValue($int64); } // form params if ($number !== null) { - $formParams['number'] = $this->apiClient->getSerializer()->toFormValue($number); + $formParams['number'] = ObjectSerializer::toFormValue($number); } // form params if ($float !== null) { - $formParams['float'] = $this->apiClient->getSerializer()->toFormValue($float); + $formParams['float'] = ObjectSerializer::toFormValue($float); } // form params if ($double !== null) { - $formParams['double'] = $this->apiClient->getSerializer()->toFormValue($double); + $formParams['double'] = ObjectSerializer::toFormValue($double); } // form params if ($string !== null) { - $formParams['string'] = $this->apiClient->getSerializer()->toFormValue($string); + $formParams['string'] = ObjectSerializer::toFormValue($string); } // form params if ($pattern_without_delimiter !== null) { - $formParams['pattern_without_delimiter'] = $this->apiClient->getSerializer()->toFormValue($pattern_without_delimiter); + $formParams['pattern_without_delimiter'] = ObjectSerializer::toFormValue($pattern_without_delimiter); } // form params if ($byte !== null) { - $formParams['byte'] = $this->apiClient->getSerializer()->toFormValue($byte); + $formParams['byte'] = ObjectSerializer::toFormValue($byte); } // form params if ($binary !== null) { - $formParams['binary'] = $this->apiClient->getSerializer()->toFormValue($binary); + $formParams['binary'] = ObjectSerializer::toFormValue($binary); } // form params if ($date !== null) { - $formParams['date'] = $this->apiClient->getSerializer()->toFormValue($date); + $formParams['date'] = ObjectSerializer::toFormValue($date); } // form params if ($date_time !== null) { - $formParams['dateTime'] = $this->apiClient->getSerializer()->toFormValue($date_time); + $formParams['dateTime'] = ObjectSerializer::toFormValue($date_time); } // form params if ($password !== null) { - $formParams['password'] = $this->apiClient->getSerializer()->toFormValue($password); + $formParams['password'] = ObjectSerializer::toFormValue($password); } // form params if ($callback !== null) { - $formParams['callback'] = $this->apiClient->getSerializer()->toFormValue($callback); + $formParams['callback'] = ObjectSerializer::toFormValue($callback); } // 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 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 { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/fake' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $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'] + ); + } + + // this endpoint requires HTTP basic authentication + 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); + $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation testEnumParameters * @@ -395,12 +518,12 @@ class FakeApi * @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); - return $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); } /** @@ -417,84 +540,142 @@ class FakeApi * @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 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 = ''; + + $resourcePath = '/fake'; + $formParams = []; $queryParams = []; $headerParams = []; - $formParams = []; - $_header_accept = $this->apiClient->selectHeaderAccept(['*/*']); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['*/*']); + $httpBody = ''; + $multipart = false; + $returnType = ''; // 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 = ObjectSerializer::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'] = ObjectSerializer::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'] = ObjectSerializer::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'] = ObjectSerializer::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 = ObjectSerializer::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'] = ObjectSerializer::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'] = ObjectSerializer::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); + $formParams['enum_form_string_array'] = ObjectSerializer::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'] = ObjectSerializer::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'] = ObjectSerializer::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 = $formParams; // for HTTP post (form) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - null, - '/fake' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['*/*'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['*/*'], + ['*/*'] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } 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 38974979730..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 @@ -28,10 +28,15 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Psr7\MultipartStream; +use GuzzleHttp\Psr7\Request; +use Swagger\Client\ApiException; +use Swagger\Client\Configuration; +use Swagger\Client\HeaderSelector; +use Swagger\Client\ObjectSerializer; /** * Fake_classname_tags123Api Class Doc Comment @@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer; class Fake_classname_tags123Api { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient + * @var ClientInterface */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var Configuration */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } + protected $config; - $this->apiClient = $apiClient; + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @return Configuration */ - public function getApiClient() + public function getConfig() { - return $this->apiClient; - } - - /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return Fake_classname_tags123Api - */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) - { - $this->apiClient = $apiClient; - return $this; + return $this->config; } /** @@ -94,6 +88,7 @@ class Fake_classname_tags123Api * * @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 +104,7 @@ class Fake_classname_tags123Api * * @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 +113,16 @@ class Fake_classname_tags123Api 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 +133,102 @@ class Fake_classname_tags123Api // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PATCH', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Client', - '/fake_classname_test' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Client', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + 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 : ''); + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'PATCH', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 2a83fec174f..d7085ea8419 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,15 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Psr7\MultipartStream; +use GuzzleHttp\Psr7\Request; +use Swagger\Client\ApiException; +use Swagger\Client\Configuration; +use Swagger\Client\HeaderSelector; +use Swagger\Client\ObjectSerializer; /** * PetApi Class Doc Comment @@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer; class PetApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient + * @var ClientInterface */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var Configuration */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } + protected $config; - $this->apiClient = $apiClient; + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @return Configuration */ - public function getApiClient() + public function getConfig() { - return $this->apiClient; - } - - /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return PetApi - */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) - { - $this->apiClient = $apiClient; - return $this; + return $this->config; } /** @@ -94,12 +88,12 @@ class PetApi * * @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); - return $response; + $this->addPetWithHttpInfo($body); } /** @@ -109,6 +103,7 @@ class PetApi * * @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 array of null, HTTP status code, HTTP response headers (array of strings) */ public function addPetWithHttpInfo($body) @@ -117,17 +112,16 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling addPet'); } - // parse inputs - $resourcePath = "/pet"; - $httpBody = ''; + + $resourcePath = '/pet'; + $formParams = []; $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(['application/json', 'application/xml']); + $httpBody = ''; + $multipart = false; + $returnType = ''; + + // body params $_tempBody = null; @@ -138,34 +132,91 @@ class PetApi // 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->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation deletePet * @@ -174,12 +225,12 @@ class PetApi * @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); - return $response; + $this->deletePetWithHttpInfo($pet_id, $api_key); } /** @@ -190,6 +241,7 @@ class PetApi * @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 array of null, HTTP status code, HTTP response headers (array of strings) */ public function deletePetWithHttpInfo($pet_id, $api_key = null) @@ -198,62 +250,114 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; + + $resourcePath = '/pet/{petId}'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; // header params if ($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); + $headerParams['api_key'] = ObjectSerializer::toHeaderValue($api_key); } + // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::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->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'DELETE', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet/{petId}' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'DELETE', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation findPetsByStatus * @@ -261,6 +365,7 @@ class PetApi * * @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) @@ -276,6 +381,7 @@ class PetApi * * @param string[] $status Status values that need to be considered for filter (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByStatusWithHttpInfo($status) @@ -284,61 +390,131 @@ class PetApi if ($status === null) { throw new \InvalidArgumentException('Missing the required parameter $status when calling findPetsByStatus'); } - // parse inputs - $resourcePath = "/pet/findByStatus"; - $httpBody = ''; + + $resourcePath = '/pet/findByStatus'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\Pet[]'; // query params if (is_array($status)) { - $status = $this->apiClient->getSerializer()->serializeCollection($status, 'csv', true); + $status = ObjectSerializer::serializeCollection($status, 'csv', true); } if ($status !== null) { - $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); + $queryParams['status'] = ObjectSerializer::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->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet[]', - '/pet/findByStatus' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * @@ -346,6 +522,7 @@ class PetApi * * @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) @@ -361,6 +538,7 @@ class PetApi * * @param string[] $tags Tags to filter by (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ public function findPetsByTagsWithHttpInfo($tags) @@ -369,61 +547,131 @@ class PetApi if ($tags === null) { throw new \InvalidArgumentException('Missing the required parameter $tags when calling findPetsByTags'); } - // parse inputs - $resourcePath = "/pet/findByTags"; - $httpBody = ''; + + $resourcePath = '/pet/findByTags'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\Pet[]'; // query params if (is_array($tags)) { - $tags = $this->apiClient->getSerializer()->serializeCollection($tags, 'csv', true); + $tags = ObjectSerializer::serializeCollection($tags, 'csv', true); } if ($tags !== null) { - $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); + $queryParams['tags'] = ObjectSerializer::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->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet[]', - '/pet/findByTags' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * @@ -431,6 +679,7 @@ class PetApi * * @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) @@ -446,6 +695,7 @@ class PetApi * * @param int $pet_id ID of pet to return (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ public function getPetByIdWithHttpInfo($pet_id) @@ -454,63 +704,129 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; + + $resourcePath = '/pet/{petId}'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\Pet'; + // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::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 API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Pet', - '/pet/{petId}' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * @@ -518,12 +834,12 @@ class PetApi * * @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); - return $response; + $this->updatePetWithHttpInfo($body); } /** @@ -533,6 +849,7 @@ class PetApi * * @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 array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithHttpInfo($body) @@ -541,17 +858,16 @@ class PetApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updatePet'); } - // parse inputs - $resourcePath = "/pet"; - $httpBody = ''; + + $resourcePath = '/pet'; + $formParams = []; $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(['application/json', 'application/xml']); + $httpBody = ''; + $multipart = false; + $returnType = ''; + + // body params $_tempBody = null; @@ -562,34 +878,91 @@ class PetApi // 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->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/json', 'application/xml'] + ); + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'PUT', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation updatePetWithForm * @@ -599,12 +972,12 @@ class PetApi * @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); - return $response; + $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status); } /** @@ -616,6 +989,7 @@ class PetApi * @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 array of null, HTTP status code, HTTP response headers (array of strings) */ public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null) @@ -624,66 +998,118 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - // parse inputs - $resourcePath = "/pet/{petId}"; - $httpBody = ''; + + $resourcePath = '/pet/{petId}'; + $formParams = []; $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(['application/x-www-form-urlencoded']); + $httpBody = ''; + $multipart = false; + $returnType = ''; + // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::toPathValue($pet_id), $resourcePath); } + // form params if ($name !== null) { - $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); + $formParams['name'] = ObjectSerializer::toFormValue($name); } // form params if ($status !== null) { - $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); + $formParams['status'] = ObjectSerializer::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->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/pet/{petId}' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + ['application/x-www-form-urlencoded'] + ); + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation uploadFile * @@ -693,6 +1119,7 @@ class PetApi * @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) @@ -710,6 +1137,7 @@ class PetApi * @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 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,72 +1146,134 @@ class PetApi if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - // parse inputs - $resourcePath = "/pet/{petId}/uploadImage"; - $httpBody = ''; + + $resourcePath = '/pet/{petId}/uploadImage'; + $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(['multipart/form-data']); + $httpBody = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\ApiResponse'; + // path params if ($pet_id !== null) { - $resourcePath = str_replace( - "{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'petId' . '}', ObjectSerializer::toPathValue($pet_id), $resourcePath); } + // form params if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); + $formParams['additionalMetadata'] = ObjectSerializer::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(ObjectSerializer::toFormValue($file), 'rb'); } // 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->apiClient->getConfig()->getAccessToken()) !== 0) { - $headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\ApiResponse', - '/pet/{petId}/uploadImage' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\ApiResponse', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + ['multipart/form-data'] + ); + } + + // this endpoint requires OAuth (access token) + if ($this->config->getAccessToken() !== null) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 bfa8fd71583..775769cf427 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,15 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Psr7\MultipartStream; +use GuzzleHttp\Psr7\Request; +use Swagger\Client\ApiException; +use Swagger\Client\Configuration; +use Swagger\Client\HeaderSelector; +use Swagger\Client\ObjectSerializer; /** * StoreApi Class Doc Comment @@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer; class StoreApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient + * @var ClientInterface */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var Configuration */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } + protected $config; - $this->apiClient = $apiClient; + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @return Configuration */ - public function getApiClient() + public function getConfig() { - return $this->apiClient; - } - - /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return StoreApi - */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) - { - $this->apiClient = $apiClient; - return $this; + return $this->config; } /** @@ -94,12 +88,12 @@ class StoreApi * * @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); - return $response; + $this->deleteOrderWithHttpInfo($order_id); } /** @@ -109,6 +103,7 @@ class StoreApi * * @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 array of null, HTTP status code, HTTP response headers (array of strings) */ public function deleteOrderWithHttpInfo($order_id) @@ -117,60 +112,113 @@ class StoreApi if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } - // parse inputs - $resourcePath = "/store/order/{order_id}"; - $httpBody = ''; + + $resourcePath = '/store/order/{order_id}'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; + // path params if ($order_id !== null) { - $resourcePath = str_replace( - "{" . "order_id" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'order_id' . '}', ObjectSerializer::toPathValue($order_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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'DELETE', - $queryParams, - $httpBody, - $headerParams, - null, - '/store/order/{order_id}' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'DELETE', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation getInventory * * Returns pet inventories by status * * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return map[string,int] */ public function getInventory() @@ -185,59 +233,130 @@ class StoreApi * Returns pet inventories by status * * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of map[string,int], HTTP status code, HTTP response headers (array of strings) */ public function getInventoryWithHttpInfo() { - // parse inputs - $resourcePath = "/store/inventory"; - $httpBody = ''; + + $resourcePath = '/store/inventory'; + $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([]); + $httpBody = ''; + $multipart = false; + $returnType = 'map[string,int]'; + + // 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 API key authentication - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (strlen($apiKey) !== 0) { - $headerParams['api_key'] = $apiKey; - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - 'map[string,int]', - '/store/inventory' - ); - return [$this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/json'], + [] + ); + } + + // this endpoint requires API key authentication + $apiKey = $this->config->getApiKeyWithPrefix('api_key'); + if ($apiKey !== null) { + $headers['api_key'] = $apiKey; + } + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * @@ -245,6 +364,7 @@ class StoreApi * * @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) @@ -260,6 +380,7 @@ class StoreApi * * @param int $order_id ID of pet that needs to be fetched (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function getOrderByIdWithHttpInfo($order_id) @@ -268,65 +389,131 @@ class StoreApi 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.'); } - // parse inputs - $resourcePath = "/store/order/{order_id}"; - $httpBody = ''; + + $resourcePath = '/store/order/{order_id}'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\Order'; + // path params if ($order_id !== null) { - $resourcePath = str_replace( - "{" . "order_id" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath - ); + $resourcePath = str_replace('{' . 'order_id' . '}', ObjectSerializer::toPathValue($order_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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Order', - '/store/order/{order_id}' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * @@ -334,6 +521,7 @@ class StoreApi * * @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) @@ -349,6 +537,7 @@ class StoreApi * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @throws \Swagger\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ public function placeOrderWithHttpInfo($body) @@ -357,17 +546,16 @@ class StoreApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder'); } - // parse inputs - $resourcePath = "/store/order"; - $httpBody = ''; + + $resourcePath = '/store/order'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\Order'; + + // body params $_tempBody = null; @@ -378,30 +566,102 @@ class StoreApi // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\Order', - '/store/order' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 8d893d055ec..cea798f65ab 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,15 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; -use \Swagger\Client\ApiException; -use \Swagger\Client\Configuration; -use \Swagger\Client\ObjectSerializer; +use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; +use GuzzleHttp\Exception\RequestException; +use GuzzleHttp\Psr7\MultipartStream; +use GuzzleHttp\Psr7\Request; +use Swagger\Client\ApiException; +use Swagger\Client\Configuration; +use Swagger\Client\HeaderSelector; +use Swagger\Client\ObjectSerializer; /** * UserApi Class Doc Comment @@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer; class UserApi { /** - * API Client - * - * @var \Swagger\Client\ApiClient instance of the ApiClient + * @var ClientInterface */ - protected $apiClient; + protected $client; /** - * Constructor - * - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + * @var Configuration */ - public function __construct(\Swagger\Client\ApiClient $apiClient = null) - { - if ($apiClient === null) { - $apiClient = new ApiClient(); - } + protected $config; - $this->apiClient = $apiClient; + /** + * @param ClientInterface $client + * @param Configuration $config + * @param HeaderSelector $selector + */ + public function __construct( + ClientInterface $client = null, + Configuration $config = null, + HeaderSelector $selector = null + ) { + $this->client = $client ?: new Client(); + $this->config = $config ?: new Configuration(); + $this->headerSelector = $selector ?: new HeaderSelector(); } /** - * Get API client - * - * @return \Swagger\Client\ApiClient get the API client + * @return Configuration */ - public function getApiClient() + public function getConfig() { - return $this->apiClient; - } - - /** - * Set the API client - * - * @param \Swagger\Client\ApiClient $apiClient set the API client - * - * @return UserApi - */ - public function setApiClient(\Swagger\Client\ApiClient $apiClient) - { - $this->apiClient = $apiClient; - return $this; + return $this->config; } /** @@ -94,12 +88,12 @@ class UserApi * * @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); - return $response; + $this->createUserWithHttpInfo($body); } /** @@ -109,6 +103,7 @@ class UserApi * * @param \Swagger\Client\Model\User $body Created user object (required) * @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 createUserWithHttpInfo($body) @@ -117,17 +112,16 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUser'); } - // parse inputs - $resourcePath = "/user"; - $httpBody = ''; + + $resourcePath = '/user'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; + + // body params $_tempBody = null; @@ -138,30 +132,87 @@ class UserApi // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/user' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation createUsersWithArrayInput * @@ -169,12 +220,12 @@ class UserApi * * @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); - return $response; + $this->createUsersWithArrayInputWithHttpInfo($body); } /** @@ -184,6 +235,7 @@ class UserApi * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @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 createUsersWithArrayInputWithHttpInfo($body) @@ -192,17 +244,16 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithArrayInput'); } - // parse inputs - $resourcePath = "/user/createWithArray"; - $httpBody = ''; + + $resourcePath = '/user/createWithArray'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; + + // body params $_tempBody = null; @@ -213,30 +264,87 @@ class UserApi // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/createWithArray' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation createUsersWithListInput * @@ -244,12 +352,12 @@ class UserApi * * @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); - return $response; + $this->createUsersWithListInputWithHttpInfo($body); } /** @@ -259,6 +367,7 @@ class UserApi * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @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 createUsersWithListInputWithHttpInfo($body) @@ -267,17 +376,16 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling createUsersWithListInput'); } - // parse inputs - $resourcePath = "/user/createWithList"; - $httpBody = ''; + + $resourcePath = '/user/createWithList'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; + + // body params $_tempBody = null; @@ -288,30 +396,87 @@ class UserApi // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'POST', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/createWithList' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'POST', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation deleteUser * @@ -319,12 +484,12 @@ class UserApi * * @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); - return $response; + $this->deleteUserWithHttpInfo($username); } /** @@ -334,6 +499,7 @@ class UserApi * * @param string $username The name that needs to be deleted (required) * @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 deleteUserWithHttpInfo($username) @@ -342,54 +508,106 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; + + $resourcePath = '/user/{username}'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; + // path params if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); + $resourcePath = str_replace('{' . 'username' . '}', ObjectSerializer::toPathValue($username), $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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'DELETE', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/{username}' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'DELETE', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation getUserByName * @@ -397,6 +615,7 @@ class UserApi * * @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) @@ -412,6 +631,7 @@ class UserApi * * @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 array of \Swagger\Client\Model\User, HTTP status code, HTTP response headers (array of strings) */ public function getUserByNameWithHttpInfo($username) @@ -420,58 +640,124 @@ class UserApi if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; + + $resourcePath = '/user/{username}'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = '\Swagger\Client\Model\User'; + // path params if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); + $resourcePath = str_replace('{' . 'username' . '}', ObjectSerializer::toPathValue($username), $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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - '\Swagger\Client\Model\User', - '/user/{username}' - ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * @@ -480,6 +766,7 @@ class UserApi * @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) @@ -496,6 +783,7 @@ class UserApi * @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 array of string, HTTP status code, HTTP response headers (array of strings) */ public function loginUserWithHttpInfo($username, $password) @@ -508,70 +796,140 @@ class UserApi if ($password === null) { throw new \InvalidArgumentException('Missing the required parameter $password when calling loginUser'); } - // parse inputs - $resourcePath = "/user/login"; - $httpBody = ''; + + $resourcePath = '/user/login'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = 'string'; // query params if ($username !== null) { - $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); + $queryParams['username'] = ObjectSerializer::toQueryValue($username); } // query params if ($password !== null) { - $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); + $queryParams['password'] = ObjectSerializer::toQueryValue($password); } + + // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - 'string', - '/user/login' - ); - return [$this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader), $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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() + ]; + } 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 * * 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(); - return $response; + $this->logoutUserWithHttpInfo(); } /** @@ -580,50 +938,107 @@ class UserApi * Logs out current logged in user session * * @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 logoutUserWithHttpInfo() { - // parse inputs - $resourcePath = "/user/logout"; - $httpBody = ''; + + $resourcePath = '/user/logout'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; + + // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'GET', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/logout' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'GET', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - throw $e; } } - /** * Operation updateUser * @@ -632,12 +1047,12 @@ class UserApi * @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); - return $response; + $this->updateUserWithHttpInfo($username, $body); } /** @@ -648,6 +1063,7 @@ class UserApi * @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 array of null, HTTP status code, HTTP response headers (array of strings) */ public function updateUserWithHttpInfo($username, $body) @@ -660,26 +1076,21 @@ class UserApi if ($body === null) { throw new \InvalidArgumentException('Missing the required parameter $body when calling updateUser'); } - // parse inputs - $resourcePath = "/user/{username}"; - $httpBody = ''; + + $resourcePath = '/user/{username}'; + $formParams = []; $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 = ''; + $multipart = false; + $returnType = ''; + // path params if ($username !== null) { - $resourcePath = str_replace( - "{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath - ); + $resourcePath = str_replace('{' . 'username' . '}', ObjectSerializer::toPathValue($username), $resourcePath); } + // body params $_tempBody = null; if (isset($body)) { @@ -689,26 +1100,84 @@ class UserApi // 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) - } - // make the API Call - try { - list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, - 'PUT', - $queryParams, - $httpBody, - $headerParams, - null, - '/user/{username}' - ); - return [null, $statusCode, $httpHeader]; + } elseif (count($formParams) > 0) { + 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) + } + } + + if ($httpBody instanceof MultipartStream) { + $headers= $this->headerSelector->selectHeadersForMultipart( + ['application/xml', 'application/json'] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + ['application/xml', 'application/json'], + [] + ); + } + + + $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( + $defaultHeaders, + $headerParams, + $headers + ); + + $request = new Request( + 'PUT', + $url, + $headers, + $httpBody + ); + + try { + + try { + $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(); + + 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()]; + } catch (ApiException $e) { switch ($e->getCode()) { } - 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/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 17e0a6feda3..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 * @@ -90,20 +83,6 @@ class Configuration */ 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 * @@ -132,51 +111,6 @@ class Configuration */ 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 */ @@ -306,48 +240,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 * @@ -399,178 +291,6 @@ class Configuration 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 * @@ -640,29 +360,6 @@ class Configuration 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 * @@ -704,4 +401,29 @@ class Configuration return $report; } + + /** + * 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/HeaderSelector.php b/samples/client/petstore/php/SwaggerClient-php/lib/HeaderSelector.php new file mode 100644 index 00000000000..77cee4dd319 --- /dev/null +++ b/samples/client/petstore/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/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 281e51143b6..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 @@ class ObjectSerializer * * @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 @@ 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)); } /** @@ -117,12 +117,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); } } @@ -135,9 +135,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); } /** @@ -149,12 +149,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); } } @@ -167,7 +167,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); @@ -186,7 +186,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 @@ -261,6 +261,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)) { @@ -268,13 +270,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()); - } - return $deserialized; + $file = fopen($filename, 'w'); + while ($chunk = $data->read(200)) { + fwrite($file, $chunk); + } + fclose($file); + + 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/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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase */ 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase */ 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase */ 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 @@ class PetApiTest extends \PHPUnit_Framework_TestCase */ 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 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase $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 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase 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 @@ class UserApiTest extends \PHPUnit_Framework_TestCase */ 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"); 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 @@ +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 Configuration(); + $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 Configuration(); + $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/ExceptionTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php new file mode 100644 index 00000000000..b314b0625e1 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ExceptionTest.php @@ -0,0 +1,39 @@ +expectException(ApiException::class); + $this->expectExceptionCode(404); + $this->expectExceptionMessage('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/FakeHttpClient.php b/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php new file mode 100644 index 00000000000..abdfa7cf7c2 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/FakeHttpClient.php @@ -0,0 +1,69 @@ +request; + } + + /** + * @param null|ResponseInterface $response + */ + 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/HeaderSelectorTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php new file mode 100644 index 00000000000..7a89448f89e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/HeaderSelectorTest.php @@ -0,0 +1,56 @@ +selectHeaders([ + 'application/xml', + 'application/json' + ], []); + $this->assertSame('application/json', $headers['Accept']); + + $headers = $selector->selectHeaders([], []); + $this->assertArrayNotHasKey('Accept', $headers); + + $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']); + } + + 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); + } +} 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..5431a912efe --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/HeadersTest.php @@ -0,0 +1,31 @@ +fakeHttpClient = new FakeHttpClient(); + } + + public function testUserAgent() + { + $config = new Configuration(); + $config->setUserAgent('value'); + $api = new Api\PetApi($this->fakeHttpClient, $config); + + $api->getPetById(3); + + $request = $this->fakeHttpClient->getLastRequest(); + $headers = $request->getHeaders(); + + $this->assertArrayHasKey('User-Agent', $headers); + $this->assertEquals(['value'], $headers['User-Agent']); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php new file mode 100644 index 00000000000..25e18742ed3 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ParametersTest.php @@ -0,0 +1,55 @@ +fakeHttpClient = new FakeHttpClient(); + $this->fakeApi = new Api\FakeApi($this->fakeHttpClient); + $this->userApi = new Api\UserApi($this->fakeHttpClient); + } + + public function testHeaderParam() + { + $this->fakeApi->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->fakeApi->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']); + } + +// 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())); +// } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index bad55050ece..b6a542990c6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -2,9 +2,16 @@ namespace Swagger\Client; +use Swagger\Client\Api\PetApi; +use Swagger\Client\Model\ApiResponse; +use Swagger\Client\Model\Pet; + class PetApiTest extends \PHPUnit_Framework_TestCase { + /** @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() { @@ -12,264 +19,173 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // 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 - $new_pet_id = 10005; - $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")); + $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 = new Model\Tag; + $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); - - $pet_api = new Api\PetApi(); + + $newPet->setTags(array($tag)); + $newPet->setCategory($category); + + $config = new Configuration(); + $petApi = new Api\PetApi(null, $config); + // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); + list(, $status) = $petApi->addPetWithHttpInfo($newPet); + \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(); } - - // 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'); - } - - // 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"); - $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['status'], "available"); - } - // test invalid status - $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() - { - // 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"); - $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"); - } - // test invalid status - $response = $pet_api->findPetsByTags("unknown_and_incorrect_tag"); - $this->assertSame(count($response), 0); // confirm no object returned + $this->assertSame($response_headers['Content-Type'], ['application/json']); + } + + public function testFindPetByStatus() + { + $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 + foreach ($response as $pet) { + $this->assertSame($pet['status'], 'available'); + } + + $response = $this->api->findPetsByStatus('unknown_and_incorrect_status'); + $this->assertCount(0, $response); + } + + public function testFindPetsByTags() + { + $response = $this->api->findPetsByTags('test php tag'); + $this->assertGreaterThan(0, count($response)); // at least one object returned + $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'); + } + + $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); + $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'); } - + // 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'); @@ -278,20 +194,18 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // 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'); } @@ -336,36 +250,17 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($response->getName(), 'PHP Unit Test 3'); } */ - + // 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); } - - // 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 @@ -480,19 +375,21 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $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); +// 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() +// ]); +// } - $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 - } } 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); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 6b926c1d29d..f413737461c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -2,50 +2,24 @@ namespace Swagger\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(); } - // 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 +29,10 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase // 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']); } */ @@ -76,20 +45,16 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase * 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() +// { +// // this call returns and empty array +// $response = $this->api->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); +// } } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index a8487e58764..b65078ed476 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -2,30 +2,29 @@ namespace Swagger\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 - public static function setUpBeforeClass() + /** @var UserApi*/ + private $api; + + public function setUp() { - // for error reporting (need to run with php5.3 to get no warning) - //ini_set('display_errors', 1); - //error_reporting(~0); + $this->api = new Api\UserApi(); } - // test login user + // test login use 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->assertInternalType('string', $response); $this->assertRegExp( - "/^logged in user session/", + '/^logged in user session/', $response, "response string starts with 'logged in user session'" ); diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 5c27e3d7ae9..8863c653127 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(null, $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(null, $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";