Files
openapi-generator/modules/swagger-codegen/src/main/resources/php/api.mustache
baartosz 2315ef2a7f 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
2017-04-03 15:47:57 +08:00

359 lines
13 KiB
Plaintext

<?php
/**
* {{classname}}
* 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 {{apiPackage}};
use GuzzleHttp\Client;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use {{invokerPackage}}\ApiException;
use {{invokerPackage}}\Configuration;
use {{invokerPackage}}\HeaderSelector;
use {{invokerPackage}}\ObjectSerializer;
/**
* {{classname}} Class Doc Comment
*
* @category Class
* @package {{invokerPackage}}
* @author Swagger Codegen team
* @link https://github.com/swagger-api/swagger-codegen
*/
{{#operations}}class {{classname}}
{
/**
* @var ClientInterface
*/
protected $client;
/**
* @var Configuration
*/
protected $config;
/**
* @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();
}
/**
* @return Configuration
*/
public function getConfig()
{
return $this->config;
}
{{#operation}}
/**
* Operation {{{operationId}}}
*
* {{{summary}}}
*
{{#description}}
* {{.}}
*
{{/description}}
{{#allParams}}
* @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @throws \{{invokerPackage}}\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
public function {{operationId}}({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{
{{#returnType}}list($response) = {{/returnType}}$this->{{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}}
return $response;{{/returnType}}
}
/**
* Operation {{{operationId}}}WithHttpInfo
*
* {{{summary}}}
*
{{#description}}
* {{.}}
*
{{/description}}
{{#allParams}}
* @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @throws \{{invokerPackage}}\ApiException on non-2xx response
* @throws \InvalidArgumentException
* @return array of {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings)
*/
public function {{operationId}}WithHttpInfo({{#allParams}}${{paramName}}{{^required}} = null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{
{{#allParams}}
{{#required}}
// verify the required parameter '{{paramName}}' is set
if (${{paramName}} === null) {
throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{operationId}}');
}
{{/required}}
{{#hasValidation}}
{{#maxLength}}
if ({{^required}}${{paramName}} !== null && {{/required}}strlen(${{paramName}}) > {{maxLength}}) {
throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.');
}
{{/maxLength}}
{{#minLength}}
if ({{^required}}${{paramName}} !== null && {{/required}}strlen(${{paramName}}) < {{minLength}}) {
throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.');
}
{{/minLength}}
{{#maximum}}
if ({{^required}}${{paramName}} !== null && {{/required}}${{paramName}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) {
throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.');
}
{{/maximum}}
{{#minimum}}
if ({{^required}}${{paramName}} !== null && {{/required}}${{paramName}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) {
throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.');
}
{{/minimum}}
{{#pattern}}
if ({{^required}}${{paramName}} !== null && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) {
throw new \InvalidArgumentException("invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}.");
}
{{/pattern}}
{{#maxItems}}
if ({{^required}}${{paramName}} !== null && {{/required}}count(${{paramName}}) > {{maxItems}}) {
throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.');
}
{{/maxItems}}
{{#minItems}}
if ({{^required}}${{paramName}} !== null && {{/required}}count(${{paramName}}) < {{minItems}}) {
throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.');
}
{{/minItems}}
{{/hasValidation}}
{{/allParams}}
$resourcePath = '{{{path}}}';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
$returnType = '{{returnType}}';
{{#queryParams}}
// query params
{{#collectionFormat}}
if (is_array(${{paramName}})) {
${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}', true);
}
{{/collectionFormat}}
if (${{paramName}} !== null) {
$queryParams['{{baseName}}'] = ObjectSerializer::toQueryValue(${{paramName}});
}
{{/queryParams}}
{{#headerParams}}
// header params
{{#collectionFormat}}
if (is_array(${{paramName}})) {
${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}');
}
{{/collectionFormat}}
if (${{paramName}} !== null) {
$headerParams['{{baseName}}'] = ObjectSerializer::toHeaderValue(${{paramName}});
}
{{/headerParams}}
{{#pathParams}}
// path params
{{#collectionFormat}}
if (is_array(${{paramName}})) {
${{paramName}} = ObjectSerializer::serializeCollection(${{paramName}}, '{{collectionFormat}}');
}
{{/collectionFormat}}
if (${{paramName}} !== null) {
$resourcePath = str_replace('{' . '{{baseName}}' . '}', ObjectSerializer::toPathValue(${{paramName}}), $resourcePath);
}
{{/pathParams}}
{{#formParams}}
// form params
if (${{paramName}} !== null) {
{{#isFile}}
$multipart = true;
$formParams['file'] = \GuzzleHttp\Psr7\try_fopen(ObjectSerializer::toFormValue($file), 'rb');
{{/isFile}}
{{^isFile}}
$formParams['{{baseName}}'] = ObjectSerializer::toFormValue(${{paramName}});
{{/isFile}}
}
{{/formParams}}
{{#bodyParams}}// body params
$_tempBody = null;
if (isset(${{paramName}})) {
$_tempBody = ${{paramName}};
}
{{/bodyParams}}
// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} 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(
[{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]
);
} else {
$headers = $this->headerSelector->selectHeaders(
[{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}],
[{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]
);
}
{{#authMethods}}
{{#isApiKey}}
// this endpoint requires API key authentication
$apiKey = $this->config->getApiKeyWithPrefix('{{keyParamName}}');
if ($apiKey !== null) {
{{#isKeyInHeader}}$headers['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}}
}
{{/isApiKey}}
{{#isBasic}}
// this endpoint requires HTTP basic authentication
if ($this->config->getUsername() !== null || $this->config->getPassword() !== null) {
$headers['Authorization'] = 'Basic ' . base64_encode($this->config->getUsername() . ":" . $this->config->getPassword());
}
{{/isBasic}}
{{#isOAuth}}
// this endpoint requires OAuth (access token)
if ($this->config->getAccessToken() !== null) {
$headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
}
{{/isOAuth}}
{{/authMethods}}
$query = \GuzzleHttp\Psr7\build_query($queryParams);
$url = $this->config->getHost() . $resourcePath . ($query ? '?' . $query : '');
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$request = new Request(
'{{httpMethod}}',
$url,
$headers,
$httpBody
);
try {
try {
$response = $this->client->send($request);
} catch (RequestException $e) {
throw new ApiException(
"[{$e->getCode()}] {$e->getMessage()}",
$e->getCode(),
$e->getResponse() ? $e->getResponse()->getHeaders() : null
);
}
$statusCode = $response->getStatusCode();
if ($statusCode < 200 || $statusCode > 299) {
throw new ApiException(
"[$statusCode] Error connecting to the API ($url)",
$statusCode,
$response->getHeaders(),
$response->getBody()
);
}
{{#returnType}}
$responseBody = $response->getBody();
if ($returnType === '\SplFileObject') {
$content = $responseBody; //stream goes to serializer
} else {
$content = $responseBody->getContents();
if ($returnType !== 'string') {
$content = json_decode($content);
}
}
return [
ObjectSerializer::deserialize($content, $returnType, []),
$response->getStatusCode(),
$response->getHeaders()
];
{{/returnType}}
{{^returnType}}
return [null, $statusCode, $response->getHeaders()];
{{/returnType}}
} catch (ApiException $e) {
switch ($e->getCode()) {
{{#responses}}
{{#dataType}}
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}}
$data = ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders());
$e->setResponseObject($data);
break;
{{/dataType}}
{{/responses}}
}
throw $e;
}
}
{{/operation}}
}
{{/operations}}