[PHP] Improve generated codestyle

This commit is contained in:
Arne Jørgensen 2016-05-14 12:56:11 +02:00
parent b3a335f97b
commit cc395fdf63
10 changed files with 87 additions and 57 deletions

View File

@ -3,6 +3,7 @@ package io.swagger.codegen.languages;
import io.swagger.codegen.CliOption; import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenProperty;
import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenType;
@ -13,6 +14,7 @@ import io.swagger.models.properties.*;
import java.io.File; import java.io.File;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.HashSet; import java.util.HashSet;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -626,4 +628,14 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
// process enum in models // process enum in models
return postProcessModelsEnum(objs); return postProcessModelsEnum(objs);
} }
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
op.vendorExtensions.put("x-testOperationId", camelize(op.operationId));
}
return objs;
}
} }

View File

@ -237,7 +237,7 @@ class ApiClient
// Handle the response // Handle the response
if ($response_info['http_code'] == 0) { if ($response_info['http_code'] == 0) {
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
} elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) {
// return raw body if response is a file // return raw body if response is a file
if ($responseType == '\SplFileObject' || $responseType == 'string') { if ($responseType == '\SplFileObject' || $responseType == 'string') {
return array($http_body, $response_info['http_code'], $http_header); return array($http_body, $response_info['http_code'], $http_header);
@ -255,7 +255,9 @@ class ApiClient
throw new ApiException( throw new ApiException(
"[".$response_info['http_code']."] Error connecting to the API ($url)", "[".$response_info['http_code']."] Error connecting to the API ($url)",
$response_info['http_code'], $http_header, $data $response_info['http_code'],
$http_header,
$data
); );
} }
return array($data, $response_info['http_code'], $http_header); return array($data, $response_info['http_code'], $http_header);
@ -310,31 +312,26 @@ class ApiClient
$headers = array(); $headers = array();
$key = ''; $key = '';
foreach(explode("\n", $raw_headers) as $h) foreach (explode("\n", $raw_headers) as $h) {
{
$h = explode(':', $h, 2); $h = explode(':', $h, 2);
if (isset($h[1])) if (isset($h[1])) {
{ if (!isset($headers[$h[0]])) {
if (!isset($headers[$h[0]]))
$headers[$h[0]] = trim($h[1]); $headers[$h[0]] = trim($h[1]);
elseif (is_array($headers[$h[0]])) } elseif (is_array($headers[$h[0]])) {
{
$headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1])));
} } else {
else
{
$headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1])));
} }
$key = $h[0]; $key = $h[0];
} } else {
else if (substr($h[0], 0, 1) == "\t") {
{
if (substr($h[0], 0, 1) == "\t")
$headers[$key] .= "\r\n\t".trim($h[0]); $headers[$key] .= "\r\n\t".trim($h[0]);
elseif (!$key) } elseif (!$key) {
$headers[0] = trim($h[0]);trim($h[0]); $headers[0] = trim($h[0]);
}
trim($h[0]);
} }
} }

View File

@ -75,7 +75,7 @@ class ApiException extends Exception
* @param string $responseHeaders HTTP response header * @param string $responseHeaders HTTP response header
* @param mixed $responseBody HTTP body of the server response either as Json or string * @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); parent::__construct($message, $code);
$this->responseHeaders = $responseHeaders; $this->responseHeaders = $responseHeaders;

View File

