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
This commit is contained in:
baartosz 2017-04-03 08:47:57 +01:00 committed by wing328
parent 028cbc77b6
commit 2315ef2a7f
54 changed files with 4137 additions and 3783 deletions

View File

@ -301,12 +301,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
// make test path available in mustache template // make test path available in mustache template
additionalProperties.put("testBasePath", testBasePath); 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("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("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("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("README.mustache", getPackagePath(), "README.md"));
supportingFiles.add(new SupportingFile("phpunit.xml.mustache", getPackagePath(), "phpunit.xml.dist")); supportingFiles.add(new SupportingFile("phpunit.xml.mustache", getPackagePath(), "phpunit.xml.dist"));
supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml")); supportingFiles.add(new SupportingFile(".travis.yml", getPackagePath(), ".travis.yml"));

View File

@ -1,357 +0,0 @@
<?php
/**
* ApiClient
*
* PHP version 5
*
* @category Class
* @package {{invokerPackage}}
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
{{>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;
}
}

View File

@ -66,33 +66,12 @@ class Configuration
*/ */
protected $password = ''; protected $password = '';
/**
* The default header(s)
*
* @var array
*/
protected $defaultHeaders = [];
/** /**
* The host * The host
* *
* @var string * @var string
*/ */
protected $host = '{{{basePath}}}'; protected $host = '{{basePath}}';
/**
* Timeout (second) of the HTTP request, by default set to 0, no timeout
*
* @var string
*/
protected $curlTimeout = 0;
/**
* Timeout (second) of the HTTP connection, by default set to 0, no timeout
*
* @var string
*/
protected $curlConnectTimeout = 0;
/** /**
* User agent of the HTTP request, set to "PHP-Swagger" by default * User agent of the HTTP request, set to "PHP-Swagger" by default
@ -122,51 +101,6 @@ class Configuration
*/ */
protected $tempFolderPath; 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 * Constructor
*/ */
@ -296,48 +230,6 @@ class Configuration
return $this->password; 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 * Sets the host
* *
@ -389,178 +281,6 @@ class Configuration
return $this->userAgent; 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 * Sets debug flag
* *
@ -630,29 +350,6 @@ class Configuration
return $this->tempFolderPath; 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 * Gets the default configuration instance
* *
@ -697,4 +394,29 @@ class Configuration
return $report; 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;
}
} }

View File

