From dee0948e3e24a399d650c216e0408c8b4c6d5396 Mon Sep 17 00:00:00 2001 From: Ron Date: Mon, 15 Jun 2015 13:19:56 +0300 Subject: [PATCH 01/39] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cace22c92e9..f2c44ebf718 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ Supported config options can be different per language. Running `config-help -l {lang}` will show available options. ``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jarr config-help -l java +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar config-help -l java ``` Output From 5f1df9e093eaf7b584c98879b4e05dcf1ac8c58f Mon Sep 17 00:00:00 2001 From: Shane Oatman Date: Tue, 16 Jun 2015 12:12:17 -0700 Subject: [PATCH 02/39] Updates to csharp model template to support inheritance --- .../src/main/resources/csharp/model.mustache | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index ce0e62de192..111c98993a2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -13,7 +13,7 @@ namespace {{package}} { /// {{description}} /// [DataContract] - public class {{classname}} { + public class {{classname}}{{#parent}} : {{{parent}}}{{/parent}} { {{#vars}} {{#description}}/* {{{description}}} */{{/description}} [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] @@ -39,11 +39,11 @@ namespace {{package}} { /// Get the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() { + public {{#parent}} new {{/parent}}string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } {{/model}} {{/models}} -} +} \ No newline at end of file From 4ef34680cd53cb2b047bc2126a72f977001651fc Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Thu, 18 Jun 2015 10:30:53 -0700 Subject: [PATCH 03/39] renaming to ApiClient.mustache --- .../main/resources/php/{APIClient.mustache => ApiClient.mustache} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename modules/swagger-codegen/src/main/resources/php/{APIClient.mustache => ApiClient.mustache} (100%) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/php/APIClient.mustache rename to modules/swagger-codegen/src/main/resources/php/ApiClient.mustache From 4495774fd5b0b59ea4e5d98e28482a47499b8a06 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Thu, 18 Jun 2015 15:08:45 -0700 Subject: [PATCH 04/39] proper autoloader and move generated files to PSR-4 compliant locations --- .../codegen/languages/PhpClientCodegen.java | 95 ++++++++++++++++--- .../src/main/resources/php/autoload.mustache | 29 ++++++ .../src/main/resources/php/require.mustache | 13 --- 3 files changed, 113 insertions(+), 24 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/php/autoload.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/php/require.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 10c03fe4381..af4867108a8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -1,5 +1,6 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -12,22 +13,25 @@ import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.Map; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; + protected String rootNamespace; + protected String invokerNamespace; + protected String modelNamespace; + protected String apiNamespace; public PhpClientCodegen() { super(); - invokerPackage = camelize("SwaggerClient"); - - String packagePath = invokerPackage + "-php"; - - modelPackage = packagePath + "/lib/models"; - apiPackage = packagePath + "/lib"; + rootNamespace = "Swagger"; + invokerPackage = "Client"; + modelPackage = "Models"; + apiPackage = "Api"; outputFolder = "generated-code/php"; modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); @@ -78,11 +82,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("list", "array"); typeMapping.put("object", "object"); - supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json")); - supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php")); - supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php")); + cliOptions.add(new CliOption("rootNamespace", "root namespace from which other namespaces derive")); + cliOptions.add(new CliOption("invokerPackage", "namespace for core, non-api-specific classes")); } public CodegenType getTag() { @@ -97,6 +98,38 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return "Generates a PHP client library."; } + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("invokerPackage")) { + this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); + } + + if (additionalProperties.containsKey("rootNamespace")) { + this.setRootNamespace((String) additionalProperties.get("rootNamespace")); + } + + setNamespacesFromPackages(); + prefixPackages(); + + supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage.replace('/', File.separatorChar), "Configuration.php")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerPackage.replace('/', File.separatorChar), "ApiClient.php")); + supportingFiles.add(new SupportingFile("ApiException.mustache", invokerPackage.replace('/', File.separatorChar), "ApiException.php")); + supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); + supportingFiles.add(new SupportingFile("autoload.mustache", "", "autoload.php")); + } + + protected String getSrcDir(String packageName) { + return rootNamespace + "/src/" + packageName; + } + + protected void prefixPackages() { + setApiPackage(getSrcDir(apiPackage)); + setInvokerPackage(getSrcDir(invokerPackage)); + setModelPackage(getSrcDir(modelPackage)); + } + @Override public String escapeReservedWord(String name) { return "_" + name; @@ -149,6 +182,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return "null"; } + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setRootNamespace(String rootNamespace) { + this.rootNamespace = rootNamespace; + } @Override public String toVarName(String name) { @@ -187,4 +227,37 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelName(name); } + public String toNamespace(String packageName) { + return rootNamespace + "\\" + packageName.replace('/', '\\').replace('.', '\\'); + } + + protected void setNamespacesFromPackages() { + invokerNamespace = toNamespace(invokerPackage); + apiNamespace = toNamespace(apiPackage); + modelNamespace = toNamespace(modelPackage); + } + + @Override + public Map postProcessModels(Map objs) { + return addNamespaces(super.postProcessModels(objs)); + } + + @Override + public Map postProcessOperations(Map objs) { + return addNamespaces(super.postProcessOperations(objs)); + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + return addNamespaces(super.postProcessSupportingFileData(objs)); + } + + protected Map addNamespaces(Map objs) { + objs.put("rootNamespace", rootNamespace); + objs.put("invokerNamespace", invokerNamespace); + objs.put("apiNamespace", apiNamespace); + objs.put("modelNamespace", modelNamespace); + + return objs; + } } diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache new file mode 100644 index 00000000000..5ed11c11041 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -0,0 +1,29 @@ + From bb113229194935651573c48030d1dec94c1e7c62 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Thu, 18 Jun 2015 15:41:12 -0700 Subject: [PATCH 05/39] use proper namespaces, getters/setters, and phpdocs --- .../src/main/resources/php/ApiClient.mustache | 2 +- .../main/resources/php/ApiException.mustache | 2 +- .../src/main/resources/php/api.mustache | 10 +++-- .../src/main/resources/php/autoload.mustache | 40 +++++++++---------- .../main/resources/php/configuration.mustache | 2 +- .../src/main/resources/php/model.mustache | 31 ++++++++++---- 6 files changed, 54 insertions(+), 33 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 6356143f914..564bc1ddd66 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -15,7 +15,7 @@ * limitations under the License. */ -namespace {{invokerPackage}}; +namespace {{invokerNamespace}}; class ApiClient { diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index b66c3a51eb7..096979c11cb 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -15,7 +15,7 @@ * limitations under the License. */ -namespace {{invokerPackage}}; +namespace {{invokerNamespace}}; use \Exception; diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 12d2eb80744..5d84e0541da 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -20,11 +20,17 @@ * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. */ -namespace {{invokerPackage}}; +namespace {{apiNamespace}}; + +use {{invokerNamespace}}\Configuration; +use {{invokerNamespace}}\ApiClient; {{#operations}} class {{classname}} { + /** @var ApiClient */ + private $apiClient; + function __construct($apiClient = null) { if (null === $apiClient) { if (Configuration::$apiClient === null) { @@ -38,8 +44,6 @@ class {{classname}} { } } - private $apiClient; // instance of the ApiClient - /** * get the API client */ diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache index 5ed11c11041..41e4790da22 100644 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -1,29 +1,29 @@ {{name}} = $data["{{name}}"];{{#hasMore}} {{/hasMore}}{{/vars}} } + {{#vars}} + /** + * get {{name}} + * @return {{datatype}} + */ + public function {{getter}}() { + return $this->{{name}}; + } + /** + * set {{name}} + * @param {{datatype}} ${{name}} + */ + public function {{setter}}(${{name}}) { + $this->{{name}} = ${{name}}; + } + {{/vars}} public function offsetExists($offset) { return isset($this->$offset); } From f9f58596b8ab3cb840513ebd35efbdf730c688d3 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Thu, 18 Jun 2015 16:51:24 -0700 Subject: [PATCH 06/39] account for return type where the response type is in a list container, and properly import models into operations --- .../codegen/languages/PhpClientCodegen.java | 29 ++++++++++++++++++- .../src/main/resources/php/api.mustache | 9 ++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index af4867108a8..ad9ca3aa9b1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -10,9 +10,12 @@ import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @@ -244,7 +247,31 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public Map postProcessOperations(Map objs) { - return addNamespaces(super.postProcessOperations(objs)); + objs = addNamespaces(super.postProcessOperations(objs)); + + if (objs.containsKey("imports")) { + List> imports = new ArrayList>(); + LinkedHashMap newImport; + String currentImport; + String modelName; + + for (Map importMap : (List>) objs.get("imports")) { + currentImport = importMap.get("import"); + modelName = currentImport.replace(modelPackage + ".", ""); + + if (reservedWords.contains(modelName)) { + continue; + } + + newImport = new LinkedHashMap(); + newImport.put("import", modelNamespace + "\\" + modelName); + imports.add(newImport); + } + + objs.put("imports", imports); + } + + return objs; } @Override diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 5d84e0541da..5798ef6f882 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -25,6 +25,10 @@ namespace {{apiNamespace}}; use {{invokerNamespace}}\Configuration; use {{invokerNamespace}}\ApiClient; +{{#imports}} +use {{{import}}}; +{{/imports}} + {{#operations}} class {{classname}} { @@ -65,7 +69,7 @@ class {{classname}} { * {{{summary}}} * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +{{/allParams}} * @return {{#returnType}}{{#isListContainer}}{{returnBaseType}}[]{{/isListContainer}}{{^isListContainer}}{{{returnType}}}{{/isListContainer}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} @@ -136,6 +140,5 @@ class {{classname}} { return $responseObject;{{/returnType}} } {{/operation}} -{{newline}} -{{/operations}} } +{{/operations}} From 5c409884b95bd4bbdae756d03083c8a90d71038a Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Fri, 19 Jun 2015 10:31:05 -0700 Subject: [PATCH 07/39] make setters fluent --- modules/swagger-codegen/src/main/resources/php/model.mustache | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 7f78311ade4..9e50edcb567 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -62,9 +62,11 @@ class {{classname}} implements ArrayAccess { /** * set {{name}} * @param {{datatype}} ${{name}} + * @return $this */ public function {{setter}}(${{name}}) { $this->{{name}} = ${{name}}; + return $this; } {{/vars}} public function offsetExists($offset) { From 3252dd0d189f692ec8c49cf8b1eb3e434388a8d8 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Fri, 19 Jun 2015 10:32:38 -0700 Subject: [PATCH 08/39] check for null array in constructor --- .../swagger-codegen/src/main/resources/php/model.mustache | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 9e50edcb567..86dafc99d99 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -47,8 +47,10 @@ class {{classname}} implements ArrayAccess { public ${{name}}; {{/vars}} public function __construct(array $data = null) { - {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} - {{/hasMore}}{{/vars}} + if ($data != null) { + {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} + {{/hasMore}}{{/vars}} + } } {{#vars}} /** From acdc5328fe5da0178024b721846912f08c749751 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Fri, 19 Jun 2015 11:24:56 -0700 Subject: [PATCH 09/39] deserialize thrown exceptions --- .../codegen/languages/PhpClientCodegen.java | 33 +++++++++++-------- .../src/main/resources/php/api.mustache | 25 +++++++++++--- 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index ad9ca3aa9b1..073c7ff1c96 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -248,7 +248,26 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public Map postProcessOperations(Map objs) { objs = addNamespaces(super.postProcessOperations(objs)); + objs = formatImports(objs); + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + return addNamespaces(super.postProcessSupportingFileData(objs)); + } + + protected Map addNamespaces(Map objs) { + objs.put("rootNamespace", rootNamespace); + objs.put("invokerNamespace", invokerNamespace); + objs.put("apiNamespace", apiNamespace); + objs.put("modelNamespace", modelNamespace); + + return objs; + } + + protected Map formatImports(Map objs) { if (objs.containsKey("imports")) { List> imports = new ArrayList>(); LinkedHashMap newImport; @@ -273,18 +292,4 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return objs; } - - @Override - public Map postProcessSupportingFileData(Map objs) { - return addNamespaces(super.postProcessSupportingFileData(objs)); - } - - protected Map addNamespaces(Map objs) { - objs.put("rootNamespace", rootNamespace); - objs.put("invokerNamespace", invokerNamespace); - objs.put("apiNamespace", apiNamespace); - objs.put("modelNamespace", modelNamespace); - - return objs; - } } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 5798ef6f882..704f1c5ebab 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -24,6 +24,7 @@ namespace {{apiNamespace}}; use {{invokerNamespace}}\Configuration; use {{invokerNamespace}}\ApiClient; +use {{invokerNamespace}}\ApiException; {{#imports}} use {{{import}}}; @@ -128,16 +129,30 @@ class {{classname}} { $authSettings = array({{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}); // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, $authSettings); + } catch (ApiException $e) { + $throw = $e; - {{#returnType}}if(! $response) { + switch ($e->getCode()) { {{#responses}}{{#dataType}} + case {{code}}: + $data = $this->apiClient->deserialize($e->getResponseBody(), '{{dataType}}'); + $throw = new ApiException("{{message}}", $e->getCode(), $e->getResponseHeaders(), $data); + break;{{/dataType}}{{/responses}} + } + + throw $throw; + } + {{#returnType}} + if(!$response) { return null; } $responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); - return $responseObject;{{/returnType}} + return $responseObject; + {{/returnType}} } {{/operation}} } From caa1b7f4111ea2bf4ffafdb5244bc364cece0442 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Fri, 19 Jun 2015 15:20:29 -0700 Subject: [PATCH 10/39] generate model imports for support files, and use them as imports --- .../codegen/languages/PhpClientCodegen.java | 27 +++++++++---------- .../src/main/resources/php/ApiClient.mustache | 5 +++- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 073c7ff1c96..7fb23157b36 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -248,14 +248,17 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public Map postProcessOperations(Map objs) { objs = addNamespaces(super.postProcessOperations(objs)); - objs = formatImports(objs); + objs = formatImports(objs, "imports", "import"); return objs; } @Override public Map postProcessSupportingFileData(Map objs) { - return addNamespaces(super.postProcessSupportingFileData(objs)); + objs = addNamespaces(super.postProcessSupportingFileData(objs)); + objs = formatImports(objs, "models", "importPath"); + + return objs; } protected Map addNamespaces(Map objs) { @@ -267,27 +270,23 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return objs; } - protected Map formatImports(Map objs) { - if (objs.containsKey("imports")) { - List> imports = new ArrayList>(); - LinkedHashMap newImport; - String currentImport; + protected Map formatImports(Map objs, String objsKey, String importKey) { + if (objs.containsKey(objsKey)) { String modelName; + List> newImportList = new ArrayList>(); - for (Map importMap : (List>) objs.get("imports")) { - currentImport = importMap.get("import"); - modelName = currentImport.replace(modelPackage + ".", ""); + for (Map importMap : (List>) objs.get(objsKey)) { + modelName = ((String) importMap.get(importKey)).replace(modelPackage + ".", ""); if (reservedWords.contains(modelName)) { continue; } - newImport = new LinkedHashMap(); - newImport.put("import", modelNamespace + "\\" + modelName); - imports.add(newImport); + importMap.put(importKey, modelNamespace + "\\" + modelName); + newImportList.add(importMap); } - objs.put("imports", imports); + objs.put(objsKey, newImportList); } return objs; diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 564bc1ddd66..4a3e50dd50b 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -17,6 +17,10 @@ namespace {{invokerNamespace}}; +{{#models}} +use {{importPath}}; +{{/models}} + class ApiClient { public static $PATCH = "PATCH"; @@ -399,7 +403,6 @@ class ApiClient { settype($data, $class); $deserialized = $data; } else { - $class = "{{invokerPackage}}\\models\\".$class; $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { $original_property_name = $instance::$attributeMap[$property]; From b9ca19168a92d989bd91a2096bd16f7dceb8b540 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 08:28:22 -0700 Subject: [PATCH 11/39] remove static fields in Configuration and make variable case more consistent --- .../src/main/resources/php/ApiClient.mustache | 116 +++++++------ .../src/main/resources/php/api.mustache | 30 ++-- .../main/resources/php/configuration.mustache | 159 ++++++++++++++++-- .../src/main/resources/php/model.mustache | 2 +- 4 files changed, 221 insertions(+), 86 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 4a3e50dd50b..8a030079fa0 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -29,40 +29,46 @@ class ApiClient { public static $PUT = "PUT"; public static $DELETE = "DELETE"; - private static $default_header = array(); + protected $defaultHeaders = array(); /* * @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ - protected $curl_timeout = 0; + protected $curlTimeout = 0; /* * @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ - protected $user_agent = "PHP-Swagger"; + protected $userAgent = "PHP-Swagger"; /** - * @param string $host Base url of the API server (optional) + * @var ApiConfiguration */ - function __construct($host = null) { - if ($host === null) { - $this->host = '{{basePath}}'; - } else { - $this->host = $host; + protected $config; + + /** + * @param ApiConfiguration $config config for this ApiClient + */ + function __construct(ApiConfiguration $config = null) { + if ($config == null) { + $config = ApiConfiguration::getDefaultConfiguration(); } + + $this->config = $config; } /** * add default header * - * @param string $header_name header name (e.g. Token) - * @param string $header_value header value (e.g. 1z8wp3) + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) */ - public function addDefaultHeader($header_name, $header_value) { - if (!is_string($header_name)) + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { throw new \InvalidArgumentException('Header name must be a string.'); + } - self::$default_header[$header_name] = $header_value; + $this->defaultHeaders[$headerName] = $headerValue; } /** @@ -70,29 +76,29 @@ class ApiClient { * * @return array default header */ - public function getDefaultHeader() { - return self::$default_header; + public function getDefaultHeaders() { + return $this->defaultHeaders; } /** * delete the default header based on header name * - * @param string $header_name header name (e.g. Token) + * @param string $headerName header name (e.g. Token) */ - public function deleteDefaultHeader($header_name) { - unset(self::$default_header[$header_name]); + public function deleteDefaultHeader($headerName) { + unset($this->defaultHeaders[$headerName]); } /** * set the user agent of the api client * - * @param string $user_agent the user agent of the api client + * @param string $userAgent the user agent of the api client */ - public function setUserAgent($user_agent) { - if (!is_string($user_agent)) + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) throw new \InvalidArgumentException('User-agent must be a string.'); - $this->user_agent= $user_agent; + $this->userAgent = $userAgent; } /** @@ -100,8 +106,8 @@ class ApiClient { * * @return string user agent */ - public function getUserAgent($user_agent) { - return $this->user_agent; + public function getUserAgent() { + return $this->userAgent; } /** @@ -113,7 +119,7 @@ class ApiClient { if (!is_numeric($seconds) || $seconds < 0) throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - $this->curl_timeout = $seconds; + $this->curlTimeout = $seconds; } /** @@ -122,27 +128,34 @@ class ApiClient { * @return string HTTP timeout value */ public function getTimeout() { - return $this->curl_timeout; + return $this->curlTimeout; } /** * Get API key (with prefix if set) - * @param string key name + * @param string $apiKey name of apikey * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { - if (isset(Configuration::$apiKeyPrefix[$apiKey])) { - return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else if (isset(Configuration::$apiKey[$apiKey])) { - return Configuration::$apiKey[$apiKey]; - } else { - return; + $prefix = $this->config->getApiKeyPrefix($apiKey); + $apiKey = $this->config->getApiKey($apiKey); + + if (!isset($apiKey)) { + return null; } + + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; + } else { + $keyWithPrefix = $apiKey; + } + + return $keyWithPrefix; } /** - * update hearder and query param based on authentication setting + * update header and query param based on authentication setting * * @param array $headerParams header parameters (by ref) * @param array $queryParams query parameters (by ref) @@ -159,7 +172,7 @@ class ApiClient { switch($auth) { {{#authMethods}} case '{{name}}': - {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode(Configuration::$username.":".Configuration::$password);{{/isBasic}} + {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->config->getUsername().":".$this->config->getPassword());{{/isBasic}} {{#isOAuth}}//TODO support oauth{{/isOAuth}} break; {{/authMethods}} @@ -175,6 +188,8 @@ class ApiClient { * @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 array $authSettings parameters for authentication + * @throws \{{invokerNamespace}}\ApiException on a non 2xx response * @return mixed */ public function callApi($resourcePath, $method, $queryParams, $postData, @@ -186,7 +201,7 @@ class ApiClient { $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); # construct the http header - $headerParams = array_merge((array)self::$default_header, (array)$headerParams); + $headerParams = array_merge((array)$this->defaultHeaders, (array)$headerParams); foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; @@ -200,12 +215,12 @@ class ApiClient { $postData = json_encode($this->sanitizeForSerialization($postData)); } - $url = $this->host . $resourcePath; + $url = $this->config->getHost() . $resourcePath; $curl = curl_init(); // set timeout, if needed - if ($this->curl_timeout != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); + if ($this->curlTimeout != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->curlTimeout); } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -234,14 +249,14 @@ class ApiClient { curl_setopt($curl, CURLOPT_URL, $url); // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + curl_setopt($curl, CURLOPT_USERAGENT, $this->userAgent); // debugging for curl - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); + curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } @@ -257,8 +272,8 @@ class ApiClient { $response_info = curl_getinfo($curl); // debug HTTP response body - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); } // Handle the response @@ -278,9 +293,10 @@ class ApiClient { /** * Build a JSON POST object + * @param mixed $data the data to serialize + * @return string serialized form of $data */ - protected function sanitizeForSerialization($data) - { + protected function sanitizeForSerialization($data) { if (is_scalar($data) || null === $data) { $sanitized = $data; } else if ($data instanceof \DateTime) { @@ -372,7 +388,7 @@ class ApiClient { /** * Deserialize a JSON string into an object * - * @param object $object object or primitive to be deserialized + * @param object $data object or primitive to be deserialized * @param string $class class name is passed as a string * @return object an instance of $class */ @@ -419,7 +435,7 @@ class ApiClient { /* * return the header 'Accept' based on an array of Accept provided * - * @param array[string] $accept Array of header + * @param string[] $accept Array of header * @return string Accept (e.g. application/json) */ public static function selectHeaderAccept($accept) { diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 704f1c5ebab..2b4f1f27ab7 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -37,16 +37,11 @@ class {{classname}} { private $apiClient; function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user + if ($apiClient == null) { + $apiClient = new ApiClient(); } + + $this->apiClient = $apiClient; } /** @@ -88,28 +83,29 @@ class {{classname}} { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + $_header_accept = ApiClient::selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); {{#queryParams}}// query params if(${{paramName}} !== null) { - $queryParams['{{baseName}}'] = $this->apiClient->toQueryValue(${{paramName}}); + $queryParams['{{baseName}}'] = ApiClient::toQueryValue(${{paramName}}); }{{/queryParams}} {{#headerParams}}// header params if(${{paramName}} !== null) { - $headerParams['{{baseName}}'] = $this->apiClient->toHeaderValue(${{paramName}}); + $headerParams['{{baseName}}'] = ApiClient::toHeaderValue(${{paramName}}); }{{/headerParams}} {{#pathParams}}// path params if(${{paramName}} !== null) { $resourcePath = str_replace("{" . "{{baseName}}" . "}", - $this->apiClient->toPathValue(${{paramName}}), $resourcePath); + ApiClient::toPathValue(${{paramName}}), + $resourcePath); }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}ApiClient::toFormValue(${{paramName}}); }{{/formParams}} {{#bodyParams}}// body params $_tempBody = null; @@ -138,7 +134,7 @@ class {{classname}} { switch ($e->getCode()) { {{#responses}}{{#dataType}} case {{code}}: - $data = $this->apiClient->deserialize($e->getResponseBody(), '{{dataType}}'); + $data = ApiClient::deserialize($e->getResponseBody(), '{{dataType}}'); $throw = new ApiException("{{message}}", $e->getCode(), $e->getResponseHeaders(), $data); break;{{/dataType}}{{/responses}} } @@ -150,7 +146,7 @@ class {{classname}} { return null; } - $responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); + $responseObject = ApiClient::deserialize($response,'{{returnType}}'); return $responseObject; {{/returnType}} } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index b7a9107e77b..1f0ebb496ab 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -17,50 +17,173 @@ namespace {{invokerNamespace}}; -class Configuration { +class ApiConfiguration { + + private static $defaultConfiguration = null; + + /** + * The host (from basePath) + */ + protected $host = '{{basePath}}'; /** * Associate array to store API key(s) */ - public static $apiKey = array(); + protected $apiKeys = array(); /** * Associate array to store API prefix (e.g. Bearer) */ - public static $apiKeyPrefix = array(); + protected $apiKeyPrefixes = array(); /** * Username for HTTP basic authentication */ - public static $username = ''; + protected $username = ''; /** * Password for HTTP basic authentication */ - public static $password = ''; - - /** - * The default instance of ApiClient - */ - public static $apiClient; + protected $password = ''; /** * Debug switch (default set to false) */ - public static $debug = false; + protected $debug = false; /** * Debug file location (log to STDOUT by default) */ - public static $debug_file = 'php://output'; + protected $debugFile = 'php://output'; - /* - * manually initalize ApiClient + /** + * @param string $host + * @return ApiConfiguration */ - public static function init() { - if (self::$apiClient === null) - self::$apiClient = new ApiClient(); + public function setHost($host) { + $this->host = $host; + return $this; } -} + /** + * @return string + */ + public function getHost() { + return $this->host; + } + /** + * @param string $key + * @param string $value + * @return ApiConfiguration + */ + public function setApiKey($key, $value) { + $this->apiKeys[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKey($key) { + return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + } + + /** + * @param string $key + * @param string $value + * @return ApiConfiguration + */ + public function setApiKeyPrefix($key, $value) { + $this->apiKeyPrefixes[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKeyPrefix($key) { + return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; + } + + /** + * @param string $username + * @return ApiConfiguration + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * @param string $password + * @return ApiConfiguration + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * @param bool $debug + * @return ApiConfiguration + */ + public function setDebug($debug) { + $this->debug = $debug; + return $this; + } + + /** + * @return bool + */ + public function getDebug() { + return $this->debug; + } + + /** + * @param string $debugFile + * @return ApiConfiguration + */ + public function setDebugFile($debugFile) { + $this->debugFile = $debugFile; + return $this; + } + + /** + * @return string + */ + public function getDebugFile() { + return $this->debugFile; + } + + /** + * @return ApiConfiguration + */ + public static function getDefaultConfiguration() { + if (self::$defaultConfiguration == null) { + return new ApiConfiguration(); + } + + return self::$defaultConfiguration; + } + + public static function setDefaultConfiguration(ApiConfiguration $config) { + self::$defaultConfiguration = $config; + } +} diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 86dafc99d99..fadf38f874b 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -44,7 +44,7 @@ class {{classname}} implements ArrayAccess { * {{{description}}}{{/description}} * @var {{{datatype}}} */ - public ${{name}}; + protected ${{name}}; {{/vars}} public function __construct(array $data = null) { if ($data != null) { From 99e963709b33f8075f5ce917de8e3eeb2f8bad99 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 08:30:08 -0700 Subject: [PATCH 12/39] renaming configuration --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 2 +- .../php/{configuration.mustache => ApiConfiguration.mustache} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename modules/swagger-codegen/src/main/resources/php/{configuration.mustache => ApiConfiguration.mustache} (100%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 7fb23157b36..18f8cb8917b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -116,7 +116,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { setNamespacesFromPackages(); prefixPackages(); - supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage.replace('/', File.separatorChar), "Configuration.php")); + supportingFiles.add(new SupportingFile("ApiConfiguration.mustache", invokerPackage.replace('/', File.separatorChar), "ApiConfiguration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerPackage.replace('/', File.separatorChar), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", invokerPackage.replace('/', File.separatorChar), "ApiException.php")); supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/php/configuration.mustache rename to modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache From 04be474f56fd019aa7c4022a8d81469f56acca11 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 08:36:49 -0700 Subject: [PATCH 13/39] moving $host back to ApiClient and making ApiClient setters fluent --- .../src/main/resources/php/ApiClient.mustache | 30 ++++++++++++++++++- .../resources/php/ApiConfiguration.mustache | 21 ------------- 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 8a030079fa0..e9e308cbf64 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -31,6 +31,11 @@ class ApiClient { protected $defaultHeaders = array(); + /** + * The host (from basePath) + */ + protected $host = '{{basePath}}'; + /* * @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ @@ -49,7 +54,11 @@ class ApiClient { /** * @param ApiConfiguration $config config for this ApiClient */ - function __construct(ApiConfiguration $config = null) { + function __construct($host = null, ApiConfiguration $config = null) { + if ($host != null) { + $this->host = $host; + } + if ($config == null) { $config = ApiConfiguration::getDefaultConfiguration(); } @@ -69,6 +78,7 @@ class ApiClient { } $this->defaultHeaders[$headerName] = $headerValue; + return $this; } /** @@ -80,6 +90,22 @@ class ApiClient { return $this->defaultHeaders; } + /** + * @param string $host + * @return ApiConfiguration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + /** * delete the default header based on header name * @@ -99,6 +125,7 @@ class ApiClient { throw new \InvalidArgumentException('User-agent must be a string.'); $this->userAgent = $userAgent; + return $this; } /** @@ -120,6 +147,7 @@ class ApiClient { throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); $this->curlTimeout = $seconds; + return $this; } /** diff --git a/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache index 1f0ebb496ab..764e0eafe89 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache @@ -21,11 +21,6 @@ class ApiConfiguration { private static $defaultConfiguration = null; - /** - * The host (from basePath) - */ - protected $host = '{{basePath}}'; - /** * Associate array to store API key(s) */ @@ -56,22 +51,6 @@ class ApiConfiguration { */ protected $debugFile = 'php://output'; - /** - * @param string $host - * @return ApiConfiguration - */ - public function setHost($host) { - $this->host = $host; - return $this; - } - - /** - * @return string - */ - public function getHost() { - return $this->host; - } - /** * @param string $key * @param string $value From b3a3bdd2e0c3a30809c7c132a03a668ca2e19465 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 09:18:41 -0700 Subject: [PATCH 14/39] add fully-qualified class names to deserialize params --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 4 +++- .../src/main/resources/php/ApiClient.mustache | 6 +----- modules/swagger-codegen/src/main/resources/php/api.mustache | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 18f8cb8917b..7e9bac9c62f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -8,6 +8,7 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; import java.io.File; import java.util.ArrayList; @@ -157,6 +158,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } else if (p instanceof RefProperty) { + return "\\\\" + modelNamespace.replace("\\", "\\\\") + "\\\\" + getSwaggerType(p); } return super.getTypeDeclaration(p); } @@ -256,7 +259,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public Map postProcessSupportingFileData(Map objs) { objs = addNamespaces(super.postProcessSupportingFileData(objs)); - objs = formatImports(objs, "models", "importPath"); return objs; } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index e9e308cbf64..b91bbf29d37 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -17,10 +17,6 @@ namespace {{invokerNamespace}}; -{{#models}} -use {{importPath}}; -{{/models}} - class ApiClient { public static $PATCH = "PATCH"; @@ -416,7 +412,7 @@ class ApiClient { /** * Deserialize a JSON string into an object * - * @param object $data object or primitive to be deserialized + * @param mixed $data object or primitive to be deserialized * @param string $class class name is passed as a string * @return object an instance of $class */ diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 2b4f1f27ab7..76fe0afab5a 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -22,7 +22,7 @@ namespace {{apiNamespace}}; -use {{invokerNamespace}}\Configuration; +use {{invokerNamespace}}\ApiConfiguration; use {{invokerNamespace}}\ApiClient; use {{invokerNamespace}}\ApiException; From 1519912a1ab460ff0d2fae820b81f01b96a0e3b7 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 09:26:45 -0700 Subject: [PATCH 15/39] cleaning up some php doc --- .../swagger-codegen/src/main/resources/php/api.mustache | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 76fe0afab5a..06f6386b046 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -46,6 +46,7 @@ class {{classname}} { /** * get the API client + * @return ApiClient this API's client */ public function getApiClient() { return $this->apiClient; @@ -53,9 +54,12 @@ class {{classname}} { /** * set the API client + * @param ApiClient $apiClient + * @return {{classname}} */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } {{#operation}} @@ -66,6 +70,7 @@ class {{classname}} { * {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} {{/allParams}} * @return {{#returnType}}{{#isListContainer}}{{returnBaseType}}[]{{/isListContainer}}{{^isListContainer}}{{{returnType}}}{{/isListContainer}}{{/returnType}}{{^returnType}}void{{/returnType}} + * @throws \{{invokerNamespace}}\ApiException on non-2xx response */ public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} From 53bddae904cca40b53552b294e73803f9443e447 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 09:47:28 -0700 Subject: [PATCH 16/39] separate serialization responsibility to ObjectSerializer class --- .../codegen/languages/PhpClientCodegen.java | 1 + .../src/main/resources/php/ApiClient.mustache | 154 +----------------- .../resources/php/ObjectSerializer.mustache | 144 ++++++++++++++++ .../src/main/resources/php/api.mustache | 13 +- 4 files changed, 158 insertions(+), 154 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 7e9bac9c62f..201f7eb0539 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -120,6 +120,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("ApiConfiguration.mustache", invokerPackage.replace('/', File.separatorChar), "ApiConfiguration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerPackage.replace('/', File.separatorChar), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", invokerPackage.replace('/', File.separatorChar), "ApiException.php")); + supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", invokerPackage.replace('/', File.separatorChar), "ObjectSerializer.php")); supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); supportingFiles.add(new SupportingFile("autoload.mustache", "", "autoload.php")); } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index b91bbf29d37..e697b7305aa 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -50,11 +50,7 @@ class ApiClient { /** * @param ApiConfiguration $config config for this ApiClient */ - function __construct($host = null, ApiConfiguration $config = null) { - if ($host != null) { - $this->host = $host; - } - + function __construct(ApiConfiguration $config = null) { if ($config == null) { $config = ApiConfiguration::getDefaultConfiguration(); } @@ -67,6 +63,7 @@ class ApiClient { * * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient */ public function addDefaultHeader($headerName, $headerValue) { if (!is_string($headerName)) { @@ -115,6 +112,7 @@ class ApiClient { * set the user agent of the api client * * @param string $userAgent the user agent of the api client + * @return ApiClient */ public function setUserAgent($userAgent) { if (!is_string($userAgent)) @@ -137,6 +135,7 @@ class ApiClient { * set the HTTP timeout value * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient */ public function setTimeout($seconds) { if (!is_numeric($seconds) || $seconds < 0) @@ -236,10 +235,10 @@ class ApiClient { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->sanitizeForSerialization($postData)); + $postData = json_encode(ObjectSerializer::sanitizeForSerialization($postData)); } - $url = $this->config->getHost() . $resourcePath; + $url = $this->getHost() . $resourcePath; $curl = curl_init(); // set timeout, if needed @@ -315,147 +314,6 @@ class ApiClient { return $data; } - /** - * Build a JSON POST object - * @param mixed $data the data to serialize - * @return string serialized form of $data - */ - protected function sanitizeForSerialization($data) { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - if ($data->$property !== null) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); - } - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - - return $sanitized; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public static function toPathValue($value) { - return rawurlencode(self::toString($value)); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public static function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return self::toString($object); - } - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the header. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value a string which will be part of the header - * @return string the header string - */ - public static function toHeaderValue($value) { - return self::toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the http body (form parameter). If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the form parameter - * @return string the form string - */ - public static function toFormValue($value) { - return self::toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the parameter. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the parameter - * @return string the header string - */ - public static function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } - - /** - * Deserialize a JSON string into an object - * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - public static function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] - $inner = substr($class, 4, -1); - $deserialized = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass); - } - } - } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); - $values = array(); - foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name) && isset($data->$original_property_name)) { - $instance->$property = self::deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; - } - /* * return the header 'Accept' based on an array of Accept provided * diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache new file mode 100644 index 00000000000..3a7765a4a82 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -0,0 +1,144 @@ +format(\DateTime::ISO8601); + } else if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = self::sanitizeForSerialization($value); + } + $sanitized = $data; + } else if (is_object($data)) { + $values = array(); + foreach (array_keys($data::$swaggerTypes) as $property) { + if ($data->$property !== null) { + $values[$data::$attributeMap[$property]] = self::sanitizeForSerialization($data->$property); + } + } + $sanitized = $values; + } else { + $sanitized = (string)$data; + } + + return $sanitized; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public static function toPathValue($value) { + return rawurlencode(self::toString($value)); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * @param object $object an object to be serialized to a string + * @return string the serialized object + */ + public static function toQueryValue($object) { + if (is_array($object)) { + return implode(',', $object); + } else { + return self::toString($object); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value a string which will be part of the header + * @return string the header string + */ + public static function toHeaderValue($value) { + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the form parameter + * @return string the form string + */ + public static function toFormValue($value) { + return self::toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the parameter + * @return string the header string + */ + public static function toString($value) { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } else { + return $value; + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ + public static function deserialize($data, $class) { + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = self::deserialize($value, $subClass); + } + } + } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { + $subClass = substr($class, 6, -1); + $values = array(); + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + $original_property_name = $instance::$attributeMap[$property]; + if (isset($original_property_name) && isset($data->$original_property_name)) { + $instance->$property = self::deserialize($data->$original_property_name, $type); + } + } + $deserialized = $instance; + } + + return $deserialized; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 06f6386b046..847527ee40c 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -25,6 +25,7 @@ namespace {{apiNamespace}}; use {{invokerNamespace}}\ApiConfiguration; use {{invokerNamespace}}\ApiClient; use {{invokerNamespace}}\ApiException; +use {{invokerNamespace}}\ObjectSerializer; {{#imports}} use {{{import}}}; @@ -96,21 +97,21 @@ class {{classname}} { {{#queryParams}}// query params if(${{paramName}} !== null) { - $queryParams['{{baseName}}'] = ApiClient::toQueryValue(${{paramName}}); + $queryParams['{{baseName}}'] = ObjectSerializer::toQueryValue(${{paramName}}); }{{/queryParams}} {{#headerParams}}// header params if(${{paramName}} !== null) { - $headerParams['{{baseName}}'] = ApiClient::toHeaderValue(${{paramName}}); + $headerParams['{{baseName}}'] = ObjectSerializer::toHeaderValue(${{paramName}}); }{{/headerParams}} {{#pathParams}}// path params if(${{paramName}} !== null) { $resourcePath = str_replace("{" . "{{baseName}}" . "}", - ApiClient::toPathValue(${{paramName}}), + ObjectSerializer::toPathValue(${{paramName}}), $resourcePath); }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}ApiClient::toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}ObjectSerializer::toFormValue(${{paramName}}); }{{/formParams}} {{#bodyParams}}// body params $_tempBody = null; @@ -139,7 +140,7 @@ class {{classname}} { switch ($e->getCode()) { {{#responses}}{{#dataType}} case {{code}}: - $data = ApiClient::deserialize($e->getResponseBody(), '{{dataType}}'); + $data = ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}'); $throw = new ApiException("{{message}}", $e->getCode(), $e->getResponseHeaders(), $data); break;{{/dataType}}{{/responses}} } @@ -151,7 +152,7 @@ class {{classname}} { return null; } - $responseObject = ApiClient::deserialize($response,'{{returnType}}'); + $responseObject = ObjectSerializer::deserialize($response,'{{returnType}}'); return $responseObject; {{/returnType}} } From e598384d97e5f3543679a3e7e6a38b2bf052a356 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 10:31:38 -0700 Subject: [PATCH 17/39] move authentication to the API level, so that supporting classes aren't api-specific --- .../src/main/resources/php/ApiClient.mustache | 43 ++++--------------- .../src/main/resources/php/api.mustache | 16 ++++--- 2 files changed, 19 insertions(+), 40 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index e697b7305aa..c2a6b369f3c 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -99,6 +99,14 @@ class ApiClient { return $this->host; } + /** + * get the config + * @return ApiConfiguration + */ + public function getConfig() { + return $this->config; + } + /** * delete the default header based on header name * @@ -176,34 +184,6 @@ class ApiClient { return $keyWithPrefix; } - - /** - * update header and query param based on authentication setting - * - * @param array $headerParams header parameters (by ref) - * @param array $queryParams query parameters (by ref) - * @param array $authSettings array of authentication scheme (e.g ['api_key']) - */ - public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) - { - if (count($authSettings) == 0) - return; - - // one endpoint can have more than 1 auth settings - foreach($authSettings as $auth) { - // determine which one to use - switch($auth) { - {{#authMethods}} - case '{{name}}': - {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->config->getUsername().":".$this->config->getPassword());{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} - break; - {{/authMethods}} - default: - //TODO show warning about security definition not found - } - } - } /** * @param string $resourcePath path to method endpoint @@ -211,18 +191,13 @@ class ApiClient { * @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 array $authSettings parameters for authentication * @throws \{{invokerNamespace}}\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, - $headerParams, $authSettings) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams) { $headers = array(); - # determine authentication setting - $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - # construct the http header $headerParams = array_merge((array)$this->defaultHeaders, (array)$headerParams); diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 847527ee40c..a014ecbaccc 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -126,15 +126,19 @@ class {{classname}} { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array({{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}); - + {{#authMethods}}{{#isApiKey}} + $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); + if (isset($apiKey)) { + {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} + }{{/isApiKey}} + {{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->apiClient->getConfig()->getUsername().":".$this->apiClient->getConfig()->getPassword());{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + {{/authMethods}} // make the API Call try { $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams, $authSettings); + $headerParams); } catch (ApiException $e) { $throw = $e; @@ -148,7 +152,7 @@ class {{classname}} { throw $throw; } {{#returnType}} - if(!$response) { + if (!$response) { return null; } From 6f11092a57442f5f2a73f155917ebfedcb8e9fd9 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 10:35:57 -0700 Subject: [PATCH 18/39] call setHost using API baspath when no apiclient is provided --- .../swagger-codegen/src/main/resources/php/ApiClient.mustache | 4 ++-- modules/swagger-codegen/src/main/resources/php/api.mustache | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index c2a6b369f3c..996ccbd16d9 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -28,9 +28,9 @@ class ApiClient { protected $defaultHeaders = array(); /** - * The host (from basePath) + * The host */ - protected $host = '{{basePath}}'; + protected $host = 'http://localhost'; /* * @var string timeout (second) of the HTTP request, by default set to 0, no timeout diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index a014ecbaccc..b6f17f528d5 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -39,7 +39,7 @@ class {{classname}} { function __construct($apiClient = null) { if ($apiClient == null) { - $apiClient = new ApiClient(); + $apiClient = (new ApiClient())->setHost('{{basePath}}'); } $this->apiClient = $apiClient; From 5de99bafa725b125dc5969d06d9fb93856ba2709 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 11:18:36 -0700 Subject: [PATCH 19/39] fixing package output --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 201f7eb0539..beddbeac729 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -126,7 +126,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } protected String getSrcDir(String packageName) { - return rootNamespace + "/src/" + packageName; + return "src/" + packageName; } protected void prefixPackages() { From 109b7eeaec3c9ab0c70a1515cc8c58cd501da722 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 11:19:01 -0700 Subject: [PATCH 20/39] adding static setters/getters for models since members are no public --- .../resources/php/ObjectSerializer.mustache | 17 ++++++++++++----- .../src/main/resources/php/model.mustache | 18 ++++++++++++++---- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 3a7765a4a82..fe70c4db653 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -21,8 +21,9 @@ class ObjectSerializer { } else if (is_object($data)) { $values = array(); foreach (array_keys($data::$swaggerTypes) as $property) { - if ($data->$property !== null) { - $values[$data::$attributeMap[$property]] = self::sanitizeForSerialization($data->$property); + $getter = $data::$getters[$property]; + if ($data->$getter() !== null) { + $values[$data::$attributeMap[$property]] = self::sanitizeForSerialization($data->$getter()); } } $sanitized = $values; @@ -131,9 +132,15 @@ class ObjectSerializer { } else { $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { - $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name) && isset($data->$original_property_name)) { - $instance->$property = self::deserialize($data->$original_property_name, $type); + $propertySetter = $instance::$setters[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::$attributeMap[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter(self::deserialize($propertyValue, $type)); } } $deserialized = $instance; diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index fadf38f874b..0e906b5885c 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -30,13 +30,23 @@ use \ArrayAccess; class {{classname}} implements ArrayAccess { static $swaggerTypes = array( - {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} + {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} ); static $attributeMap = array( - {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + static $setters = array( + {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + static $getters = array( + {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} ); {{#vars}} From 01d7776fc1a1469ea45bf4a1c2a81032cbf3bfe1 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 11:47:23 -0700 Subject: [PATCH 21/39] don't create a new response object, and keep the old string value in the exception and have the object as ApiException->responseObject --- .../main/resources/php/ApiException.mustache | 28 +++++++++++++++---- .../src/main/resources/php/api.mustache | 6 ++-- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 096979c11cb..4b8d205690c 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -24,17 +24,22 @@ class ApiException extends Exception { /** * The HTTP body of the server response. */ - protected $response_body; + protected $responseBody; /** * The HTTP header of the server response. */ - protected $response_headers; + protected $responseHeaders; + + /** + * The deserialized response object + */ + protected $responseObject; public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { parent::__construct($message, $code); - $this->response_headers = $responseHeaders; - $this->response_body = $responseBody; + $this->responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; } /** @@ -43,7 +48,7 @@ class ApiException extends Exception { * @return string HTTP response header */ public function getResponseHeaders() { - return $this->response_headers; + return $this->responseHeaders; } /** @@ -52,7 +57,18 @@ class ApiException extends Exception { * @return string HTTP response body */ public function getResponseBody() { - return $this->response_body; + return $this->responseBody; } + /** + * sets the deseralized response object (during deserialization) + * @param mixed $obj + */ + public function setResponseObject($obj) { + $this->responseObject = $obj; + } + + public function getResponseObject() { + return $this->responseObject; + } } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index b6f17f528d5..3d9ead4bed1 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -140,16 +140,14 @@ class {{classname}} { $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { - $throw = $e; - switch ($e->getCode()) { {{#responses}}{{#dataType}} case {{code}}: $data = ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}'); - $throw = new ApiException("{{message}}", $e->getCode(), $e->getResponseHeaders(), $data); + $e->setResponseObject($data); break;{{/dataType}}{{/responses}} } - throw $throw; + throw $e; } {{#returnType}} if (!$response) { From a6331244e15fc09c34aaf16262d667ac9a137ccb Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 12:05:22 -0700 Subject: [PATCH 22/39] move all configuration to ApiConfiguration --- .../src/main/resources/php/ApiClient.mustache | 125 +----------------- .../resources/php/ApiConfiguration.mustache | 109 +++++++++++++++ 2 files changed, 114 insertions(+), 120 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 996ccbd16d9..c29ca1f58e4 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -24,23 +24,6 @@ class ApiClient { public static $GET = "GET"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; - - protected $defaultHeaders = array(); - - /** - * The host - */ - protected $host = 'http://localhost'; - - /* - * @var string timeout (second) of the HTTP request, by default set to 0, no timeout - */ - protected $curlTimeout = 0; - - /* - * @var string user agent of the HTTP request, set to "PHP-Swagger" by default - */ - protected $userAgent = "PHP-Swagger"; /** * @var ApiConfiguration @@ -58,47 +41,6 @@ class ApiClient { $this->config = $config; } - /** - * add default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * @return ApiClient - */ - public function addDefaultHeader($headerName, $headerValue) { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * get the default header - * - * @return array default header - */ - public function getDefaultHeaders() { - return $this->defaultHeaders; - } - - /** - * @param string $host - * @return ApiConfiguration - */ - public function setHost($host) { - $this->host = $host; - return $this; - } - - /** - * @return string - */ - public function getHost() { - return $this->host; - } - /** * get the config * @return ApiConfiguration @@ -107,62 +49,6 @@ class ApiClient { return $this->config; } - /** - * delete the default header based on header name - * - * @param string $headerName header name (e.g. Token) - */ - public function deleteDefaultHeader($headerName) { - unset($this->defaultHeaders[$headerName]); - } - - /** - * set the user agent of the api client - * - * @param string $userAgent the user agent of the api client - * @return ApiClient - */ - public function setUserAgent($userAgent) { - if (!is_string($userAgent)) - throw new \InvalidArgumentException('User-agent must be a string.'); - - $this->userAgent = $userAgent; - return $this; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() { - return $this->userAgent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - * @return ApiClient - */ - public function setTimeout($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; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getTimeout() { - return $this->curlTimeout; - } - - /** * Get API key (with prefix if set) * @param string $apiKey name of apikey @@ -199,7 +85,7 @@ class ApiClient { $headers = array(); # construct the http header - $headerParams = array_merge((array)$this->defaultHeaders, (array)$headerParams); + $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; @@ -213,12 +99,12 @@ class ApiClient { $postData = json_encode(ObjectSerializer::sanitizeForSerialization($postData)); } - $url = $this->getHost() . $resourcePath; + $url = $this->config->getHost() . $resourcePath; $curl = curl_init(); // set timeout, if needed - if ($this->curlTimeout != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curlTimeout); + if ($this->config->getCurlTimeout() != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -247,7 +133,7 @@ class ApiClient { curl_setopt($curl, CURLOPT_URL, $url); // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->userAgent); + curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); // debugging for curl if ($this->config->getDebug()) { @@ -320,6 +206,5 @@ class ApiClient { return implode(',', $content_type); } } - } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache index 764e0eafe89..4834294901d 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache @@ -41,6 +41,26 @@ class ApiConfiguration { */ protected $password = ''; + /** + * default headers for requests this conf + */ + protected $defaultHeaders = array(); + + /** + * The host + */ + protected $host = 'http://localhost'; + + /* + * @var string timeout (second) of the HTTP request, by default set to 0, no timeout + */ + protected $curlTimeout = 0; + + /* + * @var string user agent of the HTTP request, set to "PHP-Swagger" by default + */ + protected $userAgent = "PHP-Swagger"; + /** * Debug switch (default set to false) */ @@ -119,6 +139,95 @@ class ApiConfiguration { return $this->password; } + /** + * add default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient + */ + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeaders() { + return $this->defaultHeaders; + } + + /** + * @param string $host + * @return ApiConfiguration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + + /** + * set the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * @return ApiClient + */ + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() { + return $this->userAgent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient + */ + 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; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getCurlTimeout() { + return $this->curlTimeout; + } + /** * @param bool $debug * @return ApiConfiguration From 5ef50f9f4b27f943e841d04d6958926d9c2e8f48 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 12:07:48 -0700 Subject: [PATCH 23/39] rename ApiConfiguration to ApiClientConfiguration --- .../codegen/languages/PhpClientCodegen.java | 2 +- .../src/main/resources/php/ApiClient.mustache | 10 ++++----- ...stache => ApiClientConfiguration.mustache} | 22 +++++++++---------- .../src/main/resources/php/api.mustache | 2 +- 4 files changed, 18 insertions(+), 18 deletions(-) rename modules/swagger-codegen/src/main/resources/php/{ApiConfiguration.mustache => ApiClientConfiguration.mustache} (92%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index beddbeac729..a9909427a0d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -117,7 +117,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { setNamespacesFromPackages(); prefixPackages(); - supportingFiles.add(new SupportingFile("ApiConfiguration.mustache", invokerPackage.replace('/', File.separatorChar), "ApiConfiguration.php")); + supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", invokerPackage.replace('/', File.separatorChar), "ApiClientConfiguration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerPackage.replace('/', File.separatorChar), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", invokerPackage.replace('/', File.separatorChar), "ApiException.php")); supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", invokerPackage.replace('/', File.separatorChar), "ObjectSerializer.php")); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index c29ca1f58e4..d6133b08584 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -26,16 +26,16 @@ class ApiClient { public static $DELETE = "DELETE"; /** - * @var ApiConfiguration + * @var ApiClientConfiguration */ protected $config; /** - * @param ApiConfiguration $config config for this ApiClient + * @param ApiClientConfiguration $config config for this ApiClient */ - function __construct(ApiConfiguration $config = null) { + function __construct(ApiClientConfiguration $config = null) { if ($config == null) { - $config = ApiConfiguration::getDefaultConfiguration(); + $config = ApiClientConfiguration::getDefaultConfiguration(); } $this->config = $config; @@ -43,7 +43,7 @@ class ApiClient { /** * get the config - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function getConfig() { return $this->config; diff --git a/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache similarity index 92% rename from modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache rename to modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache index 4834294901d..6a674ccfd3f 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache @@ -17,7 +17,7 @@ namespace {{invokerNamespace}}; -class ApiConfiguration { +class ApiClientConfiguration { private static $defaultConfiguration = null; @@ -74,7 +74,7 @@ class ApiConfiguration { /** * @param string $key * @param string $value - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function setApiKey($key, $value) { $this->apiKeys[$key] = $value; @@ -92,7 +92,7 @@ class ApiConfiguration { /** * @param string $key * @param string $value - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function setApiKeyPrefix($key, $value) { $this->apiKeyPrefixes[$key] = $value; @@ -109,7 +109,7 @@ class ApiConfiguration { /** * @param string $username - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function setUsername($username) { $this->username = $username; @@ -125,7 +125,7 @@ class ApiConfiguration { /** * @param string $password - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function setPassword($password) { $this->password = $password; @@ -166,7 +166,7 @@ class ApiConfiguration { /** * @param string $host - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function setHost($host) { $this->host = $host; @@ -230,7 +230,7 @@ class ApiConfiguration { /** * @param bool $debug - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function setDebug($debug) { $this->debug = $debug; @@ -246,7 +246,7 @@ class ApiConfiguration { /** * @param string $debugFile - * @return ApiConfiguration + * @return ApiClientConfiguration */ public function setDebugFile($debugFile) { $this->debugFile = $debugFile; @@ -261,17 +261,17 @@ class ApiConfiguration { } /** - * @return ApiConfiguration + * @return ApiClientConfiguration */ public static function getDefaultConfiguration() { if (self::$defaultConfiguration == null) { - return new ApiConfiguration(); + return new ApiClientConfiguration(); } return self::$defaultConfiguration; } - public static function setDefaultConfiguration(ApiConfiguration $config) { + public static function setDefaultConfiguration(ApiClientConfiguration $config) { self::$defaultConfiguration = $config; } } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 3d9ead4bed1..d276d1c652c 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -22,7 +22,7 @@ namespace {{apiNamespace}}; -use {{invokerNamespace}}\ApiConfiguration; +use {{invokerNamespace}}\ApiClientConfiguration; use {{invokerNamespace}}\ApiClient; use {{invokerNamespace}}\ApiException; use {{invokerNamespace}}\ObjectSerializer; From 8e15bd6a85e2a1cc5d04b8ac067d2daa33fbf146 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 12:13:39 -0700 Subject: [PATCH 24/39] call setHost on config --- modules/swagger-codegen/src/main/resources/php/api.mustache | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index d276d1c652c..6fb9fb5dd06 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -39,7 +39,8 @@ class {{classname}} { function __construct($apiClient = null) { if ($apiClient == null) { - $apiClient = (new ApiClient())->setHost('{{basePath}}'); + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('{{basePath}}'); } $this->apiClient = $apiClient; From bd5eb7ace39123389184a103cb404ace51cc5d79 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 12:30:52 -0700 Subject: [PATCH 25/39] update tests --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 2 ++ .../swagger-codegen/src/test/scala/php/PhpModelTest.scala | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index a9909427a0d..5317530a9eb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -41,6 +41,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("api.mustache", ".php"); templateDir = "php"; + setNamespacesFromPackages(); + reservedWords = new HashSet( Arrays.asList( "__halt_compiler", "abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "goto", "if", "implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list", "namespace", "new", "or", "print", "private", "protected", "public", "require", "require_once", "return", "static", "switch", "throw", "trait", "try", "unset", "use", "var", "while", "xor") diff --git a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala index ade8a09e80d..fae3999bbbd 100644 --- a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala @@ -142,7 +142,7 @@ class PhpModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("children") - vars.get(0).datatype should be("Children") + vars.get(0).datatype should be("\\\\Swagger\\\\Models\\\\Children") vars.get(0).name should be("children") vars.get(0).baseType should be("Children") vars.get(0).required should equal(null) @@ -166,7 +166,7 @@ class PhpModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("children") vars.get(0).complexType should be("Children") - vars.get(0).datatype should be("array[Children]") + vars.get(0).datatype should be("array[\\\\Swagger\\\\Models\\\\Children]") vars.get(0).name should be("children") vars.get(0).baseType should be("array") vars.get(0).containerType should be("array") @@ -192,7 +192,7 @@ class PhpModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("children") vars.get(0).complexType should be("Children") - vars.get(0).datatype should be("map[string,Children]") + vars.get(0).datatype should be("map[string,\\\\Swagger\\\\Models\\\\Children]") vars.get(0).name should be("children") vars.get(0).baseType should be("map") vars.get(0).containerType should be("map") From da14c9e6927ec78006e5c40c161f88a9706816f3 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 19:09:32 -0700 Subject: [PATCH 26/39] changing to invokerPackage --- .../src/main/resources/php/ApiClientConfiguration.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache index 84b901f84e9..491f5a45dd8 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache @@ -15,7 +15,7 @@ * limitations under the License. */ -namespace {{invokerNamespace}}; +namespace {{invokerPackage}}; class ApiClientConfiguration { From 4fe979a8c0e564cd8eebb123612488562fe29e2f Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 19:26:26 -0700 Subject: [PATCH 27/39] code compiles and *should* work, but need to re-organize for separate client/api-specific class namespaces --- .../codegen/languages/PhpClientCodegen.java | 155 +++++++----------- .../src/main/resources/php/ApiClient.mustache | 4 +- .../resources/php/ObjectSerializer.mustache | 2 +- .../src/main/resources/php/api.mustache | 6 +- 4 files changed, 63 insertions(+), 104 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index c362ce8da3b..88e7725578c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -24,18 +24,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String groupId = "swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = null; - protected String rootNamespace; - protected String invokerNamespace; - protected String modelNamespace; - protected String apiNamespace; public PhpClientCodegen() { super(); - rootNamespace = "Swagger"; - invokerPackage = "Client"; - modelPackage = "Models"; - apiPackage = "Api"; outputFolder = "generated-code/php"; modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); @@ -95,7 +87,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - cliOptions.add(new CliOption("rootNamespace", "root namespace from which other namespaces derive")); cliOptions.add(new CliOption("invokerPackage", "namespace for core, non-api-specific classes")); } @@ -138,20 +129,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); } - if (additionalProperties.containsKey("rootNamespace")) { - this.setRootNamespace((String) additionalProperties.get("rootNamespace")); - } - - prefixPackages(); - - // theirs - supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); - supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, "lib"), "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php")); - supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); - - // mine supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", toPackagePath(invokerPackage, "lib"), "ApiClientConfiguration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php")); @@ -160,15 +137,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); } - protected String getSrcDir(String packageName) { - return "src/" + packageName; - } - - protected void prefixPackages() { - setApiPackage(getSrcDir(apiPackage)); - setInvokerPackage(getSrcDir(invokerPackage)); - setModelPackage(getSrcDir(modelPackage)); - } +// protected String getSrcDir(String packageName) { +// return "src/" + packageName; +// } +// +// protected void prefixPackages() { +// setApiPackage(getSrcDir(apiPackage)); +// setInvokerPackage(getSrcDir(invokerPackage)); +// setModelPackage(getSrcDir(modelPackage)); +// } @Override public String escapeReservedWord(String name) { @@ -238,10 +215,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.invokerPackage = invokerPackage; } - public void setRootNamespace(String rootNamespace) { - this.rootNamespace = rootNamespace; - } - @Override public String toVarName(String name) { // parameter name starting with number won't compile @@ -279,64 +252,54 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelName(name); } - public String toNamespace(String packageName) { - return rootNamespace + "\\" + packageName.replace('/', '\\').replace('.', '\\'); - } - - protected void setNamespacesFromPackages() { - invokerNamespace = toNamespace(invokerPackage); - apiNamespace = toNamespace(apiPackage); - modelNamespace = toNamespace(modelPackage); - } - - @Override - public Map postProcessModels(Map objs) { - return addNamespaces(super.postProcessModels(objs)); - } - - @Override - public Map postProcessOperations(Map objs) { - objs = addNamespaces(super.postProcessOperations(objs)); - objs = formatImports(objs, "imports", "import"); - - return objs; - } - - @Override - public Map postProcessSupportingFileData(Map objs) { - objs = addNamespaces(super.postProcessSupportingFileData(objs)); - - return objs; - } - - protected Map addNamespaces(Map objs) { - objs.put("rootNamespace", rootNamespace); - objs.put("invokerNamespace", invokerNamespace); - objs.put("apiNamespace", apiNamespace); - objs.put("modelNamespace", modelNamespace); - - return objs; - } - - protected Map formatImports(Map objs, String objsKey, String importKey) { - if (objs.containsKey(objsKey)) { - String modelName; - List> newImportList = new ArrayList>(); - - for (Map importMap : (List>) objs.get(objsKey)) { - modelName = ((String) importMap.get(importKey)).replace(modelPackage + ".", ""); - - if (reservedWords.contains(modelName)) { - continue; - } - - importMap.put(importKey, modelNamespace + "\\" + modelName); - newImportList.add(importMap); - } - - objs.put(objsKey, newImportList); - } - - return objs; - } +// @Override +// public Map postProcessModels(Map objs) { +// return addNamespaces(super.postProcessModels(objs)); +// } +// +// @Override +// public Map postProcessOperations(Map objs) { +// objs = addNamespaces(super.postProcessOperations(objs)); +// objs = formatImports(objs, "imports", "import"); +// +// return objs; +// } +// +// @Override +// public Map postProcessSupportingFileData(Map objs) { +// objs = addNamespaces(super.postProcessSupportingFileData(objs)); +// +// return objs; +// } +// +// protected Map addNamespaces(Map objs) { +// objs.put("rootNamespace", rootNamespace); +// objs.put("invokerNamespace", invokerNamespace); +// objs.put("apiNamespace", apiNamespace); +// objs.put("modelNamespace", modelNamespace); +// +// return objs; +// } +// +// protected Map formatImports(Map objs, String objsKey, String importKey) { +// if (objs.containsKey(objsKey)) { +// String modelName; +// List> newImportList = new ArrayList>(); +// +// for (Map importMap : (List>) objs.get(objsKey)) { +// modelName = ((String) importMap.get(importKey)).replace(modelPackage + ".", ""); +// +// if (reservedWords.contains(modelName)) { +// continue; +// } +// +// importMap.put(importKey, modelNamespace + "\\" + modelName); +// newImportList.add(importMap); +// } +// +// objs.put(objsKey, newImportList); +// } +// +// return objs; +// } } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index b22c4e86a21..15726db05ea 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -15,7 +15,7 @@ * limitations under the License. */ -namespace {{invokerNamespace}}; +namespace {{invokerPackage}}; class ApiClient { @@ -77,7 +77,7 @@ class ApiClient { * @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 - * @throws \{{invokerNamespace}}\ApiException on a non 2xx response + * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams) { diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 79e7c8b356e..4880a8106d0 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -1,5 +1,5 @@ Date: Mon, 22 Jun 2015 19:34:03 -0700 Subject: [PATCH 28/39] make packagePath configureable, and remove unused code --- .../codegen/languages/PhpClientCodegen.java | 73 +++---------------- 1 file changed, 11 insertions(+), 62 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 88e7725578c..54ae637d9a9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -23,6 +23,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "Swagger\\Client"; protected String groupId = "swagger"; protected String artifactId = "swagger-client"; + protected String packagePath = "SwaggerClient-php"; protected String artifactVersion = null; public PhpClientCodegen() { @@ -88,10 +89,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("DateTime", "\\DateTime"); cliOptions.add(new CliOption("invokerPackage", "namespace for core, non-api-specific classes")); + cliOptions.add(new CliOption("packagePath", "main package name for classes")); } public String getPackagePath() { - return "SwaggerClient-php"; + return packagePath; } public String toPackagePath(String packageName, String basePath) { @@ -129,6 +131,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); } + if (additionalProperties.containsKey("packagePath")) { + this.setPackagePath((String) additionalProperties.get("packagePath")); + } + supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", toPackagePath(invokerPackage, "lib"), "ApiClientConfiguration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php")); @@ -137,16 +143,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); } -// protected String getSrcDir(String packageName) { -// return "src/" + packageName; -// } -// -// protected void prefixPackages() { -// setApiPackage(getSrcDir(apiPackage)); -// setInvokerPackage(getSrcDir(invokerPackage)); -// setModelPackage(getSrcDir(modelPackage)); -// } - @Override public String escapeReservedWord(String name) { return "_" + name; @@ -215,6 +211,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.invokerPackage = invokerPackage; } + public void setPackagePath(String packagePath) { + this.packagePath = packagePath; + } + @Override public String toVarName(String name) { // parameter name starting with number won't compile @@ -251,55 +251,4 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // should be the same as the model name return toModelName(name); } - -// @Override -// public Map postProcessModels(Map objs) { -// return addNamespaces(super.postProcessModels(objs)); -// } -// -// @Override -// public Map postProcessOperations(Map objs) { -// objs = addNamespaces(super.postProcessOperations(objs)); -// objs = formatImports(objs, "imports", "import"); -// -// return objs; -// } -// -// @Override -// public Map postProcessSupportingFileData(Map objs) { -// objs = addNamespaces(super.postProcessSupportingFileData(objs)); -// -// return objs; -// } -// -// protected Map addNamespaces(Map objs) { -// objs.put("rootNamespace", rootNamespace); -// objs.put("invokerNamespace", invokerNamespace); -// objs.put("apiNamespace", apiNamespace); -// objs.put("modelNamespace", modelNamespace); -// -// return objs; -// } -// -// protected Map formatImports(Map objs, String objsKey, String importKey) { -// if (objs.containsKey(objsKey)) { -// String modelName; -// List> newImportList = new ArrayList>(); -// -// for (Map importMap : (List>) objs.get(objsKey)) { -// modelName = ((String) importMap.get(importKey)).replace(modelPackage + ".", ""); -// -// if (reservedWords.contains(modelName)) { -// continue; -// } -// -// importMap.put(importKey, modelNamespace + "\\" + modelName); -// newImportList.add(importMap); -// } -// -// objs.put(objsKey, newImportList); -// } -// -// return objs; -// } } From d5d148365630604177043da54bc18973339af1f2 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 20:14:54 -0700 Subject: [PATCH 29/39] properly account for custom and non-custom settings for modelPackage and apiPackage --- .../codegen/languages/PhpClientCodegen.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 54ae637d9a9..72fba6c54ce 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -33,8 +33,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); templateDir = "php"; - apiPackage = invokerPackage + "\\Api"; - modelPackage = invokerPackage + "\\Model"; + apiPackage = "Api"; + modelPackage = "Model"; reservedWords = new HashSet( Arrays.asList( @@ -88,7 +88,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); typeMapping.put("DateTime", "\\DateTime"); - cliOptions.add(new CliOption("invokerPackage", "namespace for core, non-api-specific classes")); cliOptions.add(new CliOption("packagePath", "main package name for classes")); } @@ -127,14 +126,22 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { public void processOpts() { super.processOpts(); - if (additionalProperties.containsKey("invokerPackage")) { - this.setInvokerPackage((String) additionalProperties.get("invokerPackage")); - } - if (additionalProperties.containsKey("packagePath")) { this.setPackagePath((String) additionalProperties.get("packagePath")); } + if (additionalProperties.containsKey("modelPackage")) { + this.setModelPackage(invokerPackage + "\\" + additionalProperties.get("modelPackage")); + } + + if (additionalProperties.containsKey("apiPackage")) { + this.setApiPackage(invokerPackage + "\\" + additionalProperties.get("apiPackage")); + } + + additionalProperties.replace("modelPackage", modelPackage); + additionalProperties.replace("apiPackage", apiPackage); + additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); + supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", toPackagePath(invokerPackage, "lib"), "ApiClientConfiguration.php")); supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php")); supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php")); From c93b0dd3b80e9bd735e3c831f8dddbfc2a5020fa Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 20:24:19 -0700 Subject: [PATCH 30/39] make srcBasePath configureable --- .../codegen/languages/PhpClientCodegen.java | 24 ++++++++++++++----- .../src/main/resources/php/autoload.mustache | 4 ++-- .../src/main/resources/php/composer.mustache | 2 +- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 72fba6c54ce..71b0d67d215 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -25,6 +25,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String artifactId = "swagger-client"; protected String packagePath = "SwaggerClient-php"; protected String artifactVersion = null; + protected String srcBasePath = "lib"; public PhpClientCodegen() { super(); @@ -44,6 +45,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put("modelPackage", modelPackage); additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put("srcBasePath", srcBasePath); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); additionalProperties.put("groupId", groupId); additionalProperties.put("artifactId", artifactId); @@ -89,6 +91,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("DateTime", "\\DateTime"); cliOptions.add(new CliOption("packagePath", "main package name for classes")); + cliOptions.add(new CliOption("srcBasePath", "directory directory under packagePath to serve as source root")); } public String getPackagePath() { @@ -130,6 +133,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.setPackagePath((String) additionalProperties.get("packagePath")); } + if (additionalProperties.containsKey("srcBasePath")) { + this.setSrcBasePath((String) additionalProperties.get("srcBasePath")); + } + if (additionalProperties.containsKey("modelPackage")) { this.setModelPackage(invokerPackage + "\\" + additionalProperties.get("modelPackage")); } @@ -138,14 +145,15 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.setApiPackage(invokerPackage + "\\" + additionalProperties.get("apiPackage")); } + additionalProperties.replace("srcBasePath", srcBasePath); additionalProperties.replace("modelPackage", modelPackage); additionalProperties.replace("apiPackage", apiPackage); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); - supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", toPackagePath(invokerPackage, "lib"), "ApiClientConfiguration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php")); - supportingFiles.add(new SupportingFile("ObjectSerializer.mustache", toPackagePath(invokerPackage, "lib"), "ObjectSerializer.php")); + supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClientConfiguration.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("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); } @@ -157,11 +165,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return (outputFolder + "/" + toPackagePath(apiPackage(), "lib")); + return (outputFolder + "/" + toPackagePath(apiPackage(), srcBasePath)); } public String modelFileFolder() { - return (outputFolder + "/" + toPackagePath(modelPackage(), "lib")); + return (outputFolder + "/" + toPackagePath(modelPackage(), srcBasePath)); } @Override @@ -222,6 +230,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.packagePath = packagePath; } + public void setSrcBasePath(String srcBasePath) { + this.srcBasePath = srcBasePath; + } + @Override public String toVarName(String name) { // parameter name starting with number won't compile diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache index 4f56a6e20c0..04be6e11992 100644 --- a/modules/swagger-codegen/src/main/resources/php/autoload.mustache +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -4,7 +4,7 @@ * * 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/lib/Baz/Qux.php: + * from /path/to/project/{{srcBasePath}}/Baz/Qux.php: * * new \{{invokerPackage}}\Baz\Qux; * @@ -17,7 +17,7 @@ spl_autoload_register(function ($class) { $prefix = '{{escapedInvokerPackage}}\\'; // base directory for the namespace prefix - $base_dir = __DIR__ . '/lib/'; + $base_dir = __DIR__ . '/{{srcBasePath}}/'; // does the class use the namespace prefix? $len = strlen($prefix); diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index f4e38c84f73..d36267617c4 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -28,6 +28,6 @@ "squizlabs/php_codesniffer": "~2.0" }, "autoload": { - "psr-4": { "{{escapedInvokerPackage}}\\" : "lib/" } + "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } } } From 8e0142338ecf63ff1cc84f635d8edb296e650aee Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 20:36:57 -0700 Subject: [PATCH 31/39] removing unused imports --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 71b0d67d215..7a67a6c3b34 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -11,13 +11,9 @@ import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import java.io.File; -import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "Swagger\\Client"; From 5a9e9550ca9a5701a222ca89f229082efa9c60de Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 20:43:00 -0700 Subject: [PATCH 32/39] fixing php-doc --- .../swagger-codegen/src/main/resources/php/ApiClient.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 15726db05ea..e96961975d8 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -194,7 +194,7 @@ class ApiClient { /* * return the content type based on an array of content-type provided * - * @param array[string] content_type_array Array fo content-type + * @param string[] content_type_array Array fo content-type * @return string Content-Type (e.g. application/json) */ public static function selectHeaderContentType($content_type) { From 46ec934a9c065a3d4146f958d6cd171f72565002 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 20:49:12 -0700 Subject: [PATCH 33/39] java7 doesn't have replace, but put operates as such, so switch to that --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 7a67a6c3b34..9967980c53a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -141,9 +141,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { this.setApiPackage(invokerPackage + "\\" + additionalProperties.get("apiPackage")); } - additionalProperties.replace("srcBasePath", srcBasePath); - additionalProperties.replace("modelPackage", modelPackage); - additionalProperties.replace("apiPackage", apiPackage); + additionalProperties.put("srcBasePath", srcBasePath); + additionalProperties.put("modelPackage", modelPackage); + additionalProperties.put("apiPackage", apiPackage); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClientConfiguration.php")); From 6623e120cd22d6f490b8003ca3fe5488e0c0063b Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 20:53:59 -0700 Subject: [PATCH 34/39] renaming to Configuration --- .../codegen/languages/PhpClientCodegen.java | 2 +- .../src/main/resources/php/ApiClient.mustache | 10 +- .../php/ApiClientConfiguration.mustache | 257 ------------------ .../src/main/resources/php/api.mustache | 2 +- .../main/resources/php/configuration.mustache | 232 +++++++++++++++- 5 files changed, 225 insertions(+), 278 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 9967980c53a..550aa151f23 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -146,7 +146,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("apiPackage", apiPackage); additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); - supportingFiles.add(new SupportingFile("ApiClientConfiguration.mustache", toPackagePath(invokerPackage, srcBasePath), "ApiClientConfiguration.php")); + 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("ObjectSerializer.mustache", toPackagePath(invokerPackage, srcBasePath), "ObjectSerializer.php")); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index e96961975d8..488857c3a00 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -26,16 +26,16 @@ class ApiClient { public static $DELETE = "DELETE"; /** - * @var ApiClientConfiguration + * @var Configuration */ protected $config; /** - * @param ApiClientConfiguration $config config for this ApiClient + * @param Configuration $config config for this ApiClient */ - function __construct(ApiClientConfiguration $config = null) { + function __construct(Configuration $config = null) { if ($config == null) { - $config = ApiClientConfiguration::getDefaultConfiguration(); + $config = Configuration::getDefaultConfiguration(); } $this->config = $config; @@ -43,7 +43,7 @@ class ApiClient { /** * get the config - * @return ApiClientConfiguration + * @return Configuration */ public function getConfig() { return $this->config; diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache deleted file mode 100644 index 491f5a45dd8..00000000000 --- a/modules/swagger-codegen/src/main/resources/php/ApiClientConfiguration.mustache +++ /dev/null @@ -1,257 +0,0 @@ -apiKeys[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKey($key) { - return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; - } - - /** - * @param string $key - * @param string $value - * @return ApiClientConfiguration - */ - public function setApiKeyPrefix($key, $value) { - $this->apiKeyPrefixes[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKeyPrefix($key) { - return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; - } - - /** - * @param string $username - * @return ApiClientConfiguration - */ - public function setUsername($username) { - $this->username = $username; - return $this; - } - - /** - * @return string - */ - public function getUsername() { - return $this->username; - } - - /** - * @param string $password - * @return ApiClientConfiguration - */ - public function setPassword($password) { - $this->password = $password; - return $this; - } - - /** - * @return string - */ - public function getPassword() { - return $this->password; - } - - /** - * add default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * @return ApiClient - */ - public function addDefaultHeader($headerName, $headerValue) { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); - } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * get the default header - * - * @return array default header - */ - public function getDefaultHeaders() { - return $this->defaultHeaders; - } - - /** - * @param string $host - * @return ApiClientConfiguration - */ - public function setHost($host) { - $this->host = $host; - return $this; - } - - /** - * @return string - */ - public function getHost() { - return $this->host; - } - - /** - * set the user agent of the api client - * - * @param string $userAgent the user agent of the api client - * @return ApiClient - */ - public function setUserAgent($userAgent) { - if (!is_string($userAgent)) { - throw new \InvalidArgumentException('User-agent must be a string.'); - } - - $this->userAgent = $userAgent; - return $this; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() { - return $this->userAgent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - * @return ApiClient - */ - 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; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getCurlTimeout() { - return $this->curlTimeout; - } - - /** - * @param bool $debug - * @return ApiClientConfiguration - */ - public function setDebug($debug) { - $this->debug = $debug; - return $this; - } - - /** - * @return bool - */ - public function getDebug() { - return $this->debug; - } - - /** - * @param string $debugFile - * @return ApiClientConfiguration - */ - public function setDebugFile($debugFile) { - $this->debugFile = $debugFile; - return $this; - } - - /** - * @return string - */ - public function getDebugFile() { - return $this->debugFile; - } - - /** - * @return ApiClientConfiguration - */ - public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { - return new ApiClientConfiguration(); - } - - return self::$defaultConfiguration; - } - - public static function setDefaultConfiguration(ApiClientConfiguration $config) { - self::$defaultConfiguration = $config; - } -} diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index c9d21ca81b1..23f8f494aef 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -22,7 +22,7 @@ namespace {{apiPackage}}; -use \{{invokerPackage}}\ApiClientConfiguration; +use \{{invokerPackage}}\Configuration; use \{{invokerPackage}}\ApiClient; use \{{invokerPackage}}\ApiException; use \{{invokerPackage}}\ObjectSerializer; diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 030910ffca7..a0cae318c2d 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -17,37 +17,241 @@ namespace {{invokerPackage}}; -use \{{invokerPackage}}\ApiClient; - class Configuration { + private static $defaultConfiguration = null; + /** @var string[] Associate array to store API key(s) */ - public static $apiKey = array(); + protected $apiKeys = array(); /** string[] Associate array to store API prefix (e.g. Bearer) */ - public static $apiKeyPrefix = array(); + protected $apiKeyPrefixes = array(); /** @var string Username for HTTP basic authentication */ - public static $username = ''; + protected $username = ''; /** @var string Password for HTTP basic authentication */ - public static $password = ''; + protected $password = ''; /** @var \{{invokerPackage}}\ApiClient The default instance of ApiClient */ - public static $apiClient; + protected $defaultHeaders = array(); + + /** @var string The host */ + protected $host = 'http://localhost'; + + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ + protected $curlTimeout = 0; + + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ + protected $userAgent = "PHP-Swagger"; /** @var bool Debug switch (default set to false) */ - public static $debug = false; + protected $debug = false; /** @var string Debug file location (log to STDOUT by default) */ - public static $debug_file = 'php://output'; + protected $debugFile = 'php://output'; - /* - * manually initalize ApiClient + /** + * @param string $key + * @param string $value + * @return Configuration */ - public static function init() { - if (self::$apiClient === null) - self::$apiClient = new ApiClient(); + public function setApiKey($key, $value) { + $this->apiKeys[$key] = $value; + return $this; } + /** + * @param $key + * @return string + */ + public function getApiKey($key) { + return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + } + + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKeyPrefix($key, $value) { + $this->apiKeyPrefixes[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKeyPrefix($key) { + return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; + } + + /** + * @param string $username + * @return Configuration + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * @param string $password + * @return Configuration + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * add default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient + */ + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeaders() { + return $this->defaultHeaders; + } + + /** + * @param string $host + * @return Configuration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + + /** + * set the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * @return ApiClient + */ + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() { + return $this->userAgent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient + */ + 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; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getCurlTimeout() { + return $this->curlTimeout; + } + + /** + * @param bool $debug + * @return Configuration + */ + public function setDebug($debug) { + $this->debug = $debug; + return $this; + } + + /** + * @return bool + */ + public function getDebug() { + return $this->debug; + } + + /** + * @param string $debugFile + * @return Configuration + */ + public function setDebugFile($debugFile) { + $this->debugFile = $debugFile; + return $this; + } + + /** + * @return string + */ + public function getDebugFile() { + return $this->debugFile; + } + + /** + * @return Configuration + */ + public static function getDefaultConfiguration() { + if (self::$defaultConfiguration == null) { + return new Configuration(); + } + + return self::$defaultConfiguration; + } + + public static function setDefaultConfiguration(Configuration $config) { + self::$defaultConfiguration = $config; + } } From 60b0ffeb0eeb93b47bc82372f2d3204bcd5b5110 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 21:06:22 -0700 Subject: [PATCH 35/39] don't prepend the invokerPackage - an artifact from an earlier implementation --- .../io/swagger/codegen/languages/PhpClientCodegen.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 550aa151f23..20e8d20c5ed 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -30,8 +30,8 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); templateDir = "php"; - apiPackage = "Api"; - modelPackage = "Model"; + apiPackage = invokerPackage + "\\Api"; + modelPackage = invokerPackage + "\\Model"; reservedWords = new HashSet( Arrays.asList( @@ -134,11 +134,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } if (additionalProperties.containsKey("modelPackage")) { - this.setModelPackage(invokerPackage + "\\" + additionalProperties.get("modelPackage")); + this.setModelPackage((String) additionalProperties.get("modelPackage")); } if (additionalProperties.containsKey("apiPackage")) { - this.setApiPackage(invokerPackage + "\\" + additionalProperties.get("apiPackage")); + this.setApiPackage((String) additionalProperties.get("apiPackage")); } additionalProperties.put("srcBasePath", srcBasePath); From 2fced0f6342a4594c2f8a000cef9f266a2e68d66 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 21:12:13 -0700 Subject: [PATCH 36/39] Revert "Updates to csharp model template to support inheritance" This reverts commit 5f1df9e093eaf7b584c98879b4e05dcf1ac8c58f. --- .../src/main/resources/csharp/model.mustache | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index 111c98993a2..ce0e62de192 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -13,7 +13,7 @@ namespace {{package}} { /// {{description}} /// [DataContract] - public class {{classname}}{{#parent}} : {{{parent}}}{{/parent}} { + public class {{classname}} { {{#vars}} {{#description}}/* {{{description}}} */{{/description}} [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] @@ -39,11 +39,11 @@ namespace {{package}} { /// Get the JSON string presentation of the object /// /// JSON string presentation of the object - public {{#parent}} new {{/parent}}string ToJson() { + public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } {{/model}} {{/models}} -} \ No newline at end of file +} From c91a1b963bb8548f807ecbfe8b22c1e27f8f9a8a Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Mon, 22 Jun 2015 21:33:44 -0700 Subject: [PATCH 37/39] change serializer to be instanced, rather than static methods --- .../src/main/resources/php/ApiClient.mustache | 18 ++++++++--- .../resources/php/ObjectSerializer.mustache | 32 +++++++++---------- .../src/main/resources/php/api.mustache | 12 +++---- 3 files changed, 36 insertions(+), 26 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 488857c3a00..2862a0e0538 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -25,11 +25,12 @@ class ApiClient { public static $PUT = "PUT"; public static $DELETE = "DELETE"; - /** - * @var Configuration - */ + /** @var Configuration */ protected $config; + /** @var ObjectSerializer */ + protected $serializer; + /** * @param Configuration $config config for this ApiClient */ @@ -39,6 +40,7 @@ class ApiClient { } $this->config = $config; + $this->serializer = new ObjectSerializer(); } /** @@ -49,6 +51,14 @@ class ApiClient { return $this->config; } + /** + * get the serializer + * @return ObjectSerializer + */ + public function getSerializer() { + return $this->serializer; + } + /** * Get API key (with prefix if set) * @param string $apiKey name of apikey @@ -96,7 +106,7 @@ class ApiClient { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode(ObjectSerializer::sanitizeForSerialization($postData)); + $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } $url = $this->config->getHost() . $resourcePath; diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 4880a8106d0..56a61e97c91 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -8,14 +8,14 @@ class ObjectSerializer { * @param mixed $data the data to serialize * @return string serialized form of $data */ - public static function sanitizeForSerialization($data) { + public function sanitizeForSerialization($data) { if (is_scalar($data) || null === $data) { $sanitized = $data; } else if ($data instanceof \DateTime) { $sanitized = $data->format(\DateTime::ISO8601); } else if (is_array($data)) { foreach ($data as $property => $value) { - $data[$property] = self::sanitizeForSerialization($value); + $data[$property] = $this->sanitizeForSerialization($value); } $sanitized = $data; } else if (is_object($data)) { @@ -23,7 +23,7 @@ class ObjectSerializer { foreach (array_keys($data::$swaggerTypes) as $property) { $getter = $data::$getters[$property]; if ($data->$getter() !== null) { - $values[$data::$attributeMap[$property]] = self::sanitizeForSerialization($data->$getter()); + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); } } $sanitized = $values; @@ -40,8 +40,8 @@ class ObjectSerializer { * @param string $value a string which will be part of the path * @return string the serialized object */ - public static function toPathValue($value) { - return rawurlencode(self::toString($value)); + public function toPathValue($value) { + return rawurlencode($this->toString($value)); } /** @@ -52,11 +52,11 @@ class ObjectSerializer { * @param object $object an object to be serialized to a string * @return string the serialized object */ - public static function toQueryValue($object) { + public function toQueryValue($object) { if (is_array($object)) { return implode(',', $object); } else { - return self::toString($object); + return $this->toString($object); } } @@ -67,8 +67,8 @@ class ObjectSerializer { * @param string $value a string which will be part of the header * @return string the header string */ - public static function toHeaderValue($value) { - return self::toString($value); + public function toHeaderValue($value) { + return $this->toString($value); } /** @@ -78,8 +78,8 @@ class ObjectSerializer { * @param string $value the value of the form parameter * @return string the form string */ - public static function toFormValue($value) { - return self::toString($value); + public function toFormValue($value) { + return $this->toString($value); } /** @@ -89,7 +89,7 @@ class ObjectSerializer { * @param string $value the value of the parameter * @return string the header string */ - public static function toString($value) { + public function toString($value) { if ($value instanceof \DateTime) { // datetime in ISO8601 format return $value->format(\DateTime::ISO8601); } else { @@ -104,7 +104,7 @@ class ObjectSerializer { * @param string $class class name is passed as a string * @return object an instance of $class */ - public static function deserialize($data, $class) { + public function deserialize($data, $class) { if (null === $data) { $deserialized = null; } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] @@ -114,14 +114,14 @@ class ObjectSerializer { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass); + $deserialized[$key] = $this->deserialize($value, $subClass); } } } elseif (strcasecmp(substr($class, -2),'[]') == 0) { $subClass = substr($class, 0, -2); $values = array(); foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass); + $values[] = $this->deserialize($value, $subClass); } $deserialized = $values; } elseif ($class == 'DateTime') { @@ -140,7 +140,7 @@ class ObjectSerializer { $propertyValue = $data->{$instance::$attributeMap[$property]}; if (isset($propertyValue)) { - $instance->$propertySetter(self::deserialize($propertyValue, $type)); + $instance->$propertySetter($this->deserialize($propertyValue, $type)); } } $deserialized = $instance; diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 23f8f494aef..cd483ffa881 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -95,21 +95,21 @@ class {{classname}} { {{#queryParams}}// query params if(${{paramName}} !== null) { - $queryParams['{{baseName}}'] = ObjectSerializer::toQueryValue(${{paramName}}); + $queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); }{{/queryParams}} {{#headerParams}}// header params if(${{paramName}} !== null) { - $headerParams['{{baseName}}'] = ObjectSerializer::toHeaderValue(${{paramName}}); + $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); }{{/headerParams}} {{#pathParams}}// path params if(${{paramName}} !== null) { $resourcePath = str_replace("{" . "{{baseName}}" . "}", - ObjectSerializer::toPathValue(${{paramName}}), + $this->apiClient->getSerializer()->toPathValue(${{paramName}}), $resourcePath); }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}ObjectSerializer::toFormValue(${{paramName}}); + $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->getSerializer()->toFormValue(${{paramName}}); }{{/formParams}} {{#bodyParams}}// body params $_tempBody = null; @@ -140,7 +140,7 @@ class {{classname}} { } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}}{{#dataType}} case {{code}}: - $data = ObjectSerializer::deserialize($e->getResponseBody(), '{{dataType}}'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}'); $e->setResponseObject($data); break;{{/dataType}}{{/responses}} } @@ -152,7 +152,7 @@ class {{classname}} { return null; } - $responseObject = ObjectSerializer::deserialize($response,'{{returnType}}'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'{{returnType}}'); return $responseObject; {{/returnType}} } From 1b4c71c28039ead9f656f4afe22b70d635470ffe Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Tue, 23 Jun 2015 09:27:34 -0700 Subject: [PATCH 38/39] re-adding Configuration->deleteDefaultHeader --- .../src/main/resources/php/configuration.mustache | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index a0cae318c2d..b85ad289418 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -144,6 +144,15 @@ class Configuration { return $this->defaultHeaders; } + /** + * delete a default header + * @param string $headerName the header to delete + * @return Configuration + */ + public function deleteDefaultHeader($headerName) { + unset($this->defaultHeaders[$headerName]); + } + /** * @param string $host * @return Configuration From efd5b806be552c973594fb95622d1114922d02b2 Mon Sep 17 00:00:00 2001 From: nmonterroso Date: Tue, 23 Jun 2015 09:27:52 -0700 Subject: [PATCH 39/39] updating php generated samples and updating tests --- .../php/SwaggerClient-php/lib/Api/PetApi.php | 310 +++++++++++------ .../SwaggerClient-php/lib/Api/StoreApi.php | 174 ++++++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 256 ++++++++------ .../php/SwaggerClient-php/lib/ApiClient.php | 327 +++--------------- .../SwaggerClient-php/lib/ApiException.php | 28 +- .../SwaggerClient-php/lib/Configuration.php | 241 ++++++++++++- .../SwaggerClient-php/lib/Model/Category.php | 60 +++- .../php/SwaggerClient-php/lib/Model/Order.php | 156 ++++++++- .../php/SwaggerClient-php/lib/Model/Pet.php | 156 ++++++++- .../php/SwaggerClient-php/lib/Model/Tag.php | 60 +++- .../php/SwaggerClient-php/lib/Model/User.php | 204 ++++++++++- .../lib/ObjectSerializer.php | 151 ++++++++ .../SwaggerClient-php/tests/PetApiTest.php | 104 +++--- .../SwaggerClient-php/tests/StoreApiTest.php | 7 +- .../SwaggerClient-php/tests/UserApiTest.php | 7 +- 15 files changed, 1549 insertions(+), 692 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index f4f6ea8538a..e6d8fcd2c8c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -22,30 +22,28 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; use \Swagger\Client\Configuration; +use \Swagger\Client\ApiClient; +use \Swagger\Client\ApiException; +use \Swagger\Client\ObjectSerializer; class PetApi { - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration - */ - function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ private $apiClient; + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; + } + /** * @return \Swagger\Client\ApiClient get the API client */ @@ -54,10 +52,12 @@ class PetApi { } /** - * @param \Swagger\Client $apiClient set the API client + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return PetApi */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } @@ -68,6 +68,7 @@ class PetApi { * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePet($body) { @@ -80,11 +81,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); @@ -103,14 +104,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -121,6 +129,7 @@ class PetApi { * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function addPet($body) { @@ -133,11 +142,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); @@ -156,14 +165,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -174,6 +190,7 @@ class PetApi { * * @param string[] $status Status values that need to be considered for filter (required) * @return \Swagger\Client\Model\Pet[] + * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByStatus($status) { @@ -186,15 +203,15 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params if($status !== null) { - $queryParams['status'] = $this->apiClient->toQueryValue($status); + $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); } @@ -208,20 +225,33 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Pet[]'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); return $responseObject; + } /** @@ -231,6 +261,7 @@ class PetApi { * * @param string[] $tags Tags to filter by (required) * @return \Swagger\Client\Model\Pet[] + * @throws \Swagger\Client\ApiException on non-2xx response */ public function findPetsByTags($tags) { @@ -243,15 +274,15 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params if($tags !== null) { - $queryParams['tags'] = $this->apiClient->toQueryValue($tags); + $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); } @@ -265,20 +296,33 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Pet[]'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); return $responseObject; + } /** @@ -288,6 +332,7 @@ class PetApi { * * @param int $pet_id ID of pet that needs to be fetched (required) * @return \Swagger\Client\Model\Pet + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { @@ -305,18 +350,19 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } @@ -328,20 +374,40 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('api_key', 'petstore_auth'); - + + + //TODO support oauth + + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; + } + + + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Pet'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet'); return $responseObject; + } /** @@ -353,6 +419,7 @@ class PetApi { * @param string $name Updated name of the pet (required) * @param string $status Updated status of the pet (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithForm($pet_id, $name, $status) { @@ -370,25 +437,26 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/x-www-form-urlencoded')); // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } // form params if ($name !== null) { - $formParams['name'] = $this->apiClient->toFormValue($name); + $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); }// form params if ($status !== null) { - $formParams['status'] = $this->apiClient->toFormValue($status); + $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); } @@ -399,14 +467,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -418,6 +493,7 @@ class PetApi { * @param string $api_key (required) * @param int $pet_id Pet id to delete (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function deletePet($api_key, $pet_id) { @@ -435,21 +511,22 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // header params if($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key); + $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); } // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } @@ -461,14 +538,21 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -481,6 +565,7 @@ class PetApi { * @param string $additional_metadata Additional data to pass to server (required) * @param string $file file to upload (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function uploadFile($pet_id, $additional_metadata, $file) { @@ -498,25 +583,26 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('multipart/form-data')); // path params if($pet_id !== null) { $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); } // form params if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata); + $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); }// form params if ($file !== null) { - $formParams['file'] = '@' . $this->apiClient->toFormValue($file); + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); } @@ -527,16 +613,22 @@ class PetApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - + + + //TODO support oauth + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 07a922aab0a..237ba3f1acf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -22,30 +22,28 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; use \Swagger\Client\Configuration; +use \Swagger\Client\ApiClient; +use \Swagger\Client\ApiException; +use \Swagger\Client\ObjectSerializer; class StoreApi { - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration - */ - function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ private $apiClient; + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; + } + /** * @return \Swagger\Client\ApiClient get the API client */ @@ -54,10 +52,12 @@ class StoreApi { } /** - * @param \Swagger\Client $apiClient set the API client + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return StoreApi */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } @@ -67,6 +67,7 @@ class StoreApi { * Returns pet inventories by status * * @return map[string,int] + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventory() { @@ -79,11 +80,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -98,20 +99,37 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array('api_key'); - + + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; + } + + + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'map[string,int]'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'map[string,int]'); return $responseObject; + } /** @@ -121,6 +139,7 @@ class StoreApi { * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response */ public function placeOrder($body) { @@ -133,11 +152,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -156,20 +175,30 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Order'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); return $responseObject; + } /** @@ -179,6 +208,7 @@ class StoreApi { * * @param string $order_id ID of pet that needs to be fetched (required) * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderById($order_id) { @@ -196,18 +226,19 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($order_id !== null) { $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($order_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath); } @@ -219,20 +250,30 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\Order'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); return $responseObject; + } /** @@ -242,6 +283,7 @@ class StoreApi { * * @param string $order_id ID of the order that needs to be deleted (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) { @@ -259,18 +301,19 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($order_id !== null) { $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($order_id), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath); } @@ -282,16 +325,19 @@ class StoreApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index f4d35a3a7a0..1d0765bbb81 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -22,30 +22,28 @@ namespace Swagger\Client\Api; -use \Swagger\Client\ApiClient; use \Swagger\Client\Configuration; +use \Swagger\Client\ApiClient; +use \Swagger\Client\ApiException; +use \Swagger\Client\ObjectSerializer; class UserApi { - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration - */ - function __construct($apiClient = null) { - if (null === $apiClient) { - if (Configuration::$apiClient === null) { - Configuration::$apiClient = new ApiClient(); // create a new API client if not present - $this->apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ private $apiClient; + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; + } + /** * @return \Swagger\Client\ApiClient get the API client */ @@ -54,10 +52,12 @@ class UserApi { } /** - * @param \Swagger\Client $apiClient set the API client + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return UserApi */ - public function setApiClient($apiClient) { + public function setApiClient(ApiClient $apiClient) { $this->apiClient = $apiClient; + return $this; } @@ -68,6 +68,7 @@ class UserApi { * * @param \Swagger\Client\Model\User $body Created user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUser($body) { @@ -80,11 +81,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -103,14 +104,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -121,6 +126,7 @@ class UserApi { * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithArrayInput($body) { @@ -133,11 +139,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -156,14 +162,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -174,6 +184,7 @@ class UserApi { * * @param \Swagger\Client\Model\User[] $body List of user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function createUsersWithListInput($body) { @@ -186,11 +197,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -209,14 +220,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -228,6 +243,7 @@ class UserApi { * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) * @return string + * @throws \Swagger\Client\ApiException on non-2xx response */ public function loginUser($username, $password) { @@ -240,18 +256,18 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params if($username !== null) { - $queryParams['username'] = $this->apiClient->toQueryValue($username); + $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); }// query params if($password !== null) { - $queryParams['password'] = $this->apiClient->toQueryValue($password); + $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); } @@ -265,20 +281,30 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'string'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'string'); return $responseObject; + } /** @@ -287,6 +313,7 @@ class UserApi { * Logs out current logged in user session * * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUser() { @@ -299,11 +326,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); @@ -318,14 +345,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -336,6 +367,7 @@ class UserApi { * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @return \Swagger\Client\Model\User + * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByName($username) { @@ -353,18 +385,19 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($username !== null) { $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); } @@ -376,20 +409,30 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - if(! $response) { + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User'); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { return null; } - $responseObject = $this->apiClient->deserialize($response,'\Swagger\Client\Model\User'); + $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\User'); return $responseObject; + } /** @@ -400,6 +443,7 @@ class UserApi { * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function updateUser($username, $body) { @@ -417,18 +461,19 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($username !== null) { $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); } // body params @@ -444,14 +489,18 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } @@ -462,6 +511,7 @@ class UserApi { * * @param string $username The name that needs to be deleted (required) * @return void + * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUser($username) { @@ -479,18 +529,19 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // path params if($username !== null) { $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); } @@ -502,16 +553,19 @@ class UserApi { // for HTTP post (form) $httpBody = $formParams; } - - // authentication setting, if any - $authSettings = array(); - + // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); + try { + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } } - } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index bb5229fb170..66204f0c4f3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -25,146 +25,60 @@ class ApiClient { public static $PUT = "PUT"; public static $DELETE = "DELETE"; - /** @var string[] Array of default headers where the key is the header name and the value is the header value */ - private $default_header = array(); + /** @var Configuration */ + protected $config; - /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ - protected $curl_timeout = 0; - - /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ - protected $user_agent = "PHP-Swagger"; + /** @var ObjectSerializer */ + protected $serializer; /** - * @param string $host Base url of the API server (optional) + * @param Configuration $config config for this ApiClient */ - function __construct($host = null) { - if ($host === null) { - $this->host = 'http://petstore.swagger.io/v2'; - } else { - $this->host = $host; + function __construct(Configuration $config = null) { + if ($config == null) { + $config = Configuration::getDefaultConfiguration(); } + + $this->config = $config; + $this->serializer = new ObjectSerializer(); } /** - * add default header - * - * @param string $header_name header name (e.g. Token) - * @param string $header_value header value (e.g. 1z8wp3) + * get the config + * @return Configuration */ - public function addDefaultHeader($header_name, $header_value) { - if (!is_string($header_name)) - throw new \InvalidArgumentException('Header name must be a string.'); - - $this->default_header[$header_name] = $header_value; + public function getConfig() { + return $this->config; } /** - * get the default header - * - * @return array default header + * get the serializer + * @return ObjectSerializer */ - public function getDefaultHeader() { - return $this->default_header; + public function getSerializer() { + return $this->serializer; } - /** - * delete the default header based on header name - * - * @param string $header_name header name (e.g. Token) - */ - public function deleteDefaultHeader($header_name) { - unset($this->default_header[$header_name]); - } - - /** - * set the user agent of the api client - * - * @param string $user_agent the user agent of the api client - */ - public function setUserAgent($user_agent) { - if (!is_string($user_agent)) - throw new \InvalidArgumentException('User-agent must be a string.'); - - $this->user_agent= $user_agent; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent($user_agent) { - return $this->user_agent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ - public function setTimeout($seconds) { - if (!is_numeric($seconds) || $seconds < 0) - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); - - $this->curl_timeout = $seconds; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getTimeout() { - return $this->curl_timeout; - } - - /** * Get API key (with prefix if set) - * @param string key name + * @param string $apiKey name of apikey * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { - if (isset(Configuration::$apiKeyPrefix[$apiKey])) { - return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; - } else if (isset(Configuration::$apiKey[$apiKey])) { - return Configuration::$apiKey[$apiKey]; + $prefix = $this->config->getApiKeyPrefix($apiKey); + $apiKey = $this->config->getApiKey($apiKey); + + if (!isset($apiKey)) { + return null; + } + + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; } else { - return; + $keyWithPrefix = $apiKey; } - } - /** - * update hearder and query param based on authentication setting - * - * @param array $headerParams header parameters (by ref) - * @param array $queryParams query parameters (by ref) - * @param array $authSettings array of authentication scheme (e.g ['api_key']) - */ - public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) - { - if (count($authSettings) == 0) - return; - - // one endpoint can have more than 1 auth settings - foreach($authSettings as $auth) { - // determine which one to use - switch($auth) { - - case 'api_key': - $headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key'); - - break; - - case 'petstore_auth': - - //TODO support oauth - break; - - default: - //TODO show warning about security definition not found - } - } + return $keyWithPrefix; } /** @@ -173,18 +87,15 @@ class ApiClient { * @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 + * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, - $headerParams, $authSettings) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams) { $headers = array(); - # determine authentication setting - $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - # construct the http header - $headerParams = array_merge((array)$this->default_header, (array)$headerParams); + $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; @@ -195,15 +106,15 @@ class ApiClient { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->sanitizeForSerialization($postData)); + $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } - $url = $this->host . $resourcePath; + $url = $this->config->getHost() . $resourcePath; $curl = curl_init(); // set timeout, if needed - if ($this->curl_timeout != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout); + if ($this->config->getCurlTimeout() != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -232,14 +143,14 @@ class ApiClient { curl_setopt($curl, CURLOPT_URL, $url); // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); + curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); // debugging for curl - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); + curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } @@ -255,8 +166,8 @@ class ApiClient { $response_info = curl_getinfo($curl); // debug HTTP response body - if (Configuration::$debug) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); } // Handle the response @@ -274,153 +185,13 @@ class ApiClient { return $data; } - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - if ($data->$property !== null) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); - } - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - - return $sanitized; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public function toPathValue($value) { - return rawurlencode($this->toString($value)); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return $this->toString($object); - } - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the header. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value a string which will be part of the header - * @return string the header string - */ - public function toHeaderValue($value) { - return $this->toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the http body (form parameter). If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the form parameter - * @return string the form string - */ - public function toFormValue($value) { - return $this->toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the parameter. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * @param string $value the value of the parameter - * @return string the header string - */ - public function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } - else { - return $value; - } - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - public function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] - $inner = substr($class, 4, -1); - $deserialized = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = $this->deserialize($value, $subClass); - } - } - } elseif (strcasecmp(substr($class, -2),'[]') == 0) { - $subClass = substr($class, 0, -2); - $values = array(); - foreach ($data as $key => $value) { - $values[] = $this->deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $original_property_name = $instance::$attributeMap[$property]; - if (isset($original_property_name) && isset($data->$original_property_name)) { - $instance->$property = $this->deserialize($data->$original_property_name, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; - } - /* * return the header 'Accept' based on an array of Accept provided * - * @param array[string] $accept Array of header + * @param string[] $accept Array of header * @return string Accept (e.g. application/json) */ - public function selectHeaderAccept($accept) { + public static function selectHeaderAccept($accept) { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { return NULL; } elseif (preg_grep("/application\/json/i", $accept)) { @@ -433,10 +204,10 @@ class ApiClient { /* * return the content type based on an array of content-type provided * - * @param array[string] content_type_array Array fo content-type + * @param string[] content_type_array Array fo content-type * @return string Content-Type (e.g. application/json) */ - public function selectHeaderContentType($content_type) { + public static 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)) { @@ -445,6 +216,4 @@ class ApiClient { return implode(',', $content_type); } } - } - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 5f3b1812261..51774137aed 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -22,15 +22,20 @@ use \Exception; class ApiException extends Exception { /** @var string The HTTP body of the server response. */ - protected $response_body; + protected $responseBody; /** @var string[] The HTTP header of the server response. */ - protected $response_headers; + protected $responseHeaders; + + /** + * The deserialized response object + */ + protected $responseObject; public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { parent::__construct($message, $code); - $this->response_headers = $responseHeaders; - $this->response_body = $responseBody; + $this->responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; } /** @@ -39,7 +44,7 @@ class ApiException extends Exception { * @return string HTTP response header */ public function getResponseHeaders() { - return $this->response_headers; + return $this->responseHeaders; } /** @@ -48,7 +53,18 @@ class ApiException extends Exception { * @return string HTTP response body */ public function getResponseBody() { - return $this->response_body; + return $this->responseBody; } + /** + * sets the deseralized response object (during deserialization) + * @param mixed $obj + */ + public function setResponseObject($obj) { + $this->responseObject = $obj; + } + + public function getResponseObject() { + return $this->responseObject; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index e6381781bb0..a407fe4dd49 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -17,37 +17,250 @@ namespace Swagger\Client; -use \Swagger\Client\ApiClient; - class Configuration { + private static $defaultConfiguration = null; + /** @var string[] Associate array to store API key(s) */ - public static $apiKey = array(); + protected $apiKeys = array(); /** string[] Associate array to store API prefix (e.g. Bearer) */ - public static $apiKeyPrefix = array(); + protected $apiKeyPrefixes = array(); /** @var string Username for HTTP basic authentication */ - public static $username = ''; + protected $username = ''; /** @var string Password for HTTP basic authentication */ - public static $password = ''; + protected $password = ''; /** @var \Swagger\Client\ApiClient The default instance of ApiClient */ - public static $apiClient; + protected $defaultHeaders = array(); + + /** @var string The host */ + protected $host = 'http://localhost'; + + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ + protected $curlTimeout = 0; + + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ + protected $userAgent = "PHP-Swagger"; /** @var bool Debug switch (default set to false) */ - public static $debug = false; + protected $debug = false; /** @var string Debug file location (log to STDOUT by default) */ - public static $debug_file = 'php://output'; + protected $debugFile = 'php://output'; - /* - * manually initalize ApiClient + /** + * @param string $key + * @param string $value + * @return Configuration */ - public static function init() { - if (self::$apiClient === null) - self::$apiClient = new ApiClient(); + public function setApiKey($key, $value) { + $this->apiKeys[$key] = $value; + return $this; } + /** + * @param $key + * @return string + */ + public function getApiKey($key) { + return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + } + + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKeyPrefix($key, $value) { + $this->apiKeyPrefixes[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKeyPrefix($key) { + return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; + } + + /** + * @param string $username + * @return Configuration + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * @param string $password + * @return Configuration + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * add default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient + */ + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeaders() { + return $this->defaultHeaders; + } + + /** + * delete a default header + * @param string $headerName the header to delete + * @return Configuration + */ + public function deleteDefaultHeader($headerName) { + unset($this->defaultHeaders[$headerName]); + } + + /** + * @param string $host + * @return Configuration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + + /** + * set the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * @return ApiClient + */ + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() { + return $this->userAgent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient + */ + 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; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getCurlTimeout() { + return $this->curlTimeout; + } + + /** + * @param bool $debug + * @return Configuration + */ + public function setDebug($debug) { + $this->debug = $debug; + return $this; + } + + /** + * @return bool + */ + public function getDebug() { + return $this->debug; + } + + /** + * @param string $debugFile + * @return Configuration + */ + public function setDebugFile($debugFile) { + $this->debugFile = $debugFile; + return $this; + } + + /** + * @return string + */ + public function getDebugFile() { + return $this->debugFile; + } + + /** + * @return Configuration + */ + public static function getDefaultConfiguration() { + if (self::$defaultConfiguration == null) { + return new Configuration(); + } + + return self::$defaultConfiguration; + } + + public static function setDefaultConfiguration(Configuration $config) { + self::$defaultConfiguration = $config; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 750a8fee5df..75aaf2eeead 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -38,21 +38,69 @@ class Category implements ArrayAccess { 'id' => 'id', 'name' => 'name' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'name' => 'setName' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'name' => 'getName' + ); + /** @var int $id */ - public $id; + protected $id; /** @var string $name */ - public $name; + protected $name; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->name = @$data["name"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 64552afb763..c7a433c3d8c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -46,37 +46,165 @@ class Order implements ArrayAccess { 'status' => 'status', 'complete' => 'complete' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'pet_id' => 'setPetId', + 'quantity' => 'setQuantity', + 'ship_date' => 'setShipDate', + 'status' => 'setStatus', + 'complete' => 'setComplete' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'pet_id' => 'getPetId', + 'quantity' => 'getQuantity', + 'ship_date' => 'getShipDate', + 'status' => 'getStatus', + 'complete' => 'getComplete' + ); + /** @var int $id */ - public $id; + protected $id; /** @var int $pet_id */ - public $pet_id; + protected $pet_id; /** @var int $quantity */ - public $quantity; + protected $quantity; /** @var \DateTime $ship_date */ - public $ship_date; + protected $ship_date; /** @var string $status Order Status */ - public $status; + protected $status; /** @var bool $complete */ - public $complete; + protected $complete; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->pet_id = $data["pet_id"]; + $this->quantity = $data["quantity"]; + $this->ship_date = $data["ship_date"]; + $this->status = $data["status"]; + $this->complete = $data["complete"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->pet_id = @$data["pet_id"]; - $this->quantity = @$data["quantity"]; - $this->ship_date = @$data["ship_date"]; - $this->status = @$data["status"]; - $this->complete = @$data["complete"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get pet_id + * @return int + */ + public function getPetId() { + return $this->pet_id; + } + + /** + * set pet_id + * @param int $pet_id + * @return $this + */ + public function setPetId($pet_id) { + $this->pet_id = $pet_id; + return $this; + } + + /** + * get quantity + * @return int + */ + public function getQuantity() { + return $this->quantity; + } + + /** + * set quantity + * @param int $quantity + * @return $this + */ + public function setQuantity($quantity) { + $this->quantity = $quantity; + return $this; + } + + /** + * get ship_date + * @return \DateTime + */ + public function getShipDate() { + return $this->ship_date; + } + + /** + * set ship_date + * @param \DateTime $ship_date + * @return $this + */ + public function setShipDate($ship_date) { + $this->ship_date = $ship_date; + return $this; + } + + /** + * get status + * @return string + */ + public function getStatus() { + return $this->status; + } + + /** + * set status + * @param string $status + * @return $this + */ + public function setStatus($status) { + $this->status = $status; + return $this; + } + + /** + * get complete + * @return bool + */ + public function getComplete() { + return $this->complete; + } + + /** + * set complete + * @param bool $complete + * @return $this + */ + public function setComplete($complete) { + $this->complete = $complete; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index ef2a4c76a0d..cbe27e1fce9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -46,37 +46,165 @@ class Pet implements ArrayAccess { 'tags' => 'tags', 'status' => 'status' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'category' => 'setCategory', + 'name' => 'setName', + 'photo_urls' => 'setPhotoUrls', + 'tags' => 'setTags', + 'status' => 'setStatus' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'category' => 'getCategory', + 'name' => 'getName', + 'photo_urls' => 'getPhotoUrls', + 'tags' => 'getTags', + 'status' => 'getStatus' + ); + /** @var int $id */ - public $id; + protected $id; /** @var \Swagger\Client\Model\Category $category */ - public $category; + protected $category; /** @var string $name */ - public $name; + protected $name; /** @var string[] $photo_urls */ - public $photo_urls; + protected $photo_urls; /** @var \Swagger\Client\Model\Tag[] $tags */ - public $tags; + protected $tags; /** @var string $status pet status in the store */ - public $status; + protected $status; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->category = $data["category"]; + $this->name = $data["name"]; + $this->photo_urls = $data["photo_urls"]; + $this->tags = $data["tags"]; + $this->status = $data["status"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->category = @$data["category"]; - $this->name = @$data["name"]; - $this->photo_urls = @$data["photo_urls"]; - $this->tags = @$data["tags"]; - $this->status = @$data["status"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get category + * @return \Swagger\Client\Model\Category + */ + public function getCategory() { + return $this->category; + } + + /** + * set category + * @param \Swagger\Client\Model\Category $category + * @return $this + */ + public function setCategory($category) { + $this->category = $category; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + + /** + * get photo_urls + * @return string[] + */ + public function getPhotoUrls() { + return $this->photo_urls; + } + + /** + * set photo_urls + * @param string[] $photo_urls + * @return $this + */ + public function setPhotoUrls($photo_urls) { + $this->photo_urls = $photo_urls; + return $this; + } + + /** + * get tags + * @return \Swagger\Client\Model\Tag[] + */ + public function getTags() { + return $this->tags; + } + + /** + * set tags + * @param \Swagger\Client\Model\Tag[] $tags + * @return $this + */ + public function setTags($tags) { + $this->tags = $tags; + return $this; + } + + /** + * get status + * @return string + */ + public function getStatus() { + return $this->status; + } + + /** + * set status + * @param string $status + * @return $this + */ + public function setStatus($status) { + $this->status = $status; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 5959cb20a6a..3fd785f001b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -38,21 +38,69 @@ class Tag implements ArrayAccess { 'id' => 'id', 'name' => 'name' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'name' => 'setName' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'name' => 'getName' + ); + /** @var int $id */ - public $id; + protected $id; /** @var string $name */ - public $name; + protected $name; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->name = @$data["name"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 1bfb7f332db..2bb31056bde 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -50,45 +50,213 @@ class User implements ArrayAccess { 'phone' => 'phone', 'user_status' => 'userStatus' ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'username' => 'setUsername', + 'first_name' => 'setFirstName', + 'last_name' => 'setLastName', + 'email' => 'setEmail', + 'password' => 'setPassword', + 'phone' => 'setPhone', + 'user_status' => 'setUserStatus' + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'username' => 'getUsername', + 'first_name' => 'getFirstName', + 'last_name' => 'getLastName', + 'email' => 'getEmail', + 'password' => 'getPassword', + 'phone' => 'getPhone', + 'user_status' => 'getUserStatus' + ); + /** @var int $id */ - public $id; + protected $id; /** @var string $username */ - public $username; + protected $username; /** @var string $first_name */ - public $first_name; + protected $first_name; /** @var string $last_name */ - public $last_name; + protected $last_name; /** @var string $email */ - public $email; + protected $email; /** @var string $password */ - public $password; + protected $password; /** @var string $phone */ - public $phone; + protected $phone; /** @var int $user_status User Status */ - public $user_status; + protected $user_status; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->username = $data["username"]; + $this->first_name = $data["first_name"]; + $this->last_name = $data["last_name"]; + $this->email = $data["email"]; + $this->password = $data["password"]; + $this->phone = $data["phone"]; + $this->user_status = $data["user_status"]; + } + } /** - * @param mixed[] Array of parameters to initialize the object with + * get id + * @return int */ - public function __construct(array $data = null) { - $this->id = @$data["id"]; - $this->username = @$data["username"]; - $this->first_name = @$data["first_name"]; - $this->last_name = @$data["last_name"]; - $this->email = @$data["email"]; - $this->password = @$data["password"]; - $this->phone = @$data["phone"]; - $this->user_status = @$data["user_status"]; + public function getId() { + return $this->id; } + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get username + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * set username + * @param string $username + * @return $this + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * get first_name + * @return string + */ + public function getFirstName() { + return $this->first_name; + } + + /** + * set first_name + * @param string $first_name + * @return $this + */ + public function setFirstName($first_name) { + $this->first_name = $first_name; + return $this; + } + + /** + * get last_name + * @return string + */ + public function getLastName() { + return $this->last_name; + } + + /** + * set last_name + * @param string $last_name + * @return $this + */ + public function setLastName($last_name) { + $this->last_name = $last_name; + return $this; + } + + /** + * get email + * @return string + */ + public function getEmail() { + return $this->email; + } + + /** + * set email + * @param string $email + * @return $this + */ + public function setEmail($email) { + $this->email = $email; + return $this; + } + + /** + * get password + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * set password + * @param string $password + * @return $this + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * get phone + * @return string + */ + public function getPhone() { + return $this->phone; + } + + /** + * set phone + * @param string $phone + * @return $this + */ + public function setPhone($phone) { + $this->phone = $phone; + return $this; + } + + /** + * get user_status + * @return int + */ + public function getUserStatus() { + return $this->user_status; + } + + /** + * set user_status + * @param int $user_status + * @return $this + */ + public function setUserStatus($user_status) { + $this->user_status = $user_status; + return $this; + } + public function offsetExists($offset) { return isset($this->$offset); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php new file mode 100644 index 00000000000..802a49bc01a --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -0,0 +1,151 @@ +format(\DateTime::ISO8601); + } else if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = $this->sanitizeForSerialization($value); + } + $sanitized = $data; + } else if (is_object($data)) { + $values = array(); + foreach (array_keys($data::$swaggerTypes) as $property) { + $getter = $data::$getters[$property]; + if ($data->$getter() !== null) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); + } + } + $sanitized = $values; + } else { + $sanitized = (string)$data; + } + + return $sanitized; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public function toPathValue($value) { + return rawurlencode($this->toString($value)); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * @param object $object an object to be serialized to a string + * @return string the serialized object + */ + public function toQueryValue($object) { + if (is_array($object)) { + return implode(',', $object); + } else { + return $this->toString($object); + } + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the header. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value a string which will be part of the header + * @return string the header string + */ + public function toHeaderValue($value) { + return $this->toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the http body (form parameter). If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the form parameter + * @return string the form string + */ + public function toFormValue($value) { + return $this->toString($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the parameter. If it's a string, pass through unchanged + * If it's a datetime object, format it in ISO8601 + * @param string $value the value of the parameter + * @return string the header string + */ + public function toString($value) { + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } else { + return $value; + } + } + + /** + * Deserialize a JSON string into an object + * + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ + public function deserialize($data, $class) { + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = $this->deserialize($value, $subClass); + } + } + } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + $subClass = substr($class, 0, -2); + $values = array(); + foreach ($data as $key => $value) { + $values[] = $this->deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + $propertySetter = $instance::$setters[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::$attributeMap[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter($this->deserialize($propertyValue, $type)); + } + } + $deserialized = $instance; + } + + return $deserialized; + } +} \ No newline at end of file diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 131a79dba92..3ac28772291 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -22,19 +22,19 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // new pet $new_pet_id = 10005; $new_pet = new Swagger\Client\Model\Pet; - $new_pet->id = $new_pet_id; - $new_pet->name = "PHP Unit Test"; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); // new tag $tag= new Swagger\Client\Model\Tag; - $tag->id = $new_pet_id; // use the same id as pet - $tag->name = "test php tag"; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("test php tag"); // new category $category = new Swagger\Client\Model\Category; - $category->id = $new_pet_id; // use the same id as pet - $category->name = "test php category"; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("test php category"); - $new_pet->tags = array($tag); - $new_pet->category = $category; + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); $pet_api = new Swagger\Client\Api\PetAPI(); // add a new pet (model) @@ -56,65 +56,53 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); // test addDefaultHeader and getDefaultHeader - $api_client->addDefaultHeader('test1', 'value1'); - $api_client->addDefaultHeader('test2', 200); - $defaultHeader = $api_client->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->deleteDefaultHeader('test2'); - $defaultHeader = $api_client->getDefaultHeader(); + $api_client->getConfig()->deleteDefaultHeader('test2'); + $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); $this->assertFalse(isset($defaultHeader['test2'])); - $pet_api = new Swagger\Client\Api\PetAPI(); $pet_api2 = new Swagger\Client\Api\PetAPI(); $apiClient3 = new Swagger\Client\ApiClient(); - $apiClient3->setUserAgent = 'api client 3'; + $apiClient3->getConfig()->setUserAgent('api client 3'); $apiClient4 = new Swagger\Client\ApiClient(); - $apiClient4->setUserAgent = 'api client 4'; + $apiClient4->getConfig()->setUserAgent('api client 4'); $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); - // same default api client - $this->assertSame($pet_api->getApiClient(), $pet_api2->getApiClient()); - // confirm using the default api client in the Configuration - $this->assertSame($pet_api->getApiClient(), Swagger\Client\Configuration::$apiClient); // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); - // customized pet api not using the default (configuration) api client - $this->assertNotEquals($pet_api3->getApiClient(), Swagger\Client\Configuration::$apiClient); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); - - // both pet api and pet api2 share the same api client and confirm using timeout value - $pet_api->getApiClient()->setTimeout(999); - $this->assertSame(999, $pet_api2->getApiClient()->getTimeout()); - } // test getPetById with a Pet object (id 10005) public function testGetPetById() { // initialize the API client without host - $api_client = new Swagger\Client\ApiClient(); - Swagger\Client\Configuration::$apiKey['api_key'] = '111222333444555'; $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); // return Pet (model) $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->id, $pet_id); - $this->assertSame($response->name, 'PHP Unit Test'); - $this->assertSame($response->category->id, $pet_id); - $this->assertSame($response->category->name, 'test php category'); - $this->assertSame($response->tags[0]->id, $pet_id); - $this->assertSame($response->tags[0]->name, 'test php tag'); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + $this->assertSame($response->getCategory()->getId(), $pet_id); + $this->assertSame($response->getCategory()->getName(), 'test php category'); + $this->assertSame($response->getTags()[0]->getId(), $pet_id); + $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); } // test getPetByStatus and verify by the "id" of the response public function testFindPetByStatus() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_api = new Swagger\Client\Api\PetAPI($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); @@ -133,30 +121,32 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePet() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new Swagger\Client\Api\PetAPI($api_client); // create updated pet object $updated_pet = new Swagger\Client\Model\Pet; - $updated_pet->id = $pet_id; - $updated_pet->name = 'updatePet'; // new name - $updated_pet->status = 'pending'; // new status + $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 $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->id, $pet_id); - $this->assertSame($response->status, 'pending'); - $this->assertSame($response->name, 'updatePet'); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getStatus(), 'pending'); + $this->assertSame($response->getName(), 'updatePet'); } // test updatePet and verify by the "id" of the response public function testUpdatePetWithForm() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new Swagger\Client\Api\PetAPI($api_client); // update Pet (form) @@ -164,20 +154,21 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // return nothing (void) $this->assertSame($update_response, NULL); $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->id, $pet_id); - $this->assertSame($response->name, 'update pet with form'); - $this->assertSame($response->status, 'sold'); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form'); + $this->assertSame($response->getStatus(), 'sold'); } // test addPet and verify by the "id" and "name" of the response public function testAddPet() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $new_pet_id = 10001; $new_pet = new Swagger\Client\Model\Pet; - $new_pet->id = $new_pet_id; - $new_pet->name = "PHP Unit Test"; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); $pet_api = new Swagger\Client\Api\PetAPI($api_client); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); @@ -185,15 +176,16 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($add_response, NULL); // verify added Pet $response = $pet_api->getPetById($new_pet_id); - $this->assertSame($response->id, $new_pet_id); - $this->assertSame($response->name, 'PHP Unit Test'); + $this->assertSame($response->getId(), $new_pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); } // test upload file public function testUploadFile() { // initialize the API client - $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); $pet_api = new Swagger\Client\Api\PetAPI($api_client); // upload file $pet_id = 10001; @@ -206,7 +198,9 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $api_client = new Swagger\Client\APIClient('http://petstore.swagger.io/v2'); + $config = new Swagger\Client\Configuration(); + $config->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\APIClient($config); $store_api = new Swagger\Client\Api\StoreAPI($api_client); // get inventory $get_response = $store_api->getInventory(); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index a92149fbaf3..05bd873c993 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -1,6 +1,6 @@ setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $store_api = new Swagger\Client\Api\StoreAPI($api_client); // get inventory $get_response = $store_api->getInventory(); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php index 181e8a1249e..3efce8b08ba 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/UserApiTest.php @@ -1,6 +1,6 @@ setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $user_api = new Swagger\Client\Api\UserApi($api_client); // login $response = $user_api->loginUser("xxxxx", "yyyyyyyy");