@ -185,7 +185,7 @@ class ObjectSerializer
* *
* @return string * @return string
*/ */
public function serializeCollection(array $collection, $collectionFormat, $allowCollectionFormatMulti=false) public 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
@ -219,7 +219,7 @@ class ObjectSerializer
* *
* @return object an instance of $class * @return object an instance of $class
*/ */
public static function deserialize($data, $class, $httpHeaders=null, $discriminator=null) public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null)
{ {
if (null === $data) { if (null === $data) {
return null; return null;
@ -261,7 +261,8 @@ class ObjectSerializer
return $data; return $data;
} elseif ($class === '\SplFileObject') { } elseif ($class === '\SplFileObject') {
// determine file name // determine file name
if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { if (array_key_exists('Content-Disposition', $httpHeaders) &&
preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) {
$filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]);
} else { } else {
$filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), '');
@ -274,7 +275,6 @@ class ObjectSerializer
} }
return $deserialized; return $deserialized;
} 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.
if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) {

View File

@ -62,7 +62,7 @@ use \{{invokerPackage}}\ObjectSerializer;
* *
* @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use
*/ */
function __construct(\{{invokerPackage}}\ApiClient $apiClient = null) public function __construct(\{{invokerPackage}}\ApiClient $apiClient = null)
{ {
if ($apiClient == null) { if ($apiClient == null) {
$apiClient = new ApiClient(); $apiClient = new ApiClient();
@ -99,7 +99,7 @@ use \{{invokerPackage}}\ObjectSerializer;
/** /**
* Operation {{{operationId}}} * Operation {{{operationId}}}
* *
* {{{summary}}} * {{{summary}}}.
* *
{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * {{/allParams}} *
@ -116,7 +116,7 @@ use \{{invokerPackage}}\ObjectSerializer;
/** /**
* Operation {{{operationId}}}WithHttpInfo * Operation {{{operationId}}}WithHttpInfo
* *
* {{{summary}}} * {{{summary}}}.
* *
{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}} * {{/allParams}} *
@ -251,9 +251,12 @@ use \{{invokerPackage}}\ObjectSerializer;
// make the API Call // make the API Call
try { try {
list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( list($response, $statusCode, $httpHeader) = $this->apiClient->callApi(
$resourcePath, '{{httpMethod}}', $resourcePath,
$queryParams, $httpBody, '{{httpMethod}}',
$headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} $queryParams,
$httpBody,
$headerParams{{#returnType}},
'{{returnType}}'{{/returnType}}
); );
{{#returnType}} {{#returnType}}
if (!$response) { if (!$response) {
@ -261,15 +264,20 @@ use \{{invokerPackage}}\ObjectSerializer;
} }
return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader); return array($this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader);
{{/returnType}}{{^returnType}} {{/returnType}}
{{^returnType}}
return array(null, $statusCode, $httpHeader); return array(null, $statusCode, $httpHeader);
{{/returnType}} {{/returnType}}
} catch (ApiException $e) { } catch (ApiException $e) {
switch ($e->getCode()) { {{#responses}}{{#dataType}} switch ($e->getCode()) {
{{#responses}}
{{#dataType}}
{{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}} {{^isWildcard}}case {{code}}:{{/isWildcard}}{{#isWildcard}}default:{{/isWildcard}}
$data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders());
$e->setResponseObject($data); $e->setResponseObject($data);
break;{{/dataType}}{{/responses}} break;
{{/dataType}}
{{/responses}}
} }
throw $e; throw $e;

View File

@ -70,10 +70,10 @@ use \{{invokerPackage}}\ObjectSerializer;
/** /**
* Test case for {{{operationId}}} * Test case for {{{operationId}}}
* *
* {{{summary}}} * {{{summary}}}.
* *
*/ */
public function test_{{operationId}}() public function test{{vendorExtensions.x-testOperationId}}()
{ {
} }

View File

@ -47,7 +47,7 @@ namespace {{invokerPackage}};
class Configuration class Configuration
{ {
private static $_defaultConfiguration = null; private static $defaultConfiguration = null;
/** /**
* Associate array to store API key(s) * Associate array to store API key(s)
@ -487,11 +487,11 @@ class Configuration
*/ */
public static function getDefaultConfiguration() public static function getDefaultConfiguration()
{ {
if (self::$_defaultConfiguration == null) { if (self::$defaultConfiguration == null) {
self::$_defaultConfiguration = new Configuration(); self::$defaultConfiguration = new Configuration();
} }
return self::$_defaultConfiguration; return self::$defaultConfiguration;
} }
/** /**
@ -503,7 +503,7 @@ class Configuration
*/ */
public static function setDefaultConfiguration(Configuration $config) public static function setDefaultConfiguration(Configuration $config)
{ {
self::$_defaultConfiguration = $config; self::$defaultConfiguration = $config;
} }
/** /**
@ -522,5 +522,4 @@ class Configuration
return $report; return $report;
} }
} }

View File

@ -41,7 +41,9 @@ use \ArrayAccess;
* {{classname}} Class Doc Comment * {{classname}} Class Doc Comment
* *
* @category Class * @category Class
{{#description}}
* @description {{description}} * @description {{description}}
{{/description}}
* @package {{invokerPackage}} * @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen * @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
@ -53,18 +55,19 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple
* The original name of the model. * The original name of the model.
* @var string * @var string
*/ */
static $swaggerModelName = '{{name}}'; protected static $swaggerModelName = '{{name}}';
/** /**
* Array of property to type mappings. Used for (de)serialization * Array of property to type mappings. Used for (de)serialization
* @var string[] * @var string[]
*/ */
static $swaggerTypes = array( protected static $swaggerTypes = array(
{{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}},
{{/hasMore}}{{/vars}} {{/hasMore}}{{/vars}}
); );
static function swaggerTypes() { public static function swaggerTypes()
{
return self::$swaggerTypes{{#parentSchema}} + parent::swaggerTypes(){{/parentSchema}}; return self::$swaggerTypes{{#parentSchema}} + parent::swaggerTypes(){{/parentSchema}};
} }
@ -72,12 +75,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple
* Array of attributes where the key is the local name, and the value is the original name * Array of attributes where the key is the local name, and the value is the original name
* @var string[] * @var string[]
*/ */
static $attributeMap = array( protected static $attributeMap = array(
{{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}},
{{/hasMore}}{{/vars}} {{/hasMore}}{{/vars}}
); );
static function attributeMap() { public static function attributeMap()
{
return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap; return {{#parentSchema}}parent::attributeMap() + {{/parentSchema}}self::$attributeMap;
} }
@ -85,12 +89,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple
* Array of attributes to setter functions (for deserialization of responses) * Array of attributes to setter functions (for deserialization of responses)
* @var string[] * @var string[]
*/ */
static $setters = array( protected static $setters = array(
{{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}},
{{/hasMore}}{{/vars}} {{/hasMore}}{{/vars}}
); );
static function setters() { public static function setters()
{
return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters; return {{#parentSchema}}parent::setters() + {{/parentSchema}}self::$setters;
} }
@ -98,12 +103,12 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple
* Array of attributes to getter functions (for serialization of requests) * Array of attributes to getter functions (for serialization of requests)
* @var string[] * @var string[]
*/ */
static $getters = array( protected static $getters = array(
{{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}},
{{/hasMore}}{{/vars}} {{/hasMore}}{{/vars}}
); );
static function getters() public static function getters()
{ {
return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters; return {{#parentSchema}}parent::getters() + {{/parentSchema}}self::$getters;
} }
@ -267,7 +272,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple
/** /**
* Sets {{name}} * Sets {{name}}
* @param {{datatype}} ${{name}} {{#description}}{{{description}}}{{/description}} * @param {{datatype}} ${{name}}{{#description}} {{{description}}}{{/description}}
* @return $this * @return $this
*/ */
public function {{setter}}(${{name}}) public function {{setter}}(${{name}})

View File

@ -39,7 +39,7 @@ namespace {{modelPackage}};
* {{classname}}Test Class Doc Comment * {{classname}}Test Class Doc Comment
* *
* @category Class * @category Class
* @description {{description}} * @description {{#description}}{{description}}{{/description}}{{^description}}{{classname}}{{/description}}
* @package {{invokerPackage}} * @package {{invokerPackage}}
* @author http://github.com/swagger-api/swagger-codegen * @author http://github.com/swagger-api/swagger-codegen
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
@ -65,13 +65,12 @@ class {{classname}}Test extends \PHPUnit_Framework_TestCase
} }
/** /**
* Test {{classname}} * Test "{{classname}}"
*/ */
public function test{{classname}}() public function test{{classname}}()
{ {
} }
} }
{{/model}} {{/model}}
{{/models}} {{/models}}

View File

@ -0,0 +1,10 @@
<?xml version="1.0"?>
<!-- See http://pear.php.net/manual/en/package.php.php-codesniffer.annotated-ruleset.php -->
<ruleset name="PhpSwaggerCodegen">
<description>Arnes Drupal code checker</description>
<rule ref="PSR2" />
<rule ref="Generic.Files.LineLength">
<exclude-pattern>*</exclude-pattern>
</rule>
</ruleset>