@ -0,0 +1,100 @@
<?php
/**
* ApiException
* PHP version 5
*
* @category Class
* @package {{invokerPackage}}
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
{{>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);
}
}
}

View File

@ -75,7 +75,7 @@ class ObjectSerializer
* *
* @return string the sanitized filename * @return string the sanitized filename
*/ */
public function sanitizeFilename($filename) public static function sanitizeFilename($filename)
{ {
if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) {
return $match[1]; return $match[1];
@ -92,9 +92,9 @@ class ObjectSerializer
* *
* @return string the serialized object * @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 * @return string the serialized object
*/ */
public function toQueryValue($object) public static function toQueryValue($object)
{ {
if (is_array($object)) { if (is_array($object)) {
return implode(',', $object); return implode(',', $object);
} else { } else {
return $this->toString($object); return self::toString($object);
} }
} }
@ -125,9 +125,9 @@ class ObjectSerializer
* *
* @return string the header string * @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 * @return string the form string
*/ */
public function toFormValue($value) public static function toFormValue($value)
{ {
if ($value instanceof \SplFileObject) { if ($value instanceof \SplFileObject) {
return $value->getRealPath(); return $value->getRealPath();
} else { } else {
return $this->toString($value); return self::toString($value);
} }
} }
@ -157,7 +157,7 @@ class ObjectSerializer
* *
* @return string the header string * @return string the header string
*/ */
public function toString($value) public static function toString($value)
{ {
if ($value instanceof \DateTime) { // datetime in ISO8601 format if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(\DateTime::ATOM); return $value->format(\DateTime::ATOM);
@ -176,7 +176,7 @@ class ObjectSerializer
* *
* @return string * @return string
*/ */
public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false)
{ {
if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) {
// http_build_query() almost does the job for us. We just // http_build_query() almost does the job for us. We just
@ -251,6 +251,8 @@ class ObjectSerializer
settype($data, $class); settype($data, $class);
return $data; return $data;
} elseif ($class === '\SplFileObject') { } elseif ($class === '\SplFileObject') {
/** @var \Psr\Http\Message\StreamInterface $data */
// determine file name // determine file name
if (array_key_exists('Content-Disposition', $httpHeaders) && if (array_key_exists('Content-Disposition', $httpHeaders) &&
preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) {
@ -258,13 +260,14 @@ class ObjectSerializer
} else { } else {
$filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); $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')) { } elseif (method_exists($class, 'getAllowableEnumValues')) {
if (!in_array($data, $class::getAllowableEnumValues())) { if (!in_array($data, $class::getAllowableEnumValues())) {
$imploded = implode("', '", $class::getAllowableEnumValues()); $imploded = implode("', '", $class::getAllowableEnumValues());

View File

@ -19,7 +19,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
## Requirements ## Requirements
PHP 5.4.0 and later PHP 5.5 and later
## Installation & Usage ## Installation & Usage
### Composer ### Composer
@ -47,7 +47,7 @@ Then run `composer install`
Download the files and include `autoload.php`: Download the files and include `autoload.php`:
```php ```php
require_once('/path/to/{{packagePath}}/autoload.php'); require_once('/path/to/{{packagePath}}/vendor/autoload.php');
``` ```
## Tests ## Tests

View File

@ -18,10 +18,15 @@
namespace {{apiPackage}}; namespace {{apiPackage}};
use \{{invokerPackage}}\ApiClient; use GuzzleHttp\Client;
use \{{invokerPackage}}\ApiException; use GuzzleHttp\ClientInterface;
use \{{invokerPackage}}\Configuration; use GuzzleHttp\Exception\RequestException;
use \{{invokerPackage}}\ObjectSerializer; use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use {{invokerPackage}}\ApiException;
use {{invokerPackage}}\Configuration;
use {{invokerPackage}}\HeaderSelector;
use {{invokerPackage}}\ObjectSerializer;
/** /**
* {{classname}} Class Doc Comment * {{classname}} Class Doc Comment
@ -34,50 +39,39 @@ use \{{invokerPackage}}\ObjectSerializer;
{{#operations}}class {{classname}} {{#operations}}class {{classname}}
{ {
/** /**
* API Client * @var ClientInterface
*
* @var \{{invokerPackage}}\ApiClient instance of the ApiClient
*/ */
protected $apiClient; protected $client;
/** /**
* Constructor * @var Configuration
*
* @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use
*/ */
public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) protected $config;
{
if ($apiClient === null) {
$apiClient = new ApiClient();
}
$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 Configuration
*
* @return \{{invokerPackage}}\ApiClient get the API client
*/ */
public function getApiClient() public function getConfig()
{ {
return $this->apiClient; return $this->config;
} }
/** {{#operation}}
* 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 {{{operationId}}} * Operation {{{operationId}}}
* *
@ -91,12 +85,13 @@ use \{{invokerPackage}}\ObjectSerializer;
* @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} {{/allParams}}
* @throws \{{invokerPackage}}\ApiException on non-2xx response * @throws \{{invokerPackage}}\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/ */
public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{ {
list($response) = $this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return $response; return $response;{{/returnType}}
} }
/** /**
@ -112,6 +107,7 @@ use \{{invokerPackage}}\ObjectSerializer;
* @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} {{/allParams}}
* @throws \{{invokerPackage}}\ApiException on non-2xx response * @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) * @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}}) public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
@ -125,106 +121,96 @@ use \{{invokerPackage}}\ObjectSerializer;
{{/required}} {{/required}}
{{#hasValidation}} {{#hasValidation}}
{{#maxLength}} {{#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}}.'); throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.');
} }
{{/maxLength}} {{/maxLength}}
{{#minLength}} {{#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}}.'); throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.');
} }
{{/minLength}} {{/minLength}}
{{#maximum}} {{#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}}.'); throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.');
} }
{{/maximum}} {{/maximum}}
{{#minimum}} {{#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}}.'); throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.');
} }
{{/minimum}} {{/minimum}}
{{#pattern}} {{#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}}}."); throw new \InvalidArgumentException("invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.");
} }
{{/pattern}} {{/pattern}}
{{#maxItems}} {{#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}}.'); throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.');
} }
{{/maxItems}} {{/maxItems}}
{{#minItems}} {{#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}}.'); throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.');
} }
{{/minItems}} {{/minItems}}
{{/hasValidation}} {{/hasValidation}}
{{/allParams}} {{/allParams}}
// parse inputs
$resourcePath = "{{{path}}}"; $resourcePath = '{{{path}}}';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept([{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '{{returnType}}';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]);
{{#queryParams}} {{#queryParams}}
// query params // query params
{{#collectionFormat}} {{#collectionFormat}}
if (is_array(${{paramName}})) { if (is_array(${{paramName}})) {
${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}', true); ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}', true);
} }
{{/collectionFormat}} {{/collectionFormat}}
if (${{paramName}} !== null) { if (${{paramName}} !== null) {
$queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); $queryParams['{{baseName}}'] = ObjectSerializer::toQueryValue(${{paramName}});
} }
{{/queryParams}} {{/queryParams}}
{{#headerParams}} {{#headerParams}}
// header params // header params
{{#collectionFormat}} {{#collectionFormat}}
if (is_array(${{paramName}})) { if (is_array(${{paramName}})) {
${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}'); ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}');
} }
{{/collectionFormat}} {{/collectionFormat}}
if (${{paramName}} !== null) { if (${{paramName}} !== null) {
$headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); $headerParams['{{baseName}}'] = ObjectSerializer::toHeaderValue(${{paramName}});
} }
{{/headerParams}} {{/headerParams}}
{{#pathParams}} {{#pathParams}}
// path params // path params
{{#collectionFormat}} {{#collectionFormat}}
if (is_array(${{paramName}})) { if (is_array(${{paramName}})) {
${{paramName}} = $this->apiClient->getSerializer()->serializeCollection(${{paramName}}, '{{collectionFormat}}'); ${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}');
} }
{{/collectionFormat}} {{/collectionFormat}}
if (${{paramName}} !== null) { if (${{paramName}} !== null) {
$resourcePath = str_replace( $resourcePath = str_replace('{' . '{{baseName}}' . '}', ObjectSerializer::toPathValue(${{paramName}}), $resourcePath);
"{" . "{{baseName}}" . "}",
$this->apiClient->getSerializer()->toPathValue(${{paramName}}),
$resourcePath
);
} }
{{/pathParams}} {{/pathParams}}
{{#formParams}} {{#formParams}}
// form params // form params
if (${{paramName}} !== null) { if (${{paramName}} !== null) {
{{#isFile}} {{#isFile}}
// PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax $multipart = true;
// See: https://wiki.php.net/rfc/curl-file-upload $formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb');
if (function_exists('curl_file_create')) {
$formParams['{{baseName}}'] = curl_file_create($this->apiClient->getSerializer()->toFormValue(${{paramName}}));
} else {
$formParams['{{baseName}}'] = '@' . $this->apiClient->getSerializer()->toFormValue(${{paramName}});
}
{{/isFile}} {{/isFile}}
{{^isFile}} {{^isFile}}
$formParams['{{baseName}}'] = $this->apiClient->getSerializer()->toFormValue(${{paramName}}); $formParams['{{baseName}}'] = ObjectSerializer::toFormValue(${{paramName}});
{{/isFile}} {{/isFile}}
} }
{{/formParams}} {{/formParams}}
@ -238,65 +224,132 @@ use \{{invokerPackage}}\ObjectSerializer;
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} elseif (count($formParams) > 0) { } 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}} {{#authMethods}}
{{#isApiKey}} {{#isApiKey}}
// this endpoint requires API key authentication // this endpoint requires API key authentication
$apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); $apiKey = $this->config->getApiKeyWithPrefix('{{keyParamName}}');
if (strlen($apiKey) !== 0) { if ($apiKey !== null) {
{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} {{#isKeyInHeader}}$headers['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}}
} }
{{/isApiKey}} {{/isApiKey}}
{{#isBasic}} {{#isBasic}}
// this endpoint requires HTTP basic authentication // this endpoint requires HTTP basic authentication
if (strlen($this->apiClient->getConfig()->getUsername()) !== 0 or strlen($this->apiClient->getConfig()->getPassword()) !== 0) { if ($this->config->getUsername() !== null || $this->config->getPassword() !== null) {
$headerParams['Authorization'] = 'Basic ' . base64_encode($this->apiClient->getConfig()->getUsername() . ":" . $this->apiClient->getConfig()->getPassword()); $headers['Authorization'] = 'Basic ' . base64_encode($this->config->getUsername() . ":" . $this->config->getPassword());
} }
{{/isBasic}} {{/isBasic}}
{{#isOAuth}} {{#isOAuth}}
// this endpoint requires OAuth (access token) // this endpoint requires OAuth (access token)
if (strlen($this->apiClient->getConfig()->getAccessToken()) !== 0) { if ($this->config->getAccessToken() !== null) {
$headerParams['Authorization'] = 'Bearer ' . $this->apiClient->getConfig()->getAccessToken(); $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
} }
{{/isOAuth}} {{/isOAuth}}
{{/authMethods}} {{/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}} $query = \GuzzleHttp\Psr7\build_query($queryParams);
return [$this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader), $statusCode, $httpHeader]; $url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : '');
{{/returnType}}
{{^returnType}} $defaultHeaders = [];
return [null, $statusCode, $httpHeader]; if ($this->config->getUserAgent()) {
{{/returnType}} $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
} catch (ApiException $e) { }
switch ($e->getCode()) {
{{#responses}} $headers = array_merge(
{{#dataType}} $defaultHeaders,
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} $headerParams,
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); $headers
$e->setResponseObject($data); );
break;
{{/dataType}} $request = new Request(
{{/responses}} '{{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; throw $e;
} }
} }

View File

@ -33,7 +33,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}}
{{/hasAuthMethods}} {{/hasAuthMethods}}
$api_instance = new {{invokerPackage}}\Api\{{classname}}(); $api_instance = new {{invokerPackage}}\Api\{{classname}}(new \Http\Adapter\Guzzle6\Client());
{{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}
{{/allParams}} {{/allParams}}

View File

@ -19,7 +19,6 @@
namespace {{invokerPackage}}; namespace {{invokerPackage}};
use \{{invokerPackage}}\Configuration; use \{{invokerPackage}}\Configuration;
use \{{invokerPackage}}\ApiClient;
use \{{invokerPackage}}\ApiException; use \{{invokerPackage}}\ApiException;
use \{{invokerPackage}}\ObjectSerializer; use \{{invokerPackage}}\ObjectSerializer;

View File

@ -1,44 +0,0 @@
<?php
{{>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;
}
});

View File

@ -19,14 +19,14 @@
} }
], ],
"require": { "require": {
"php": ">=5.4", "php": ">=5.5",
"ext-curl": "*", "ext-curl": "*",
"ext-json": "*", "ext-json": "*",
"ext-mbstring": "*" "ext-mbstring": "*",
"guzzlehttp/guzzle": "^6.2"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "~4.8", "phpunit/phpunit": "^4.8",
"satooshi/php-coveralls": "~1.0",
"squizlabs/php_codesniffer": "~2.6", "squizlabs/php_codesniffer": "~2.6",
"friendsofphp/php-cs-fixer": "~1.12" "friendsofphp/php-cs-fixer": "~1.12"
}, },

View File

@ -8,7 +8,7 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git
## Requirements ## Requirements
PHP 5.4.0 and later PHP 5.5 and later
## Installation & Usage ## Installation & Usage
### Composer ### Composer
@ -36,7 +36,7 @@ Then run `composer install`
Download the files and include `autoload.php`: Download the files and include `autoload.php`:
```php ```php
require_once('/path/to/SwaggerClient-php/autoload.php'); require_once('/path/to/SwaggerClient-php/vendor/autoload.php');
``` ```
## Tests ## Tests

View File

@ -16,14 +16,14 @@
} }
], ],
"require": { "require": {
"php": ">=5.4", "php": ">=5.5",
"ext-curl": "*", "ext-curl": "*",
"ext-json": "*", "ext-json": "*",
"ext-mbstring": "*" "ext-mbstring": "*",
"guzzlehttp/guzzle": "^6.2"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "~4.8", "phpunit/phpunit": "^4.8",
"satooshi/php-coveralls": "~1.0",
"squizlabs/php_codesniffer": "~2.6", "squizlabs/php_codesniffer": "~2.6",
"friendsofphp/php-cs-fixer": "~1.12" "friendsofphp/php-cs-fixer": "~1.12"
}, },

View File

@ -17,7 +17,7 @@ To test code injection *_/ ' \" =end -- \\r\\n \\n \\r
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\FakeApi(); $api_instance = new Swagger\Client\Api\FakeApi(new \Http\Adapter\Guzzle6\Client());
$test_code_inject____end____rn_n_r = "test_code_inject____end____rn_n_r_example"; // string | To test code injection *_/ ' \" =end -- \\r\\n \\n \\r $test_code_inject____end____rn_n_r = "test_code_inject____end____rn_n_r_example"; // string | To test code injection *_/ ' \" =end -- \\r\\n \\n \\r
try { try {

View File

@ -28,10 +28,15 @@
namespace Swagger\Client\Api; namespace Swagger\Client\Api;
use \Swagger\Client\ApiClient; use GuzzleHttp\Client;
use \Swagger\Client\ApiException; use GuzzleHttp\ClientInterface;
use \Swagger\Client\Configuration; use GuzzleHttp\Exception\RequestException;
use \Swagger\Client\ObjectSerializer; use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use Swagger\Client\ApiException;
use Swagger\Client\Configuration;
use Swagger\Client\HeaderSelector;
use Swagger\Client\ObjectSerializer;
/** /**
* FakeApi Class Doc Comment * FakeApi Class Doc Comment
@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer;
class FakeApi class FakeApi
{ {
/** /**
* API Client * @var ClientInterface
*
* @var \Swagger\Client\ApiClient instance of the ApiClient
*/ */
protected $apiClient; protected $client;
/** /**
* Constructor * @var Configuration
*
* @param \Swagger\Client\ApiClient|null $apiClient The api client to use
*/ */
public function __construct(\Swagger\Client\ApiClient $apiClient = null) protected $config;
{
if ($apiClient === null) {
$apiClient = new ApiClient();
}
$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 Configuration
*
* @return \Swagger\Client\ApiClient get the API client
*/ */
public function getApiClient() public function getConfig()
{ {
return $this->apiClient; return $this->config;
}
/**
* 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;
} }
/** /**
@ -94,12 +88,12 @@ class FakeApi
* *
* @param string $test_code_inject____end____rn_n_r To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional) * @param string $test_code_inject____end____rn_n_r To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return void * @return void
*/ */
public function testCodeInjectEndRnNR($test_code_inject____end____rn_n_r = null) public function testCodeInjectEndRnNR($test_code_inject____end____rn_n_r = null)
{ {
list($response) = $this->testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r); $this->testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r);
return $response;
} }
/** /**
@ -109,53 +103,108 @@ class FakeApi
* *
* @param string $test_code_inject____end____rn_n_r To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional) * @param string $test_code_inject____end____rn_n_r To test code injection *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r (optional)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of null, HTTP status code, HTTP response headers (array of strings) * @return array of null, HTTP status code, HTTP response headers (array of strings)
*/ */
public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r = null) public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r = null)
{ {
// parse inputs
$resourcePath = "/fake"; $resourcePath = '/fake';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/json', '*_/ \" =end --']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', '*_/ \" =end --']);
// default format to json
$resourcePath = str_replace("{format}", "json", $resourcePath);
// form params // form params
if ($test_code_inject____end____rn_n_r !== null) { if ($test_code_inject____end____rn_n_r !== null) {
$formParams['test code inject */ &#39; &quot; &#x3D;end -- \r\n \n \r'] = $this->apiClient->getSerializer()->toFormValue($test_code_inject____end____rn_n_r); $formParams['test code inject */ &#39; &quot; &#x3D;end -- \r\n \n \r'] = ObjectSerializer::toFormValue($test_code_inject____end____rn_n_r);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
} }
throw $e; throw $e;
} }
} }

View File

@ -1,367 +0,0 @@
<?php
/**
* ApiClient
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end --
*
* OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* 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 Swagger\Client;
/**
* ApiClient Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @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(\Swagger\Client\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 \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;
}
}

View File

@ -51,7 +51,7 @@ class ApiException extends Exception
/** /**
* The HTTP header of the server response. * The HTTP header of the server response.
* *
* @var string[] * @var string[]|null
*/ */
protected $responseHeaders; protected $responseHeaders;
@ -65,10 +65,10 @@ class ApiException extends Exception
/** /**
* Constructor * Constructor
* *
* @param string $message Error message * @param string $message Error message
* @param int $code HTTP status code * @param int $code HTTP status code
* @param string[] $responseHeaders HTTP response header * @param string[]|null $responseHeaders HTTP response header
* @param mixed $responseBody HTTP decoded body of the server response either as \stdClass or string * @param mixed $responseBody HTTP decoded body of the server response either as \stdClass or string
*/ */
public function __construct($message = "", $code = 0, $responseHeaders = [], $responseBody = null) public function __construct($message = "", $code = 0, $responseHeaders = [], $responseBody = null)
{ {
@ -80,7 +80,7 @@ class ApiException extends Exception
/** /**
* Gets the HTTP response header * Gets the HTTP response header
* *
* @return string[] HTTP response headers * @return string[]|null HTTP response header
*/ */
public function getResponseHeaders() public function getResponseHeaders()
{ {

View File

@ -39,7 +39,7 @@ namespace Swagger\Client;
*/ */
class Configuration class Configuration
{ {
private static $defaultConfiguration = null; private static $defaultConfiguration;
/** /**
* Associate array to store API key(s) * Associate array to store API key(s)
@ -76,13 +76,6 @@ class Configuration
*/ */
protected $password = ''; protected $password = '';
/**
* The default header(s)
*
* @var array
*/
protected $defaultHeaders = [];
/** /**
* The host * The host
* *
@ -90,26 +83,12 @@ class Configuration
*/ */
protected $host = 'https://petstore.swagger.io *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r/v2 *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r'; protected $host = 'https://petstore.swagger.io *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r/v2 *_/ &#39; \&quot; &#x3D;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 * User agent of the HTTP request, set to "PHP-Swagger" by default
* *
* @var string * @var string
*/ */
protected $userAgent = "Swagger-Codegen/1.0.0/php"; protected $userAgent = 'Swagger-Codegen/1.0.0/php';
/** /**
* Debug switch (default set to false) * Debug switch (default set to false)
@ -132,51 +111,6 @@ class Configuration
*/ */
protected $tempFolderPath; 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 * Constructor
*/ */
@ -191,7 +125,7 @@ class Configuration
* @param string $apiKeyIdentifier API key identifier (authentication scheme) * @param string $apiKeyIdentifier API key identifier (authentication scheme)
* @param string $key API key or token * @param string $key API key or token
* *
* @return Configuration * @return $this
*/ */
public function setApiKey($apiKeyIdentifier, $key) public function setApiKey($apiKeyIdentifier, $key)
{ {
@ -217,7 +151,7 @@ class Configuration
* @param string $apiKeyIdentifier API key identifier (authentication scheme) * @param string $apiKeyIdentifier API key identifier (authentication scheme)
* @param string $prefix API key prefix, e.g. Bearer * @param string $prefix API key prefix, e.g. Bearer
* *
* @return Configuration * @return $this
*/ */
public function setApiKeyPrefix($apiKeyIdentifier, $prefix) public function setApiKeyPrefix($apiKeyIdentifier, $prefix)
{ {
@ -242,7 +176,7 @@ class Configuration
* *
* @param string $accessToken Token for OAuth * @param string $accessToken Token for OAuth
* *
* @return Configuration * @return $this
*/ */
public function setAccessToken($accessToken) public function setAccessToken($accessToken)
{ {
@ -265,7 +199,7 @@ class Configuration
* *
* @param string $username Username for HTTP basic authentication * @param string $username Username for HTTP basic authentication
* *
* @return Configuration * @return $this
*/ */
public function setUsername($username) public function setUsername($username)
{ {
@ -288,7 +222,7 @@ class Configuration
* *
* @param string $password Password for HTTP basic authentication * @param string $password Password for HTTP basic authentication
* *
* @return Configuration * @return $this
*/ */
public function setPassword($password) public function setPassword($password)
{ {
@ -306,52 +240,12 @@ class Configuration
return $this->password; 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 * Sets the host
* *
* @param string $host Host * @param string $host Host
* *
* @return Configuration * @return $this
*/ */
public function setHost($host) public function setHost($host)
{ {
@ -374,7 +268,8 @@ class Configuration
* *
* @param string $userAgent the user agent of the api client * @param string $userAgent the user agent of the api client
* *
* @return Configuration * @throws \InvalidArgumentException
* @return $this
*/ */
public function setUserAgent($userAgent) public function setUserAgent($userAgent)
{ {
@ -396,182 +291,12 @@ class Configuration
return $this->userAgent; 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 * Sets debug flag
* *
* @param bool $debug Debug flag * @param bool $debug Debug flag
* *
* @return Configuration * @return $this
*/ */
public function setDebug($debug) public function setDebug($debug)
{ {
@ -594,7 +319,7 @@ class Configuration
* *
* @param string $debugFile Debug file * @param string $debugFile Debug file
* *
* @return Configuration * @return $this
*/ */
public function setDebugFile($debugFile) public function setDebugFile($debugFile)
{ {
@ -617,7 +342,7 @@ class Configuration
* *
* @param string $tempFolderPath Temp folder path * @param string $tempFolderPath Temp folder path
* *
* @return Configuration * @return $this
*/ */
public function setTempFolderPath($tempFolderPath) public function setTempFolderPath($tempFolderPath)
{ {
@ -635,29 +360,6 @@ class Configuration
return $this->tempFolderPath; 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 * Gets the default configuration instance
* *
@ -693,10 +395,35 @@ class Configuration
{ {
$report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL;
$report .= ' OS: ' . php_uname() . 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 *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r' . PHP_EOL; $report .= ' OpenAPI Spec Version: 1.0.0 *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r' . PHP_EOL;
$report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL;
return $report; 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;
}
} }

View File

@ -0,0 +1,110 @@
<?php
/**
* ApiException
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end --
*
* OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r
* Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* 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 Swagger\Client;
use \Exception;
/**
* ApiException Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @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);
}
}
}

View File

@ -59,10 +59,16 @@ class ObjectSerializer
return $data; return $data;
} elseif (is_object($data)) { } elseif (is_object($data)) {
$values = []; $values = [];
foreach (array_keys($data::swaggerTypes()) as $property) { foreach ($data::swaggerTypes() as $property => $swaggerType) {
$getter = $data::getters()[$property]; $getter = $data::getters()[$property];
if ($data->$getter() !== null) { $value = $data->$getter();
$values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($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; return (object)$values;
@ -79,7 +85,7 @@ class ObjectSerializer
* *
* @return string the sanitized filename * @return string the sanitized filename
*/ */
public function sanitizeFilename($filename) public static function sanitizeFilename($filename)
{ {
if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) {
return $match[1]; return $match[1];
@ -96,9 +102,9 @@ class ObjectSerializer
* *
* @return string the serialized object * @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 * @return string the serialized object
*/ */
public function toQueryValue($object) public static function toQueryValue($object)
{ {
if (is_array($object)) { if (is_array($object)) {
return implode(',', $object); return implode(',', $object);
} else { } else {
return $this->toString($object); return self::toString($object);
} }
} }
@ -129,9 +135,9 @@ class ObjectSerializer
* *
* @return string the header string * @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 * @return string the form string
*/ */
public function toFormValue($value) public static function toFormValue($value)
{ {
if ($value instanceof \SplFileObject) { if ($value instanceof \SplFileObject) {
return $value->getRealPath(); return $value->getRealPath();
} else { } else {
return $this->toString($value); return self::toString($value);
} }
} }
@ -161,7 +167,7 @@ class ObjectSerializer
* *
* @return string the header string * @return string the header string
*/ */
public function toString($value) public static function toString($value)
{ {
if ($value instanceof \DateTime) { // datetime in ISO8601 format if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(\DateTime::ATOM); return $value->format(\DateTime::ATOM);
@ -180,7 +186,7 @@ class ObjectSerializer
* *
* @return string * @return string
*/ */
public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false)
{ {
if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) {
// http_build_query() almost does the job for us. We just // http_build_query() almost does the job for us. We just
@ -255,6 +261,8 @@ class ObjectSerializer
settype($data, $class); settype($data, $class);
return $data; return $data;
} elseif ($class === '\SplFileObject') { } elseif ($class === '\SplFileObject') {
/** @var \Psr\Http\Message\StreamInterface $data */
// determine file name // determine file name
if (array_key_exists('Content-Disposition', $httpHeaders) && if (array_key_exists('Content-Disposition', $httpHeaders) &&
preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) {
@ -262,13 +270,20 @@ class ObjectSerializer
} else { } else {
$filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); $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 { } else {
// If a discriminator is defined and points to a valid subclass, use it. // If a discriminator is defined and points to a valid subclass, use it.
$discriminator = $class::DISCRIMINATOR; $discriminator = $class::DISCRIMINATOR;

View File

@ -8,7 +8,7 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git
## Requirements ## Requirements
PHP 5.4.0 and later PHP 5.5 and later
## Installation & Usage ## Installation & Usage
### Composer ### Composer
@ -36,7 +36,7 @@ Then run `composer install`
Download the files and include `autoload.php`: Download the files and include `autoload.php`:
```php ```php
require_once('/path/to/SwaggerClient-php/autoload.php'); require_once('/path/to/SwaggerClient-php/vendor/autoload.php');
``` ```
## Tests ## Tests

View File

@ -16,14 +16,14 @@
} }
], ],
"require": { "require": {
"php": ">=5.4", "php": ">=5.5",
"ext-curl": "*", "ext-curl": "*",
"ext-json": "*", "ext-json": "*",
"ext-mbstring": "*" "ext-mbstring": "*",
"guzzlehttp/guzzle": "^6.2"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "~4.8", "phpunit/phpunit": "^4.8",
"satooshi/php-coveralls": "~1.0",
"squizlabs/php_codesniffer": "~2.6", "squizlabs/php_codesniffer": "~2.6",
"friendsofphp/php-cs-fixer": "~1.12" "friendsofphp/php-cs-fixer": "~1.12"
}, },

View File

@ -21,7 +21,7 @@ To test \"client\" model
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\FakeApi(); $api_instance = new Swagger\Client\Api\FakeApi(new \Http\Adapter\Guzzle6\Client());
$body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model $body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model
try { try {
@ -70,7 +70,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
Swagger\Client\Configuration::getDefaultConfiguration()->setUsername('YOUR_USERNAME'); Swagger\Client\Configuration::getDefaultConfiguration()->setUsername('YOUR_USERNAME');
Swagger\Client\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD'); 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 $number = 3.4; // float | None
$double = 1.2; // double | None $double = 1.2; // double | None
$pattern_without_delimiter = "pattern_without_delimiter_example"; // string | None $pattern_without_delimiter = "pattern_without_delimiter_example"; // string | None
@ -140,7 +140,7 @@ To test enum parameters
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\FakeApi(); $api_instance = new Swagger\Client\Api\FakeApi(new \Http\Adapter\Guzzle6\Client());
$enum_form_string_array = array("enum_form_string_array_example"); // string[] | Form parameter enum test (string array) $enum_form_string_array = array("enum_form_string_array_example"); // string[] | Form parameter enum test (string array)
$enum_form_string = "-efg"; // string | Form parameter enum test (string) $enum_form_string = "-efg"; // string | Form parameter enum test (string)
$enum_header_string_array = array("enum_header_string_array_example"); // string[] | Header parameter enum test (string array) $enum_header_string_array = array("enum_header_string_array_example"); // string[] | Header parameter enum test (string array)

View File

@ -1,6 +1,6 @@
# Swagger\Client\Fake_classname_tags123Api # Swagger\Client\Fake_classname_tags123Api
All URIs are relative to *http://petstore.swagger.io/v2* All URIs are relative to *http://petstore.swagger.io:80/v2*
Method | HTTP request | Description Method | HTTP request | Description
------------- | ------------- | ------------- ------------- | ------------- | -------------
@ -17,7 +17,7 @@ To test class name in snake case
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\Fake_classname_tags123Api(); $api_instance = new Swagger\Client\Api\Fake_classname_tags123Api(new \Http\Adapter\Guzzle6\Client());
$body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model $body = new \Swagger\Client\Model\Client(); // \Swagger\Client\Model\Client | client model
try { try {

View File

@ -29,7 +29,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: petstore_auth // Configure OAuth2 access token for authorization: petstore_auth
Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); 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 $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store
try { try {
@ -76,7 +76,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: petstore_auth // Configure OAuth2 access token for authorization: petstore_auth
Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); 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 $pet_id = 789; // int | Pet id to delete
$api_key = "api_key_example"; // string | $api_key = "api_key_example"; // string |
@ -125,7 +125,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: petstore_auth // Configure OAuth2 access token for authorization: petstore_auth
Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); 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 $status = array("status_example"); // string[] | Status values that need to be considered for filter
try { try {
@ -173,7 +173,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: petstore_auth // Configure OAuth2 access token for authorization: petstore_auth
Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); 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 $tags = array("tags_example"); // string[] | Tags to filter by
try { 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 // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); // 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 $pet_id = 789; // int | ID of pet to return
try { try {
@ -271,7 +271,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: petstore_auth // Configure OAuth2 access token for authorization: petstore_auth
Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); 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 $body = new \Swagger\Client\Model\Pet(); // \Swagger\Client\Model\Pet | Pet object that needs to be added to the store
try { try {
@ -318,7 +318,7 @@ require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: petstore_auth // Configure OAuth2 access token for authorization: petstore_auth
Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); 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 $pet_id = 789; // int | ID of pet that needs to be updated
$name = "name_example"; // string | Updated name of the pet $name = "name_example"; // string | Updated name of the pet
$status = "status_example"; // string | Updated status 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 // Configure OAuth2 access token for authorization: petstore_auth
Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN'); 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 $pet_id = 789; // int | ID of pet to update
$additional_metadata = "additional_metadata_example"; // string | Additional data to pass to server $additional_metadata = "additional_metadata_example"; // string | Additional data to pass to server
$file = "/path/to/file.txt"; // \SplFileObject | file to upload $file = "/path/to/file.txt"; // \SplFileObject | file to upload

View File

@ -22,7 +22,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\StoreApi(); $api_instance = new Swagger\Client\Api\StoreApi(new \Http\Adapter\Guzzle6\Client());
$order_id = "order_id_example"; // string | ID of the order that needs to be deleted $order_id = "order_id_example"; // string | ID of the order that needs to be deleted
try { try {
@ -71,7 +71,7 @@ Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'Y
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer'); // 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 { try {
$result = $api_instance->getInventory(); $result = $api_instance->getInventory();
@ -112,7 +112,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\StoreApi(); $api_instance = new Swagger\Client\Api\StoreApi(new \Http\Adapter\Guzzle6\Client());
$order_id = 789; // int | ID of pet that needs to be fetched $order_id = 789; // int | ID of pet that needs to be fetched
try { try {
@ -157,7 +157,7 @@ Place an order for a pet
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\StoreApi(); $api_instance = new Swagger\Client\Api\StoreApi(new \Http\Adapter\Guzzle6\Client());
$body = new \Swagger\Client\Model\Order(); // \Swagger\Client\Model\Order | order placed for purchasing the pet $body = new \Swagger\Client\Model\Order(); // \Swagger\Client\Model\Order | order placed for purchasing the pet
try { try {

View File

@ -26,7 +26,7 @@ This can only be done by the logged in user.
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
$body = new \Swagger\Client\Model\User(); // \Swagger\Client\Model\User | Created user object $body = new \Swagger\Client\Model\User(); // \Swagger\Client\Model\User | Created user object
try { try {
@ -70,7 +70,7 @@ Creates list of users with given input array
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
$body = array(new User()); // \Swagger\Client\Model\User[] | List of user object $body = array(new User()); // \Swagger\Client\Model\User[] | List of user object
try { try {
@ -114,7 +114,7 @@ Creates list of users with given input array
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
$body = array(new User()); // \Swagger\Client\Model\User[] | List of user object $body = array(new User()); // \Swagger\Client\Model\User[] | List of user object
try { try {
@ -158,7 +158,7 @@ This can only be done by the logged in user.
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
$username = "username_example"; // string | The name that needs to be deleted $username = "username_example"; // string | The name that needs to be deleted
try { try {
@ -202,7 +202,7 @@ Get user by user name
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
$username = "username_example"; // string | The name that needs to be fetched. Use user1 for testing. $username = "username_example"; // string | The name that needs to be fetched. Use user1 for testing.
try { try {
@ -247,7 +247,7 @@ Logs user into the system
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
$username = "username_example"; // string | The user name for login $username = "username_example"; // string | The user name for login
$password = "password_example"; // string | The password for login in clear text $password = "password_example"; // string | The password for login in clear text
@ -294,7 +294,7 @@ Logs out current logged in user session
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
try { try {
$api_instance->logoutUser(); $api_instance->logoutUser();
@ -334,7 +334,7 @@ This can only be done by the logged in user.
<?php <?php
require_once(__DIR__ . '/vendor/autoload.php'); require_once(__DIR__ . '/vendor/autoload.php');
$api_instance = new Swagger\Client\Api\UserApi(); $api_instance = new Swagger\Client\Api\UserApi(new \Http\Adapter\Guzzle6\Client());
$username = "username_example"; // string | name that need to be deleted $username = "username_example"; // string | name that need to be deleted
$body = new \Swagger\Client\Model\User(); // \Swagger\Client\Model\User | Updated user object $body = new \Swagger\Client\Model\User(); // \Swagger\Client\Model\User | Updated user object

View File

@ -0,0 +1,11 @@
# DefaultError
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**error** | **string** | | [optional]
**code** | **float** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -0,0 +1,11 @@
# Error
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**error** | **string** | | [optional]
**code** | **float** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -28,10 +28,15 @@
namespace Swagger\Client\Api; namespace Swagger\Client\Api;
use \Swagger\Client\ApiClient; use GuzzleHttp\Client;
use \Swagger\Client\ApiException; use GuzzleHttp\ClientInterface;
use \Swagger\Client\Configuration; use GuzzleHttp\Exception\RequestException;
use \Swagger\Client\ObjectSerializer; use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use Swagger\Client\ApiException;
use Swagger\Client\Configuration;
use Swagger\Client\HeaderSelector;
use Swagger\Client\ObjectSerializer;
/** /**
* FakeApi Class Doc Comment * FakeApi Class Doc Comment
@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer;
class FakeApi class FakeApi
{ {
/** /**
* API Client * @var ClientInterface
*
* @var \Swagger\Client\ApiClient instance of the ApiClient
*/ */
protected $apiClient; protected $client;
/** /**
* Constructor * @var Configuration
*
* @param \Swagger\Client\ApiClient|null $apiClient The api client to use
*/ */
public function __construct(\Swagger\Client\ApiClient $apiClient = null) protected $config;
{
if ($apiClient === null) {
$apiClient = new ApiClient();
}
$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 Configuration
*
* @return \Swagger\Client\ApiClient get the API client
*/ */
public function getApiClient() public function getConfig()
{ {
return $this->apiClient; return $this->config;
}
/**
* 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;
} }
/** /**
@ -94,6 +88,7 @@ class FakeApi
* *
* @param \Swagger\Client\Model\Client $body client model (required) * @param \Swagger\Client\Model\Client $body client model (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Client * @return \Swagger\Client\Model\Client
*/ */
public function testClientModel($body) public function testClientModel($body)
@ -109,6 +104,7 @@ class FakeApi
* *
* @param \Swagger\Client\Model\Client $body client model (required) * @param \Swagger\Client\Model\Client $body client model (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @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) * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings)
*/ */
public function testClientModelWithHttpInfo($body) public function testClientModelWithHttpInfo($body)
@ -117,17 +113,16 @@ class FakeApi
if ($body === null) { if ($body === null) {
throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel'); throw new \InvalidArgumentException('Missing the required parameter $body when calling testClientModel');
} }
// parse inputs
$resourcePath = "/fake"; $resourcePath = '/fake';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '\Swagger\Client\Model\Client';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']);
// body params // body params
$_tempBody = null; $_tempBody = null;
@ -138,34 +133,105 @@ class FakeApi
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
case 200: 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); $e->setResponseObject($data);
break; break;
} }
throw $e; throw $e;
} }
} }
/** /**
* Operation testEndpointParameters * Operation testEndpointParameters
* *
@ -186,12 +252,12 @@ class FakeApi
* @param string $password None (optional) * @param string $password None (optional)
* @param string $callback None (optional) * @param string $callback None (optional)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return void * @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) public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null)
{ {
list($response) = $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback); $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback);
return $response;
} }
/** /**
@ -214,6 +280,7 @@ class FakeApi
* @param string $password None (optional) * @param string $password None (optional)
* @param string $callback None (optional) * @param string $callback None (optional)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of null, HTTP status code, HTTP response headers (array of strings) * @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) 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) { if ($number === null) {
throw new \InvalidArgumentException('Missing the required parameter $number when calling testEndpointParameters'); 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.'); 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.'); 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) { if ($double === null) {
throw new \InvalidArgumentException('Missing the required parameter $double when calling testEndpointParameters'); 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.'); 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.'); 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) { if ($byte === null) {
throw new \InvalidArgumentException('Missing the required parameter $byte when calling testEndpointParameters'); 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.'); 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.'); 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.'); 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.'); 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.'); 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."); 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.'); 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.'); throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.');
} }
// parse inputs
$resourcePath = "/fake"; $resourcePath = '/fake';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/xml; charset=utf-8', 'application/json; charset=utf-8']);
// form params // form params
if ($integer !== null) { if ($integer !== null) {
$formParams['integer'] = $this->apiClient->getSerializer()->toFormValue($integer); $formParams['integer'] = ObjectSerializer::toFormValue($integer);
} }
// form params // form params
if ($int32 !== null) { if ($int32 !== null) {
$formParams['int32'] = $this->apiClient->getSerializer()->toFormValue($int32); $formParams['int32'] = ObjectSerializer::toFormValue($int32);
} }
// form params // form params
if ($int64 !== null) { if ($int64 !== null) {
$formParams['int64'] = $this->apiClient->getSerializer()->toFormValue($int64); $formParams['int64'] = ObjectSerializer::toFormValue($int64);
} }
// form params // form params
if ($number !== null) { if ($number !== null) {
$formParams['number'] = $this->apiClient->getSerializer()->toFormValue($number); $formParams['number'] = ObjectSerializer::toFormValue($number);
} }
// form params // form params
if ($float !== null) { if ($float !== null) {
$formParams['float'] = $this->apiClient->getSerializer()->toFormValue($float); $formParams['float'] = ObjectSerializer::toFormValue($float);
} }
// form params // form params
if ($double !== null) { if ($double !== null) {
$formParams['double'] = $this->apiClient->getSerializer()->toFormValue($double); $formParams['double'] = ObjectSerializer::toFormValue($double);
} }
// form params // form params
if ($string !== null) { if ($string !== null) {
$formParams['string'] = $this->apiClient->getSerializer()->toFormValue($string); $formParams['string'] = ObjectSerializer::toFormValue($string);
} }
// form params // form params
if ($pattern_without_delimiter !== null) { 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 // form params
if ($byte !== null) { if ($byte !== null) {
$formParams['byte'] = $this->apiClient->getSerializer()->toFormValue($byte); $formParams['byte'] = ObjectSerializer::toFormValue($byte);
} }
// form params // form params
if ($binary !== null) { if ($binary !== null) {
$formParams['binary'] = $this->apiClient->getSerializer()->toFormValue($binary); $formParams['binary'] = ObjectSerializer::toFormValue($binary);
} }
// form params // form params
if ($date !== null) { if ($date !== null) {
$formParams['date'] = $this->apiClient->getSerializer()->toFormValue($date); $formParams['date'] = ObjectSerializer::toFormValue($date);
} }
// form params // form params
if ($date_time !== null) { if ($date_time !== null) {
$formParams['dateTime'] = $this->apiClient->getSerializer()->toFormValue($date_time); $formParams['dateTime'] = ObjectSerializer::toFormValue($date_time);
} }
// form params // form params
if ($password !== null) { if ($password !== null) {
$formParams['password'] = $this->apiClient->getSerializer()->toFormValue($password); $formParams['password'] = ObjectSerializer::toFormValue($password);
} }
// form params // form params
if ($callback !== null) { if ($callback !== null) {
$formParams['callback'] = $this->apiClient->getSerializer()->toFormValue($callback); $formParams['callback'] = ObjectSerializer::toFormValue($callback);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
} }
throw $e; throw $e;
} }
} }
/** /**
* Operation testEnumParameters * Operation testEnumParameters
* *
@ -395,12 +518,12 @@ class FakeApi
* @param int $enum_query_integer Query parameter enum test (double) (optional) * @param int $enum_query_integer Query parameter enum test (double) (optional)
* @param double $enum_query_double 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 \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return void * @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) public function testEnumParameters($enum_form_string_array = null, $enum_form_string = null, $enum_header_string_array = null, $enum_header_string = null, $enum_query_string_array = null, $enum_query_string = null, $enum_query_integer = null, $enum_query_double = null)
{ {
list($response) = $this->testEnumParametersWithHttpInfo($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double); $this->testEnumParametersWithHttpInfo($enum_form_string_array, $enum_form_string, $enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double);
return $response;
} }
/** /**
@ -417,84 +540,142 @@ class FakeApi
* @param int $enum_query_integer Query parameter enum test (double) (optional) * @param int $enum_query_integer Query parameter enum test (double) (optional)
* @param double $enum_query_double 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 \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of null, HTTP status code, HTTP response headers (array of strings) * @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) 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"; $resourcePath = '/fake';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['*/*']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['*/*']);
// query params // query params
if (is_array($enum_query_string_array)) { 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) { 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 // query params
if ($enum_query_string !== null) { 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 // query params
if ($enum_query_integer !== null) { 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 // header params
if (is_array($enum_header_string_array)) { 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) { 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 // header params
if ($enum_header_string !== null) { 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 // form params
if ($enum_form_string_array !== null) { if ($enum_form_string_array !== null) {
$formParams['enum_form_string_array'] = $this->apiClient->getSerializer()->toFormValue($enum_form_string_array); $formParams['enum_form_string_array'] = ObjectSerializer::toFormValue($enum_form_string_array);
} }
// form params // form params
if ($enum_form_string !== null) { 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 // form params
if ($enum_query_double !== null) { 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) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
} }
throw $e; throw $e;
} }
} }

View File

@ -28,10 +28,15 @@
namespace Swagger\Client\Api; namespace Swagger\Client\Api;
use \Swagger\Client\ApiClient; use GuzzleHttp\Client;
use \Swagger\Client\ApiException; use GuzzleHttp\ClientInterface;
use \Swagger\Client\Configuration; use GuzzleHttp\Exception\RequestException;
use \Swagger\Client\ObjectSerializer; 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 * Fake_classname_tags123Api Class Doc Comment
@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer;
class Fake_classname_tags123Api class Fake_classname_tags123Api
{ {
/** /**
* API Client * @var ClientInterface
*
* @var \Swagger\Client\ApiClient instance of the ApiClient
*/ */
protected $apiClient; protected $client;
/** /**
* Constructor * @var Configuration
*
* @param \Swagger\Client\ApiClient|null $apiClient The api client to use
*/ */
public function __construct(\Swagger\Client\ApiClient $apiClient = null) protected $config;
{
if ($apiClient === null) {
$apiClient = new ApiClient();
}
$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 Configuration
*
* @return \Swagger\Client\ApiClient get the API client
*/ */
public function getApiClient() public function getConfig()
{ {
return $this->apiClient; return $this->config;
}
/**
* 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;
} }
/** /**
@ -94,6 +88,7 @@ class Fake_classname_tags123Api
* *
* @param \Swagger\Client\Model\Client $body client model (required) * @param \Swagger\Client\Model\Client $body client model (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Client * @return \Swagger\Client\Model\Client
*/ */
public function testClassname($body) public function testClassname($body)
@ -109,6 +104,7 @@ class Fake_classname_tags123Api
* *
* @param \Swagger\Client\Model\Client $body client model (required) * @param \Swagger\Client\Model\Client $body client model (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @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) * @return array of \Swagger\Client\Model\Client, HTTP status code, HTTP response headers (array of strings)
*/ */
public function testClassnameWithHttpInfo($body) public function testClassnameWithHttpInfo($body)
@ -117,17 +113,16 @@ class Fake_classname_tags123Api
if ($body === null) { if ($body === null) {
throw new \InvalidArgumentException('Missing the required parameter $body when calling testClassname'); throw new \InvalidArgumentException('Missing the required parameter $body when calling testClassname');
} }
// parse inputs
$resourcePath = "/fake_classname_test"; $resourcePath = '/fake_classname_test';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '\Swagger\Client\Model\Client';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']);
// body params // body params
$_tempBody = null; $_tempBody = null;
@ -138,30 +133,102 @@ class Fake_classname_tags123Api
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
case 200: 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); $e->setResponseObject($data);
break; break;
} }
throw $e; throw $e;
} }
} }

View File

@ -28,10 +28,15 @@
namespace Swagger\Client\Api; namespace Swagger\Client\Api;
use \Swagger\Client\ApiClient; use GuzzleHttp\Client;
use \Swagger\Client\ApiException; use GuzzleHttp\ClientInterface;
use \Swagger\Client\Configuration; use GuzzleHttp\Exception\RequestException;
use \Swagger\Client\ObjectSerializer; 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 * StoreApi Class Doc Comment
@ -44,47 +49,36 @@ use \Swagger\Client\ObjectSerializer;
class StoreApi class StoreApi
{ {
/** /**
* API Client * @var ClientInterface
*
* @var \Swagger\Client\ApiClient instance of the ApiClient
*/ */
protected $apiClient; protected $client;
/** /**
* Constructor * @var Configuration
*
* @param \Swagger\Client\ApiClient|null $apiClient The api client to use
*/ */
public function __construct(\Swagger\Client\ApiClient $apiClient = null) protected $config;
{
if ($apiClient === null) {
$apiClient = new ApiClient();
}
$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 Configuration
*
* @return \Swagger\Client\ApiClient get the API client
*/ */
public function getApiClient() public function getConfig()
{ {
return $this->apiClient; return $this->config;
}
/**
* 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;
} }
/** /**
@ -94,12 +88,12 @@ class StoreApi
* *
* @param string $order_id ID of the order that needs to be deleted (required) * @param string $order_id ID of the order that needs to be deleted (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return void * @return void
*/ */
public function deleteOrder($order_id) public function deleteOrder($order_id)
{ {
list($response) = $this->deleteOrderWithHttpInfo($order_id); $this->deleteOrderWithHttpInfo($order_id);
return $response;
} }
/** /**
@ -109,6 +103,7 @@ class StoreApi
* *
* @param string $order_id ID of the order that needs to be deleted (required) * @param string $order_id ID of the order that needs to be deleted (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of null, HTTP status code, HTTP response headers (array of strings) * @return array of null, HTTP status code, HTTP response headers (array of strings)
*/ */
public function deleteOrderWithHttpInfo($order_id) public function deleteOrderWithHttpInfo($order_id)
@ -117,60 +112,113 @@ class StoreApi
if ($order_id === null) { if ($order_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder');
} }
// parse inputs
$resourcePath = "/store/order/{order_id}"; $resourcePath = '/store/order/{order_id}';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);
// path params // path params
if ($order_id !== null) { if ($order_id !== null) {
$resourcePath = str_replace( $resourcePath = str_replace('{' . 'order_id' . '}', ObjectSerializer::toPathValue($order_id), $resourcePath);
"{" . "order_id" . "}",
$this->apiClient->getSerializer()->toPathValue($order_id),
$resourcePath
);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
} }
throw $e; throw $e;
} }
} }
/** /**
* Operation getInventory * Operation getInventory
* *
* Returns pet inventories by status * Returns pet inventories by status
* *
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return map[string,int] * @return map[string,int]
*/ */
public function getInventory() public function getInventory()
@ -185,59 +233,130 @@ class StoreApi
* Returns pet inventories by status * Returns pet inventories by status
* *
* @throws \Swagger\Client\ApiException on non-2xx response * @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) * @return array of map[string,int], HTTP status code, HTTP response headers (array of strings)
*/ */
public function getInventoryWithHttpInfo() public function getInventoryWithHttpInfo()
{ {
// parse inputs
$resourcePath = "/store/inventory"; $resourcePath = '/store/inventory';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = 'map[string,int]';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
case 200: 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); $e->setResponseObject($data);
break; break;
} }
throw $e; throw $e;
} }
} }
/** /**
* Operation getOrderById * Operation getOrderById
* *
@ -245,6 +364,7 @@ class StoreApi
* *
* @param int $order_id ID of pet that needs to be fetched (required) * @param int $order_id ID of pet that needs to be fetched (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Order * @return \Swagger\Client\Model\Order
*/ */
public function getOrderById($order_id) public function getOrderById($order_id)
@ -260,6 +380,7 @@ class StoreApi
* *
* @param int $order_id ID of pet that needs to be fetched (required) * @param int $order_id ID of pet that needs to be fetched (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @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) * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings)
*/ */
public function getOrderByIdWithHttpInfo($order_id) public function getOrderByIdWithHttpInfo($order_id)
@ -268,65 +389,131 @@ class StoreApi
if ($order_id === null) { if ($order_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); 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.'); 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.'); 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}"; $resourcePath = '/store/order/{order_id}';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '\Swagger\Client\Model\Order';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);
// path params // path params
if ($order_id !== null) { if ($order_id !== null) {
$resourcePath = str_replace( $resourcePath = str_replace('{' . 'order_id' . '}', ObjectSerializer::toPathValue($order_id), $resourcePath);
"{" . "order_id" . "}",
$this->apiClient->getSerializer()->toPathValue($order_id),
$resourcePath
);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
case 200: 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); $e->setResponseObject($data);
break; break;
} }
throw $e; throw $e;
} }
} }
/** /**
* Operation placeOrder * Operation placeOrder
* *
@ -334,6 +521,7 @@ class StoreApi
* *
* @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @throws \Swagger\Client\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return \Swagger\Client\Model\Order * @return \Swagger\Client\Model\Order
*/ */
public function placeOrder($body) public function placeOrder($body)
@ -349,6 +537,7 @@ class StoreApi
* *
* @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required)
* @throws \Swagger\Client\ApiException on non-2xx response * @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) * @return array of \Swagger\Client\Model\Order, HTTP status code, HTTP response headers (array of strings)
*/ */
public function placeOrderWithHttpInfo($body) public function placeOrderWithHttpInfo($body)
@ -357,17 +546,16 @@ class StoreApi
if ($body === null) { if ($body === null) {
throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder'); throw new \InvalidArgumentException('Missing the required parameter $body when calling placeOrder');
} }
// parse inputs
$resourcePath = "/store/order"; $resourcePath = '/store/order';
$httpBody = ''; $formParams = [];
$queryParams = []; $queryParams = [];
$headerParams = []; $headerParams = [];
$formParams = []; $httpBody = '';
$_header_accept = $this->apiClient->selectHeaderAccept(['application/xml', 'application/json']); $multipart = false;
if (!is_null($_header_accept)) { $returnType = '\Swagger\Client\Model\Order';
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType([]);
// body params // body params
$_tempBody = null; $_tempBody = null;
@ -378,30 +566,102 @@ class StoreApi
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $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) { } catch (ApiException $e) {
switch ($e->getCode()) { switch ($e->getCode()) {
case 200: 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); $e->setResponseObject($data);
break; break;
} }
throw $e; throw $e;
} }
} }

View File

@ -1,367 +0,0 @@
<?php
/**
* ApiClient
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Swagger Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* 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 Swagger\Client;
/**
* ApiClient Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @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(\Swagger\Client\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 \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;
}
}

View File

@ -76,13 +76,6 @@ class Configuration
*/ */
protected $password = ''; protected $password = '';
/**
* The default header(s)
*
* @var array
*/
protected $defaultHeaders = [];
/** /**
* The host * The host
* *
@ -90,20 +83,6 @@ class Configuration
*/ */
protected $host = 'http://petstore.swagger.io:80/v2'; 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 * User agent of the HTTP request, set to "PHP-Swagger" by default
* *
@ -132,51 +111,6 @@ class Configuration
*/ */
protected $tempFolderPath; 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 * Constructor
*/ */
@ -306,48 +240,6 @@ class Configuration
return $this->password; 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 * Sets the host
* *
@ -399,178 +291,6 @@ class Configuration
return $this->userAgent; 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 * Sets debug flag
* *
@ -640,29 +360,6 @@ class Configuration
return $this->tempFolderPath; 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 * Gets the default configuration instance
* *
@ -704,4 +401,29 @@ class Configuration
return $report; 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;
}
} }

View File

@ -0,0 +1,110 @@
<?php
/**
* ApiException
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Swagger Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* 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 Swagger\Client;
use \Exception;
/**
* ApiException Class Doc Comment
*
* @category Class
* @package Swagger\Client
* @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);
}
}
}

View File

@ -85,7 +85,7 @@ class ObjectSerializer
* *
* @return string the sanitized filename * @return string the sanitized filename
*/ */
public function sanitizeFilename($filename) public static function sanitizeFilename($filename)
{ {
if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) {
return $match[1]; return $match[1];
@ -102,9 +102,9 @@ class ObjectSerializer
* *
* @return string the serialized object * @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 * @return string the serialized object
*/ */
public function toQueryValue($object) public static function toQueryValue($object)
{ {
if (is_array($object)) { if (is_array($object)) {
return implode(',', $object); return implode(',', $object);
} else { } else {
return $this->toString($object); return self::toString($object);
} }
} }
@ -135,9 +135,9 @@ class ObjectSerializer
* *
* @return string the header string * @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 * @return string the form string
*/ */
public function toFormValue($value) public static function toFormValue($value)
{ {
if ($value instanceof \SplFileObject) { if ($value instanceof \SplFileObject) {
return $value->getRealPath(); return $value->getRealPath();
} else { } else {
return $this->toString($value); return self::toString($value);
} }
} }
@ -167,7 +167,7 @@ class ObjectSerializer
* *
* @return string the header string * @return string the header string
*/ */
public function toString($value) public static function toString($value)
{ {
if ($value instanceof \DateTime) { // datetime in ISO8601 format if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(\DateTime::ATOM); return $value->format(\DateTime::ATOM);
@ -186,7 +186,7 @@ class ObjectSerializer
* *
* @return string * @return string
*/ */
public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false) public static function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti = false)
{ {
if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) { if ($allowCollectionFormatMulti && ('multi' === $collectionFormat)) {
// http_build_query() almost does the job for us. We just // http_build_query() almost does the job for us. We just
@ -261,6 +261,8 @@ class ObjectSerializer
settype($data, $class); settype($data, $class);
return $data; return $data;
} elseif ($class === '\SplFileObject') { } elseif ($class === '\SplFileObject') {
/** @var \Psr\Http\Message\StreamInterface $data */
// determine file name // determine file name
if (array_key_exists('Content-Disposition', $httpHeaders) && if (array_key_exists('Content-Disposition', $httpHeaders) &&
preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) {
@ -268,13 +270,14 @@ class ObjectSerializer
} else { } else {
$filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); $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')) { } elseif (method_exists($class, 'getAllowableEnumValues')) {
if (!in_array($data, $class::getAllowableEnumValues())) { if (!in_array($data, $class::getAllowableEnumValues())) {
$imploded = implode("', '", $class::getAllowableEnumValues()); $imploded = implode("', '", $class::getAllowableEnumValues());

View File

@ -41,7 +41,6 @@
namespace Swagger\Client; namespace Swagger\Client;
use \Swagger\Client\Configuration; use \Swagger\Client\Configuration;
use \Swagger\Client\ApiClient;
use \Swagger\Client\ApiException; use \Swagger\Client\ApiException;
use \Swagger\Client\ObjectSerializer; use \Swagger\Client\ObjectSerializer;
@ -125,13 +124,11 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
public function testAddPet() public function testAddPet()
{ {
// initialize the API client // initialize the API client
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2');
$api_client = new ApiClient($config);
$new_pet_id = 10005; $new_pet_id = 10005;
$new_pet = new Model\Pet; $new_pet = new Model\Pet;
$new_pet->setId($new_pet_id); $new_pet->setId($new_pet_id);
$new_pet->setName("PHP Unit Test 2"); $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 a new pet (model)
$add_response = $pet_api->addPet($new_pet); $add_response = $pet_api->addPet($new_pet);
// return nothing (void) // return nothing (void)
@ -159,9 +156,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
public function testFindPetByStatus() public function testFindPetByStatus()
{ {
// initialize the API client // initialize the API client
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); $pet_api = new Api\PetApi();
$api_client = new ApiClient($config);
$pet_api = new Api\PetApi($api_client);
// return Pet (model) // return Pet (model)
$response = $pet_api->findPetsByStatus("available"); $response = $pet_api->findPetsByStatus("available");
$this->assertGreaterThan(0, count($response)); // at least one object returned $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 $this->assertSame(count($response), 0); // confirm no object returned
} }
/** // test currently broken, status cannot be empty
* Test case for findPetsByStatus // /**
* // * Test case for findPetsByStatus
* Finds Pets by status with empty response. // *
* // * 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 // * Make sure empty arrays from a producer is actually returned as
* returned as null because the code stumbled on PHP loose type // * an empty array and not some other value. At some point it was
* checking (not on empty array is true, same thing could happen // * returned as null because the code stumbled on PHP loose type
* with careless use of empty()). // * checking (not on empty array is true, same thing could happen
* // * with careless use of empty()).
*/ // *
public function testFindPetsByStatusWithEmptyResponse() // */
{ // public function testFindPetsByStatusWithEmptyResponse()
// initialize the API client // {
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); // $storeApi = new Api\PetApi();
$apiClient = new ApiClient($config); // // this call returns and empty array
$storeApi = new Api\PetApi($apiClient); // $response = $storeApi->findPetsByStatus(array());
// 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 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
// make sure the array is empty just in case the petstore // $this->assertEmpty($response);
// server changes its output // }
$this->assertEmpty($response);
}
/** /**
* Test case for findPetsByTags * Test case for findPetsByTags
@ -212,10 +205,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
*/ */
public function testFindPetsByTags() public function testFindPetsByTags()
{ {
// initialize the API client $pet_api = new Api\PetApi();
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2');
$api_client = new ApiClient($config);
$pet_api = new Api\PetApi($api_client);
// return Pet (model) // return Pet (model)
$response = $pet_api->findPetsByTags("test php tag"); $response = $pet_api->findPetsByTags("test php tag");
$this->assertGreaterThan(0, count($response)); // at least one object returned $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 // initialize the API client without host
$pet_id = 10005; // ID of pet that needs to be fetched $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) // return Pet (model)
$response = $pet_api->getPetById($pet_id); $response = $pet_api->getPetById($pet_id);
$this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getId(), $pet_id);
@ -259,8 +251,11 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
{ {
// initialize the API client without host // initialize the API client without host
$pet_id = 10005; // ID of pet that needs to be fetched $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) // return Pet (model)
list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id);
$this->assertSame($response->getId(), $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]->getId(), $pet_id);
$this->assertSame($response->getTags()[0]->getName(), 'test php tag'); $this->assertSame($response->getTags()[0]->getName(), 'test php tag');
$this->assertSame($status_code, 200); $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() 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_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 // create updated pet object
$updated_pet = new Model\Pet; $updated_pet = new Model\Pet;
$updated_pet->setId($pet_id); $updated_pet->setId($pet_id);
@ -308,10 +300,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
public function testUpdatePetWithFormWithHttpInfo() public function testUpdatePetWithFormWithHttpInfo()
{ {
// initialize the API client // 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_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 Pet (form)
list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo( list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo(
$pet_id, $pet_id,
@ -320,7 +310,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
// return nothing (void) // return nothing (void)
$this->assertNull($update_response); $this->assertNull($update_response);
$this->assertSame($status_code, 200); $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); $response = $pet_api->getPetById($pet_id);
$this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getId(), $pet_id);
$this->assertSame($response->getName(), 'update pet with form with http info'); $this->assertSame($response->getName(), 'update pet with form with http info');
@ -334,11 +324,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
*/ */
public function testUpdatePetWithForm() 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_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 Pet (form)
$update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold');
// return nothing (void) // return nothing (void)
@ -357,74 +344,11 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
*/ */
public function testUploadFile() public function testUploadFile()
{ {
// initialize the API client $pet_api = new Api\PetApi();
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2');
$api_client = new ApiClient($config);
$pet_api = new Api\PetApi($api_client);
// upload file // upload file
$pet_id = 10001; $pet_id = 10001;
$response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); $response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json");
// return ApiResponse // return ApiResponse
$this->assertInstanceOf('Swagger\Client\Model\ApiResponse', $response); $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());
}
} }

View File

@ -86,7 +86,7 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase
$new_pet->setTags(array($tag)); $new_pet->setTags(array($tag));
$new_pet->setCategory($category); $new_pet->setCategory($category);
$pet_api = new PetAPI(); $pet_api = new PetApi();
// add a new pet (model) // add a new pet (model)
$add_response = $pet_api->addPet($new_pet); $add_response = $pet_api->addPet($new_pet);
} }
@ -119,9 +119,7 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase
public function testGetInventory() public function testGetInventory()
{ {
// initialize the API client // initialize the API client
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); $store_api = new StoreApi();
$api_client = new ApiClient($config);
$store_api = new StoreApi($api_client);
// get inventory // get inventory
$get_response = $store_api->getInventory(); $get_response = $store_api->getInventory();

View File

@ -136,10 +136,7 @@ class UserApiTest extends \PHPUnit_Framework_TestCase
*/ */
public function testLoginUser() public function testLoginUser()
{ {
// initialize the API client $user_api = new UserApi();
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2');
$api_client = new ApiClient($config);
$user_api = new UserApi($api_client);
// login // login
$response = $user_api->loginUser("xxxxx", "yyyyyyyy"); $response = $user_api->loginUser("xxxxx", "yyyyyyyy");

View File

@ -0,0 +1,101 @@
<?php
/**
* DefaultErrorTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Swagger Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* DefaultErrorTest Class Doc Comment
*
* @category Class */
// * @description test
/**
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class DefaultErrorTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "DefaultError"
*/
public function testDefaultError()
{
}
/**
* Test attribute "error"
*/
public function testPropertyError()
{
}
/**
* Test attribute "code"
*/
public function testPropertyCode()
{
}
}

View File

@ -0,0 +1,101 @@
<?php
/**
* ErrorTest
*
* PHP version 5
*
* @category Class
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
/**
* Swagger Petstore
*
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@swagger.io
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
*/
/**
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Please update the test case below to test the model.
*/
namespace Swagger\Client;
/**
* ErrorTest Class Doc Comment
*
* @category Class */
// * @description test
/**
* @package Swagger\Client
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
class ErrorTest extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test case
*/
public static function setUpBeforeClass()
{
}
/**
* Setup before running each test case
*/
public function setUp()
{
}
/**
* Clean up after running each test case
*/
public function tearDown()
{
}
/**
* Clean up after running all test cases
*/
public static function tearDownAfterClass()
{
}
/**
* Test "Error"
*/
public function testError()
{
}
/**
* Test attribute "error"
*/
public function testPropertyError()
{
}
/**
* Test attribute "code"
*/
public function testPropertyCode()
{
}
}

View File

@ -0,0 +1,62 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\FakeApi;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Model\Pet;
require_once __DIR__ . '/FakeHttpClient.php';
class AuthTest extends \PHPUnit_Framework_TestCase
{
public function testCustomApiKeyHeader()
{
$authConfig = new Configuration();
$authConfig->setApiKey('api_key', '123qwe');
$fakeHttpClient = new FakeHttpClient();
$api = new PetApi($fakeHttpClient, $authConfig);
$api->getPetById(123);
$headers = $fakeHttpClient->getLastRequest()->getHeaders();
$this->assertArrayHasKey('api_key', $headers);
$this->assertEquals(['123qwe'], $headers['api_key']);
}
public function testApiToken()
{
$authConfig = new 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']);
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Swagger\Client;
use GuzzleHttp\Client;
class ExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testNotFound()
{
$this->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();
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace Swagger\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
class FakeHttpClient implements ClientInterface
{
/** @var RequestInterface|null */
private $request;
/** @var ResponseInterface|null */
private $response;
/**
* @return null|RequestInterface
*/
public function getLastRequest()
{
return $this->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');
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace Swagger\Client;
class HeaderSelectorTest extends \PHPUnit_Framework_TestCase
{
public function testSelectingHeaders()
{
$selector = new HeaderSelector();
$headers = $selector->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);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace Swagger\Client;
require_once __DIR__ . '/FakeHttpClient.php';
class HeadersTest extends \PHPUnit_Framework_TestCase
{
/** @var FakeHttpClient */
private $fakeHttpClient;
public function setUp()
{
$this->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']);
}
}

View File

@ -0,0 +1,55 @@
<?php
namespace Swagger\Client;
use Swagger\Client\Api\FakeApi;
use Swagger\Client\Api\UserApi;
require_once __DIR__ . '/FakeHttpClient.php';
class ParametersTest extends \PHPUnit_Framework_TestCase
{
/** @var FakeHttpClient */
private $fakeHttpClient;
/** @var FakeApi */
private $fakeApi;
/** @var UserApi */
private $userApi;
public function setUp()
{
$this->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()));
// }
}

View File

@ -2,9 +2,16 @@
namespace Swagger\Client; namespace Swagger\Client;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Model\ApiResponse;
use Swagger\Client\Model\Pet;
class PetApiTest extends \PHPUnit_Framework_TestCase 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 // add a new pet (id 10005) to ensure the pet object is available for all the tests
public static function setUpBeforeClass() public static function setUpBeforeClass()
{ {
@ -12,264 +19,173 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
// returning a lot of data // returning a lot of data
ini_set('memory_limit', '256M'); 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 // enable debugging
//Configuration::$debug = true; //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
$new_pet_id = 10005; $newPetId = 10005;
$new_pet = new Model\Pet; $newPet = new Model\Pet;
$new_pet->setId($new_pet_id); $newPet->setId($newPetId);
$new_pet->setName("PHP Unit Test"); $newPet->setName("PHP Unit Test");
$new_pet->setPhotoUrls(array("http://test_php_unit_test.com")); $newPet->setPhotoUrls(["http://test_php_unit_test.com"]);
// new tag // new tag
$tag= new Model\Tag; $tag = new Model\Tag;
$tag->setId($new_pet_id); // use the same id as pet $tag->setId($newPetId); // use the same id as pet
$tag->setName("test php tag"); $tag->setName("test php tag");
// new category // new category
$category = new Model\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"); $category->setName("test php category");
$new_pet->setTags(array($tag)); $newPet->setTags(array($tag));
$new_pet->setCategory($category); $newPet->setCategory($category);
$config = new Configuration();
$petApi = new Api\PetApi(null, $config);
$pet_api = new Api\PetApi();
// add a new pet (model) // 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 setUp()
public function testApiClient()
{ {
// test selectHeaderAccept $this->api = new Api\PetApi();
$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());
} }
// test getPetById with a Pet object (id 10005)
public function testGetPetById() public function testGetPetById()
{ {
// initialize the API client without host $petId = 10005;
$pet_id = 10005; // ID of pet that needs to be fetched
$pet_api = new Api\PetApi(); $pet = $this->api->getPetById($petId);
$pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); $this->assertSame($pet->getId(), $petId);
// return Pet (model) $this->assertSame($pet->getName(), 'PHP Unit Test');
$response = $pet_api->getPetById($pet_id); $this->assertSame($pet->getPhotoUrls()[0], 'http://test_php_unit_test.com');
$this->assertSame($response->getId(), $pet_id); $this->assertSame($pet->getCategory()->getId(), $petId);
$this->assertSame($response->getName(), 'PHP Unit Test'); $this->assertSame($pet->getCategory()->getName(), 'test php category');
$this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com'); $this->assertSame($pet->getTags()[0]->getId(), $petId);
$this->assertSame($response->getCategory()->getId(), $pet_id); $this->assertSame($pet->getTags()[0]->getName(), 'test php tag');
$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');
} }
/** /**
* comment out as we've removed invalid endpoints from the spec, we'll introduce something * 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 * similar in the future when we've time to update the petstore server
* *
// test getPetById with a Pet object (id 10005) * // test getPetById with a Pet object (id 10005)
public function testGetPetByIdInObject() * public function testGetPetByIdInObject()
{ * {
// initialize the API client without host * // initialize the API client without host
$pet_id = 10005; // ID of pet that needs to be fetched * $pet_id = 10005; // ID of pet that needs to be fetched
$pet_api = new Api\PetApi(); * $pet_api = new Api\PetApi();
$pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); * $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555');
// return Pet (inline model) * // return Pet (inline model)
$response = $pet_api->getPetByIdInObject($pet_id); * $response = $pet_api->getPetByIdInObject($pet_id);
$this->assertInstanceOf('Swagger\Client\Model\InlineResponse200', $response); * $this->assertInstanceOf('Swagger\Client\Model\InlineResponse200', $response);
$this->assertSame($response->getId(), $pet_id); * $this->assertSame($response->getId(), $pet_id);
$this->assertSame($response->getName(), 'PHP Unit Test'); * $this->assertSame($response->getName(), 'PHP Unit Test');
$this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com'); * $this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com');
*
// category is type "object" * // category is type "object"
$this->assertInternalType('array', $response->getCategory()); * $this->assertInternalType('array', $response->getCategory());
$this->assertSame($response->getCategory()['id'], $pet_id); * $this->assertSame($response->getCategory()['id'], $pet_id);
$this->assertSame($response->getCategory()['name'], 'test php category'); * $this->assertSame($response->getCategory()['name'], 'test php category');
*
$this->assertSame($response->getTags()[0]->getId(), $pet_id); * $this->assertSame($response->getTags()[0]->getId(), $pet_id);
$this->assertSame($response->getTags()[0]->getName(), 'test php tag'); * $this->assertSame($response->getTags()[0]->getName(), 'test php tag');
} * }
*/ */
// test getPetByIdWithHttpInfo with a Pet object (id 10005) // test getPetByIdWithHttpInfo with a Pet object (id 10005)
public function testGetPetByIdWithHttpInfo() public function testGetPetByIdWithHttpInfo()
{ {
// initialize the API client without host // initialize the API client without host
$pet_id = 10005; // ID of pet that needs to be fetched $petId = 10005; // ID of pet that needs to be fetched
$pet_api = new Api\PetApi();
$pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); /** @var $pet Pet */
// return Pet (model) list($pet, $status_code, $response_headers) = $this->api->getPetByIdWithHttpInfo($petId);
list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); $this->assertSame($pet->getId(), $petId);
$this->assertSame($response->getId(), $pet_id); $this->assertSame($pet->getName(), 'PHP Unit Test');
$this->assertSame($response->getName(), 'PHP Unit Test'); $this->assertSame($pet->getCategory()->getId(), $petId);
$this->assertSame($response->getCategory()->getId(), $pet_id); $this->assertSame($pet->getCategory()->getName(), 'test php category');
$this->assertSame($response->getCategory()->getName(), 'test php category'); $this->assertSame($pet->getTags()[0]->getId(), $petId);
$this->assertSame($response->getTags()[0]->getId(), $pet_id); $this->assertSame($pet->getTags()[0]->getName(), 'test php tag');
$this->assertSame($response->getTags()[0]->getName(), 'test php tag');
$this->assertSame($status_code, 200); $this->assertSame($status_code, 200);
$this->assertSame($response_headers['Content-Type'], 'application/json'); $this->assertSame($response_headers['Content-Type'], ['application/json']);
} }
// test getPetByStatus and verify by the "id" of the response
public function testFindPetByStatus() public function testFindPetByStatus()
{ {
// initialize the API client $response = $this->api->findPetsByStatus('available');
$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->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" $this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet
foreach ($response as $_pet) { foreach ($response as $pet) {
$this->assertSame($_pet['status'], "available"); $this->assertSame($pet['status'], 'available');
} }
// test invalid status
$response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); $response = $this->api->findPetsByStatus('unknown_and_incorrect_status');
$this->assertSame(count($response), 0); // confirm no object returned $this->assertCount(0, $response);
} }
// test getPetsByTags and verify by the "id" of the response
public function testFindPetsByTags() public function testFindPetsByTags()
{ {
// initialize the API client $response = $this->api->findPetsByTags('test php tag');
$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->assertGreaterThan(0, count($response)); // at least one object returned
$this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet $this->assertSame(get_class($response[0]), Pet::class); // verify the object is Pet
// loop through result to ensure status is "available"
foreach ($response as $_pet) { foreach ($response as $pet) {
$this->assertSame($_pet['tags'][0]['name'], "test php tag"); $this->assertSame($pet['tags'][0]['name'], 'test php tag');
} }
// test invalid status
$response = $pet_api->findPetsByTags("unknown_and_incorrect_tag"); $response = $this->api->findPetsByTags('unknown_and_incorrect_tag');
$this->assertSame(count($response), 0); // confirm no object returned $this->assertCount(0, $response);
} }
// test updatePet (model/json)and verify by the "id" of the response
public function testUpdatePet() public function testUpdatePet()
{ {
// initialize the API client $petId = 10001;
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); $updatedPet = new Model\Pet;
$api_client = new ApiClient($config); $updatedPet->setId($petId);
$pet_id = 10001; // ID of pet that needs to be fetched $updatedPet->setName('updatePet');
$pet_api = new Api\PetApi($api_client); $updatedPet->setStatus('pending');
// create updated pet object $result = $this->api->updatePet($updatedPet);
$updated_pet = new Model\Pet; $this->assertNull($result);
$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);
// verify updated Pet // verify updated Pet
$response = $pet_api->getPetById($pet_id); $result = $this->api->getPetById($petId);
$this->assertSame($response->getId(), $pet_id); $this->assertSame($result->getId(), $petId);
$this->assertSame($response->getStatus(), 'pending'); $this->assertSame($result->getStatus(), 'pending');
$this->assertSame($response->getName(), 'updatePet'); $this->assertSame($result->getName(), 'updatePet');
} }
// test updatePetWithFormWithHttpInfo and verify by the "name" of the response // test updatePetWithFormWithHttpInfo and verify by the "name" of the response
public function testUpdatePetWithFormWithHttpInfo() public function testUpdatePetWithFormWithHttpInfo()
{ {
// initialize the API client $petId = 10001; // ID of pet that needs to be fetched
$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 Pet (form)
list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo( list($update_response, $status_code, $http_headers) = $this->api->updatePetWithFormWithHttpInfo(
$pet_id, $petId,
'update pet with form with http info' 'update pet with form with http info'
); );
// return nothing (void) // return nothing (void)
$this->assertNull($update_response); $this->assertNull($update_response);
$this->assertSame($status_code, 200); $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); $response = $this->api->getPetById($petId);
$this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getId(), $petId);
$this->assertSame($response->getName(), 'update pet with form with http info'); $this->assertSame($response->getName(), 'update pet with form with http info');
} }
// test updatePetWithForm and verify by the "name" and "status" of the response // test updatePetWithForm and verify by the "name" and "status" of the response
public function testUpdatePetWithForm() 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_id = 10001; // ID of pet that needs to be fetched
$pet_api = new Api\PetApi($api_client); $result = $this->api->updatePetWithForm($pet_id, 'update pet with form', 'sold');
// update Pet (form)
$update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold');
// return nothing (void) // return nothing (void)
$this->assertSame($update_response, null); $this->assertNull($result);
$response = $pet_api->getPetById($pet_id);
$response = $this->api->getPetById($pet_id);
$this->assertSame($response->getId(), $pet_id); $this->assertSame($response->getId(), $pet_id);
$this->assertSame($response->getName(), 'update pet with form'); $this->assertSame($response->getName(), 'update pet with form');
$this->assertSame($response->getStatus(), 'sold'); $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 // test addPet and verify by the "id" and "name" of the response
public function testAddPet() 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_id = 10005;
$new_pet = new Model\Pet; $newPet = new Model\Pet;
$new_pet->setId($new_pet_id); $newPet->setId($new_pet_id);
$new_pet->setName("PHP Unit Test 2"); $newPet->setName("PHP Unit Test 2");
$pet_api = new Api\PetApi($api_client);
// add a new pet (model) // add a new pet (model)
$add_response = $pet_api->addPet($new_pet); $add_response = $this->api->addPet($newPet);
// return nothing (void) // return nothing (void)
$this->assertSame($add_response, null); $this->assertNull($add_response);
// verify added Pet // 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->getId(), $new_pet_id);
$this->assertSame($response->getName(), 'PHP Unit Test 2'); $this->assertSame($response->getName(), 'PHP Unit Test 2');
} }
@ -340,33 +254,14 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
// test upload file // test upload file
public function testUploadFile() 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 // upload file
$pet_id = 10001; $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 // 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 * 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 * similar in the future when we've time to update the petstore server
@ -480,19 +375,21 @@ class PetApiTest extends \PHPUnit_Framework_TestCase
$this->assertSame('red', $animal->getColor()); $this->assertSame('red', $animal->getColor());
} }
// Ensure that API Classes pickup ApiClient defaults to prevent regressions of PR #4525 // Disabled as currently we don't have any endpoint that would return file
public function testHostOverride() // For testing I just replaced url and return type in Api method.
{ // public function testDownloadingLargeFile()
$orig_default = Configuration::getDefaultConfiguration(); // {
$new_default = new Configuration(); // $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()
// ]);
// }
$new_default->setHost("http://localhost/whatever");
Configuration::setDefaultConfiguration($new_default);
$pet_api = new Api\PetApi();
$pet_host = $pet_api->getApiClient()->getConfig()->getHost();
$this->assertSame($pet_host, $new_default->getHost());
Configuration::setDefaultConfiguration($orig_default); // Reset to original to prevent failure of other tests that rely on this state
}
} }

View File

@ -0,0 +1,93 @@
<?php
namespace Swagger\Client;
use GuzzleHttp\Psr7\Response;
use Swagger\Client\Api\PetApi;
use Swagger\Client\Model\Pet;
require_once __DIR__ . '/FakeHttpClient.php';
class ResponseTypesTest extends \PHPUnit_Framework_TestCase
{
/** @var PetApi */
private $api;
/** @var FakeHttpClient */
private $fakeHttpClient;
public function setUp()
{
$this->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);
}
}

View File

@ -2,50 +2,24 @@
namespace Swagger\Client; namespace Swagger\Client;
use Swagger\Client\Api\StoreApi;
class StoreApiTest extends \PHPUnit_Framework_TestCase 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 function setUp()
public static function setUpBeforeClass()
{ {
// for error reporting (need to run with php5.3 to get no warning) $this->api = new Api\StoreApi();
//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);
} }
// test get inventory
public function testGetInventory() public function testGetInventory()
{ {
// initialize the API client $result = $this->api->getInventory();
$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();
$this->assertInternalType("array", $get_response); $this->assertInternalType("array", $result);
$this->assertInternalType("int", $get_response['available']); $this->assertInternalType("int", $result['available']);
} }
/* /*
@ -55,15 +29,10 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase
// test get inventory // test get inventory
public function testGetInventoryInObject() public function testGetInventoryInObject()
{ {
// initialize the API client $result = $this->api->getInventoryInObject();
//$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();
$this->assertInternalType("array", $get_response); $this->assertInternalType("array", $result);
$this->assertInternalType("int", $get_response['available']); $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 * checking (not on empty array is true, same thing could happen
* with careless use of empty()). * with careless use of empty()).
*/ */
public function testEmptyArrayResponse() // public function testEmptyArrayResponse()
{ // {
// initialize the API client // // this call returns and empty array
$config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); // $response = $this->api->findPetsByStatus(array());
$apiClient = new ApiClient($config); //
$storeApi = new Api\PetApi($apiClient); // // make sure this is an array as we want it to be
// this call returns and empty array // $this->assertInternalType("array", $response);
$response = $storeApi->findPetsByStatus(array()); //
// // make sure the array is empty just in case the petstore
// make sure this is an array as we want it to be // // server changes its output
$this->assertInternalType("array", $response); // $this->assertEmpty($response);
// }
// make sure the array is empty just in case the petstore
// server changes its output
$this->assertEmpty($response);
}
} }

View File

@ -2,30 +2,29 @@
namespace Swagger\Client; namespace Swagger\Client;
use Swagger\Client\Api\UserApi;
class UserApiTest extends \PHPUnit_Framework_TestCase class UserApiTest extends \PHPUnit_Framework_TestCase
{ {
// add a new pet (id 10005) to ensure the pet object is available for all the tests /** @var UserApi*/
public static function setUpBeforeClass() private $api;
public function setUp()
{ {
// for error reporting (need to run with php5.3 to get no warning) $this->api = new Api\UserApi();
//ini_set('display_errors', 1);
//error_reporting(~0);
} }
// test login user // test login use
public function testLoginUser() public function testLoginUser()
{ {
// initialize the API client // 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 // login
$response = $user_api->loginUser("xxxxx", "yyyyyyyy"); $response = $this->api->loginUser('xxxxx', 'yyyyyyyy');
$this->assertInternalType("string", $response); $this->assertInternalType('string', $response);
$this->assertRegExp( $this->assertRegExp(
"/^logged in user session/", '/^logged in user session/',
$response, $response,
"response string starts with 'logged in user session'" "response string starts with 'logged in user session'"
); );

View File

@ -1,5 +1,5 @@
<?php <?php
require_once(__DIR__ . '/SwaggerClient-php/autoload.php'); require_once(__DIR__ . '/SwaggerClient-php/vendor/autoload.php');
// show error reporting // show error reporting
//ini_set('display_errors', 1); //ini_set('display_errors', 1);
@ -20,38 +20,39 @@ try {
//$api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); //$api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2');
//$api_client->getConfig()->addDefaultHeader("test1", "value1"); //$api_client->getConfig()->addDefaultHeader("test1", "value1");
//$pet_api = new Swagger\Client\PetAPI($api_client); //$pet_api = new Swagger\Client\PetAPI($api_client);
$pet_api = new Swagger\Client\Api\PetApi(); $config = new \Swagger\Client\Configuration();
$pet_api->getApiClient()->getConfig()->setTempFolderPath('/var/tmp/php/'); $petApi = new Swagger\Client\Api\PetApi(null, $config);
$config->setTempFolderPath('/var/tmp/php/');
// test default header // test default header
//$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); //$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903");
// return Pet (model) // return Pet (model)
$response = $pet_api->getPetById($petId); $response = $petApi->getPetById($petId);
// to test __toString() // to test __toString()
print ($response); print ($response);
// add pet (post json) // add pet (post json)
$new_pet_id = 10005; $newPetId = 10005;
$new_pet = new Swagger\Client\Model\Pet; $newPet = new Swagger\Client\Model\Pet;
$new_pet->setId($new_pet_id); $newPet->setId($newPetId);
$new_pet->setName("PHP Unit Test"); $newPet->setName("PHP Unit Test");
// new tag // new tag
$tag= new Swagger\Client\Model\Tag; $tag = new Swagger\Client\Model\Tag;
$tag->setId($new_pet_id); // use the same id as pet $tag->setId($newPetId); // use the same id as pet
//$tag->name = "test php tag"; //$tag->name = "test php tag";
// new category // new category
$category = new Swagger\Client\Model\Category; $category = new Swagger\Client\Model\Category;
$category->setId(10005); // use the same id as pet $category->setId(10005); // use the same id as pet
//$category->name = "test php category"; //$category->name = "test php category";
$new_pet->setTags(array($tag)); $newPet->setTags(array($tag));
$new_pet->setCategory($category); $newPet->setCategory($category);
$pet_api = new Swagger\Client\Api\PetApi(); $petApi = new Swagger\Client\Api\PetApi(null, $config);
// add a new pet (model) // add a new pet (model)
$add_response = $pet_api->addPet($new_pet); $add_response = $petApi->addPet($newPet);
// test upload file (should return exception) // 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) { } catch (Swagger\Client\ApiException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n"; echo 'Caught exception: ', $e->getMessage(), "\n";