Merge pull request #3968 from swagger-api/revert-3898-feature/php-improved-code-quality

Revert "[WIP] Improve PHP client emitted code quality"
This commit is contained in:
wing328 2016-10-12 16:08:22 +08:00 committed by GitHub
commit 3fe45622e7
8 changed files with 106 additions and 138 deletions

View File

@ -31,13 +31,13 @@ namespace {{invokerPackage}};
*/
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';
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
@ -58,7 +58,7 @@ class ApiClient
*
* @param Configuration $config config for this ApiClient
*/
public function __construct(Configuration $config = null)
public function __construct(\{{invokerPackage}}\Configuration $config = null)
{
if ($config === null) {
$config = Configuration::getDefaultConfiguration();
@ -91,7 +91,7 @@ class ApiClient
/**
* Get API key (with prefix if set)
*
* @param string $apiKeyIdentifier name of API key
* @param string $apiKeyIdentifier name of apikey
*
* @return string API key with the prefix
*/
@ -100,13 +100,14 @@ class ApiClient
$prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier);
$apiKey = $this->config->getApiKey($apiKeyIdentifier);
if ($apiKey === null) {
if (!isset($apiKey)) {
return null;
}
if (isset($prefix)) {
$keyWithPrefix = $prefix." ".$apiKey;
} else {
$keyWithPrefix = $apiKey;
if ($prefix !== null) {
$keyWithPrefix = $prefix.' '.$apiKey;
}
return $keyWithPrefix;
@ -118,21 +119,16 @@ class ApiClient
* @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|string $postData parameters to be placed in POST body
* @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 ApiException on a non 2xx response
* @throws \{{invokerPackage}}\ApiException on a non 2xx response
* @return mixed
*/
public function callApi(
$resourcePath,
$method,
array $queryParams,
$postData,
array $headerParams,
$responseType = null
) {
public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null)
{
$headers = [];
// construct the http header
@ -146,10 +142,10 @@ class ApiClient
}
// form data
if (is_array($postData) && in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) {
if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) {
$postData = http_build_query($postData);
} elseif ((is_object($postData) || is_array($postData)) && !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model
$postData = json_encode(ObjectSerializer::sanitizeForSerialization($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;
@ -165,12 +161,12 @@ class ApiClient
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// disable SSL verification, if needed
if ($this->config->isSSLVerification() === false) {
if ($this->config->getSSLVerification() === false) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
}
if ($queryParams !== null) {
if (!empty($queryParams)) {
$url = ($url . '?' . http_build_query($queryParams));
}
@ -180,16 +176,16 @@ class ApiClient
} elseif ($method === self::$HEAD) {
curl_setopt($curl, CURLOPT_NOBODY, true);
} elseif ($method === self::$OPTIONS) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, '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_CUSTOMREQUEST, "PATCH");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} elseif ($method === self::$PUT) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, '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_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} elseif ($method !== self::$GET) {
throw new ApiException('Method ' . $method . ' is not recognized.');
@ -200,12 +196,8 @@ class ApiClient
curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent());
// debugging for curl
if ($this->config->isDebug()) {
error_log(
'[DEBUG] HTTP Request body ~BEGIN~'.PHP_EOL.print_r($postData, true).PHP_EOL.'~END~'.PHP_EOL,
3,
$this->config->getDebugFile()
);
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'));
@ -218,59 +210,55 @@ class ApiClient
// Make the request
$response = curl_exec($curl);
$httpHeaderSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$httpHeader = $this->httpParseHeaders(substr($response, 0, $httpHeaderSize));
$httpBody = substr($response, $httpHeaderSize);
$responseInfo = curl_getinfo($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->isDebug()) {
error_log(
'[DEBUG] HTTP Response body ~BEGIN~'.PHP_EOL.print_r($httpBody, true).PHP_EOL.'~END~'.PHP_EOL,
3,
$this->config->getDebugFile()
);
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 ($responseInfo['http_code'] === 0) {
$curlErrorMessage = curl_error($curl);
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 ($curlErrorMessage !== '') {
$errorMessage = 'API call to '.$url.' failed: '.$curlErrorMessage;
if (!empty($curl_error_message)) {
$error_message = "API call to $url failed: $curl_error_message";
} else {
$errorMessage = 'API call to '.$url.' failed, but for an unknown reason. ' .
'This could happen if you are disconnected from the network.';
$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($errorMessage, 0, null, null);
$exception->setResponseObject($responseInfo);
$exception = new ApiException($error_message, 0, null, null);
$exception->setResponseObject($response_info);
throw $exception;
} elseif ($responseInfo['http_code'] >= 200 && $responseInfo['http_code'] <= 299) {
} 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 [$httpBody, $responseInfo['http_code'], $httpHeader];
return [$http_body, $response_info['http_code'], $http_header];
}
$data = json_decode($httpBody);
$data = json_decode($http_body);
if (json_last_error() > 0) { // if response is a string
$data = $httpBody;
$data = $http_body;
}
} else {
$data = json_decode($httpBody);
$data = json_decode($http_body);
if (json_last_error() > 0) { // if response is a string
$data = $httpBody;
$data = $http_body;
}
throw new ApiException(
'['.$responseInfo['http_code'].'] Error connecting to the API ('.$url.')',
$responseInfo['http_code'],
$httpHeader,
"[".$response_info['http_code']."] Error connecting to the API ($url)",
$response_info['http_code'],
$http_header,
$data
);
}
return [$data, $responseInfo['http_code'], $httpHeader];
return [$data, $response_info['http_code'], $http_header];
}
/**
@ -282,9 +270,9 @@ class ApiClient
*/
public function selectHeaderAccept($accept)
{
if (count($accept) === 0 || (count($accept) === 1 && $accept[0] === '')) {
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
return null;
} elseif (preg_grep('/application\\/json/i', $accept)) {
} elseif (preg_grep("/application\/json/i", $accept)) {
return 'application/json';
} else {
return implode(',', $accept);
@ -294,35 +282,35 @@ class ApiClient
/**
* Return the content type based on an array of content-type provided
*
* @param string[] $contentType Array for Content-type
* @param string[] $content_type Array fo content-type
*
* @return string Content-Type (e.g. application/json)
*/
public function selectHeaderContentType($contentType)
public function selectHeaderContentType($content_type)
{
if (count($contentType) === 0 || (count($contentType) === 1 && $contentType[0] === '')) {
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
return 'application/json';
} elseif (preg_grep('/application\\/json/i', $contentType)) {
} elseif (preg_grep("/application\/json/i", $content_type)) {
return 'application/json';
} else {
return implode(',', $contentType);
return implode(',', $content_type);
}
}
/**
* Return an array of HTTP response headers
*
* @param string $rawHeaders A string of raw HTTP response headers
* @param string $raw_headers A string of raw HTTP response headers
*
* @return string[] Array of HTTP response headers
* @return string[] Array of HTTP response heaers
*/
protected function httpParseHeaders($rawHeaders)
protected function httpParseHeaders($raw_headers)
{
// ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986
$headers = [];
$key = '';
foreach (explode("\n", $rawHeaders) as $h) {
foreach (explode("\n", $raw_headers) as $h) {
$h = explode(':', $h, 2);
if (isset($h[1])) {
@ -336,7 +324,7 @@ class ApiClient
$key = $h[0];
} else {
if (strpos($h[0], "\t") === 0) {
if (substr($h[0], 0, 1) === "\t") {
$headers[$key] .= "\r\n\t".trim($h[0]);
} elseif (!$key) {
$headers[0] = trim($h[0]);

View File

@ -62,7 +62,7 @@ class ApiException extends Exception
* @param string $responseHeaders HTTP response header
* @param mixed $responseBody HTTP body of the server response either as Json or string
*/
public function __construct($message = '', $code = 0, $responseHeaders = null, $responseBody = null)
public function __construct($message = "", $code = 0, $responseHeaders = null, $responseBody = null)
{
parent::__construct($message, $code);
$this->responseHeaders = $responseHeaders;
@ -90,7 +90,7 @@ class ApiException extends Exception
}
/**
* Sets the deserialized response object (during deserialization)
* Sets the deseralized response object (during deserialization)
*
* @param mixed $obj Deserialized response object
*
@ -102,7 +102,7 @@ class ApiException extends Exception
}
/**
* Gets the deserialized response object (during deserialization)
* Gets the deseralized response object (during deserialization)
*
* @return mixed the deserialized response object
*/

View File

@ -213,7 +213,7 @@ class ObjectSerializer
} elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int]
$inner = substr($class, 4, -1);
$deserialized = [];
if (strrpos($inner, ',') !== false) {
if (strrpos($inner, ",") !== false) {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
@ -254,9 +254,9 @@ class ObjectSerializer
} else {
$filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), '');
}
$deserialized = new \SplFileObject($filename, 'w');
$deserialized = new \SplFileObject($filename, "w");
$byte_written = $deserialized->fwrite($data);
if (Configuration::getDefaultConfiguration()->isDebug()) {
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());
}

View File

@ -21,6 +21,8 @@ namespace {{apiPackage}};
use \{{invokerPackage}}\ApiClient;
use \{{invokerPackage}}\ApiException;
use \{{invokerPackage}}\Configuration;
use \{{invokerPackage}}\ObjectSerializer;
/**
* {{classname}} Class Doc Comment
@ -36,28 +38,29 @@ use \{{invokerPackage}}\ApiException;
/**
* API Client
*
* @var ApiClient instance of the ApiClient
* @var \{{invokerPackage}}\ApiClient instance of the ApiClient
*/
protected $apiClient;
/**
* Constructor
*
* @param ApiClient|null $apiClient The API client to use
* @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use
*/
public function __construct(ApiClient $apiClient = null)
public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null)
{
if ($apiClient === null) {
$apiClient = new ApiClient();
$apiClient->getConfig()->setHost('{{basePath}}');
}
$this->setApiClient($apiClient);
$this->apiClient = $apiClient;
}
/**
* Get API client
*
* @return ApiClient get the API client
* @return \{{invokerPackage}}\ApiClient get the API client
*/
public function getApiClient()
{
@ -67,11 +70,11 @@ use \{{invokerPackage}}\ApiException;
/**
* Set the API client
*
* @param ApiClient $apiClient set the API client
* @param \{{invokerPackage}}\ApiClient $apiClient set the API client
*
* @return {{classname}}
*/
public function setApiClient(ApiClient $apiClient)
public function setApiClient(\{{invokerPackage}}\ApiClient $apiClient)
{
$this->apiClient = $apiClient;
return $this;
@ -112,7 +115,6 @@ use \{{invokerPackage}}\ApiException;
* @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}})
@ -164,7 +166,7 @@ use \{{invokerPackage}}\ApiException;
{{/hasValidation}}
{{/allParams}}
// parse inputs
$resourcePath = '{{path}}';
$resourcePath = "{{path}}";
$httpBody = '';
$queryParams = [];
$headerParams = [];
@ -206,14 +208,14 @@ use \{{invokerPackage}}\ApiException;
{{/collectionFormat}}
if (${{paramName}} !== null) {
$resourcePath = str_replace(
'{'.'{{baseName}}'.'}',
"{" . "{{baseName}}" . "}",
$this->apiClient->getSerializer()->toPathValue(${{paramName}}),
$resourcePath
);
}
{{/pathParams}}
// default format to json
$resourcePath = str_replace('{format}', 'json', $resourcePath);
$resourcePath = str_replace("{format}", "json", $resourcePath);
{{#formParams}}
// form params
@ -275,11 +277,12 @@ use \{{invokerPackage}}\ApiException;
$httpBody,
$headerParams,
{{#returnType}}
'{{returnType}}'
'{{returnType}}',
{{/returnType}}
{{^returnType}}
null
null,
{{/returnType}}
'{{path}}'
);
{{#returnType}}

View File

@ -19,6 +19,11 @@
namespace {{invokerPackage}};
use \{{invokerPackage}}\Configuration;
use \{{invokerPackage}}\ApiClient;
use \{{invokerPackage}}\ApiException;
use \{{invokerPackage}}\ObjectSerializer;
/**
* {{classname}}Test Class Doc Comment
*
@ -30,6 +35,7 @@ namespace {{invokerPackage}};
*/
{{#operations}}class {{classname}}Test extends \PHPUnit_Framework_TestCase
{
/**
* Setup before running any test cases
*/
@ -67,6 +73,7 @@ namespace {{invokerPackage}};
* Test case for {{{operationId}}}
*
* {{{summary}}}.
*
*/
public function test{{vendorExtensions.x-testOperationId}}()
{

View File

@ -31,10 +31,7 @@ namespace {{invokerPackage}};
*/
class Configuration
{
/**
* @var Configuration
*/
private static $defaultConfiguration;
private static $defaultConfiguration = null;
/**
* Associate array to store API key(s)
@ -97,7 +94,7 @@ class Configuration
*
* @var string
*/
protected $userAgent = '{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}';
protected $userAgent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{#artifactVersion}}{{{.}}}{{/artifactVersion}}{{^artifactVersion}}1.0.0{{/artifactVersion}}/php{{/httpUserAgent}}";
/**
* Debug switch (default set to false)
@ -264,7 +261,6 @@ class Configuration
* @param string $headerName header name (e.g. Token)
* @param string $headerValue header value (e.g. 1z8wp3)
*
* @throws \InvalidArgumentException
* @return Configuration
*/
public function addDefaultHeader($headerName, $headerValue)
@ -297,7 +293,6 @@ class Configuration
public function deleteDefaultHeader($headerName)
{
unset($this->defaultHeaders[$headerName]);
return $this;
}
/**
@ -328,7 +323,6 @@ class Configuration
*
* @param string $userAgent the user agent of the api client
*
* @throws \InvalidArgumentException
* @return Configuration
*/
public function setUserAgent($userAgent)
@ -356,7 +350,6 @@ class Configuration
*
* @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
*
* @throws \InvalidArgumentException
* @return Configuration
*/
public function setCurlTimeout($seconds)
@ -397,17 +390,6 @@ class Configuration
*
* @return bool
*/
public function isDebug()
{
return $this->debug;
}
/**
* Gets the debug flag
*
* @return bool
* @deprecated
*/
public function getDebug()
{
return $this->debug;
@ -477,17 +459,6 @@ class Configuration
*
* @return boolean True if the certificate should be validated, false otherwise
*/
public function isSSLVerification()
{
return $this->sslVerification;
}
/**
* Gets if SSL verification should be enabled or disabled
*
* @return boolean True if the certificate should be validated, false otherwise
* @deprecated
*/
public function getSSLVerification()
{
return $this->sslVerification;
@ -508,7 +479,7 @@ class Configuration
}
/**
* Sets the default configuration instance
* Sets the detault configuration instance
*
* @param Configuration $config An instance of the Configuration Object
*

View File

@ -23,7 +23,6 @@
namespace {{modelPackage}};
use \ArrayAccess;
use \{{invokerPackage}}\ObjectSerializer;
/**
* {{classname}} Class Doc Comment

View File

@ -183,7 +183,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple
* validate all the properties in the model
* return true if all passed
*
* @return bool True if all properties are valid
* @return bool True if all properteis are valid
*/
public function valid()
{
@ -365,9 +365,9 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this));
}
}