diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index ce0110daf736..e1c0733a2982 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -33,7 +33,6 @@ import io.swagger.v3.oas.models.responses.ApiResponses; import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.parser.core.models.ParseOptions; - import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.config.GlobalSettings; import org.openapitools.codegen.model.ModelMap; @@ -3717,7 +3716,7 @@ public void testComposedPropertyTypes() { modelName = "ObjectWithComposedProperties"; CodegenModel m = codegen.fromModel(modelName, openAPI.getComponents().getSchemas().get(modelName)); /* TODO inline allOf schema are created as separate models and the following assumptions that - the properties are non-model are no longer valid and need to be revised + the properties are non-model are no longer valid and need to be revised assertTrue(m.vars.get(0).getIsMap()); assertTrue(m.vars.get(1).getIsNumber()); assertTrue(m.vars.get(2).getIsUnboundedInteger()); @@ -4216,6 +4215,12 @@ public void testNullabelObjectProperties() { String propertyName; CodegenProperty property; + // Non regression on regular oneOf construct + propertyName = "nonNullableProperty"; + property = codegen.fromProperty(propertyName, (Schema) schema.getProperties().get(propertyName)); + assertEquals(property.openApiType, "oneOf"); + // oneOf property resolve to any type and is set to nullable + // openapi 3.0 nullable propertyName = "propertyName30"; property = codegen.fromProperty(propertyName, (Schema) schema.getProperties().get(propertyName)); @@ -4227,11 +4232,5 @@ public void testNullabelObjectProperties() { property = codegen.fromProperty(propertyName, (Schema) schema.getProperties().get(propertyName)); assertEquals(property.openApiType, "PropertyType"); assertTrue(property.isNullable); - - // Non regression on regular oneOf construct - propertyName = "nonNullableProperty"; - property = codegen.fromProperty(propertyName, (Schema) schema.getProperties().get(propertyName)); - assertEquals(property.openApiType, "oneOf"); - // oneOf property resolve to any type and is set to nullable } } diff --git a/samples/client/petstore/java/nullable-object-property/.github/workflows/maven.yml b/samples/client/petstore/java/nullable-object-property/.github/workflows/maven.yml new file mode 100644 index 000000000000..0d6b2f82a92c --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build Title + runs-on: ubuntu-latest + strategy: + matrix: + java: [ '8' ] + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml diff --git a/samples/client/petstore/java/nullable-object-property/.openapi-generator/FILES b/samples/client/petstore/java/nullable-object-property/.openapi-generator/FILES index c61d42af6108..3504cb74ffe4 100644 --- a/samples/client/petstore/java/nullable-object-property/.openapi-generator/FILES +++ b/samples/client/petstore/java/nullable-object-property/.openapi-generator/FILES @@ -1,3 +1,4 @@ +.github/workflows/maven.yml .gitignore .travis.yml README.md @@ -6,6 +7,10 @@ build.gradle build.sbt docs/DefaultApi.md docs/ModelWithNullableObjectProperty.md +docs/ModelWithNullableObjectPropertyNonNullableProperty.md +docs/ModelWithNullableObjectPropertyPropertyName30.md +docs/ModelWithNullableObjectPropertyPropertyName31.md +docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md docs/OtherPropertyType.md docs/PropertyType.md git_push.sh @@ -29,5 +34,9 @@ src/main/java/org/openapitools/client/ServerVariable.java src/main/java/org/openapitools/client/api/DefaultApi.java src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java src/main/java/org/openapitools/client/model/ModelWithNullableObjectProperty.java +src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyNonNullableProperty.java +src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName30.java +src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName31.java +src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.java src/main/java/org/openapitools/client/model/OtherPropertyType.java src/main/java/org/openapitools/client/model/PropertyType.java diff --git a/samples/client/petstore/java/nullable-object-property/.openapi-generator/VERSION b/samples/client/petstore/java/nullable-object-property/.openapi-generator/VERSION index 4077803655c0..89648de3311c 100644 --- a/samples/client/petstore/java/nullable-object-property/.openapi-generator/VERSION +++ b/samples/client/petstore/java/nullable-object-property/.openapi-generator/VERSION @@ -1 +1 @@ -5.3.1-SNAPSHOT \ No newline at end of file +6.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/nullable-object-property/README.md b/samples/client/petstore/java/nullable-object-property/README.md index d8cdb9c9f1d8..fe3c5711706c 100644 --- a/samples/client/petstore/java/nullable-object-property/README.md +++ b/samples/client/petstore/java/nullable-object-property/README.md @@ -111,6 +111,10 @@ Class | Method | HTTP request | Description ## Documentation for Models - [ModelWithNullableObjectProperty](docs/ModelWithNullableObjectProperty.md) + - [ModelWithNullableObjectPropertyNonNullableProperty](docs/ModelWithNullableObjectPropertyNonNullableProperty.md) + - [ModelWithNullableObjectPropertyPropertyName30](docs/ModelWithNullableObjectPropertyPropertyName30.md) + - [ModelWithNullableObjectPropertyPropertyName31](docs/ModelWithNullableObjectPropertyPropertyName31.md) + - [ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes](docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md) - [OtherPropertyType](docs/OtherPropertyType.md) - [PropertyType](docs/PropertyType.md) diff --git a/samples/client/petstore/java/nullable-object-property/api/openapi.yaml b/samples/client/petstore/java/nullable-object-property/api/openapi.yaml index be298c2c30a6..8c39e55421a9 100644 --- a/samples/client/petstore/java/nullable-object-property/api/openapi.yaml +++ b/samples/client/petstore/java/nullable-object-property/api/openapi.yaml @@ -22,30 +22,21 @@ components: example: propertyName: foo: foo - nonNullableProperty: "" - propertyName31: "" - propertyName30: "" - propertyWithNullAndTwoTypes: "" + nonNullableProperty: null + propertyName31: null + propertyName30: null + propertyWithNullAndTwoTypes: null properties: propertyName: $ref: '#/components/schemas/PropertyType' propertyName30: - nullable: true - oneOf: - - $ref: '#/components/schemas/PropertyType' + $ref: '#/components/schemas/ModelWithNullableObjectProperty_propertyName30' propertyName31: - oneOf: - - type: "null" - - $ref: '#/components/schemas/PropertyType' + $ref: '#/components/schemas/ModelWithNullableObjectProperty_propertyName31' nonNullableProperty: - oneOf: - - type: string - - type: number + $ref: '#/components/schemas/ModelWithNullableObjectProperty_nonNullableProperty' propertyWithNullAndTwoTypes: - oneOf: - - type: "null" - - $ref: '#/components/schemas/PropertyType' - - $ref: '#/components/schemas/OtherPropertyType' + $ref: '#/components/schemas/ModelWithNullableObjectProperty_propertyWithNullAndTwoTypes' PropertyType: example: foo: foo @@ -56,4 +47,21 @@ components: properties: bar: type: string + ModelWithNullableObjectProperty_propertyName30: + nullable: true + oneOf: + - $ref: '#/components/schemas/PropertyType' + ModelWithNullableObjectProperty_propertyName31: + oneOf: + - type: "null" + - $ref: '#/components/schemas/PropertyType' + ModelWithNullableObjectProperty_nonNullableProperty: + oneOf: + - type: string + - type: number + ModelWithNullableObjectProperty_propertyWithNullAndTwoTypes: + oneOf: + - type: "null" + - $ref: '#/components/schemas/PropertyType' + - $ref: '#/components/schemas/OtherPropertyType' diff --git a/samples/client/petstore/java/nullable-object-property/build.gradle b/samples/client/petstore/java/nullable-object-property/build.gradle index 5aa7299de84e..c3af3bdb83dc 100644 --- a/samples/client/petstore/java/nullable-object-property/build.gradle +++ b/samples/client/petstore/java/nullable-object-property/build.gradle @@ -63,9 +63,9 @@ artifacts { ext { swagger_annotations_version = "1.5.22" - jackson_version = "2.10.4" + jackson_version = "2.13.0" jakarta_annotation_version = "1.3.5" - junit_version = "4.13.1" + junit_version = "4.13.2" } dependencies { diff --git a/samples/client/petstore/java/nullable-object-property/docs/DefaultApi.md b/samples/client/petstore/java/nullable-object-property/docs/DefaultApi.md index 7efb1b4fc4d3..7e2dda03d168 100644 --- a/samples/client/petstore/java/nullable-object-property/docs/DefaultApi.md +++ b/samples/client/petstore/java/nullable-object-property/docs/DefaultApi.md @@ -2,10 +2,10 @@ All URIs are relative to *http://localhost* -Method | HTTP request | Description -------------- | ------------- | ------------- -[**operation**](DefaultApi.md#operation) | **GET** / | -[**operationWithHttpInfo**](DefaultApi.md#operationWithHttpInfo) | **GET** / | +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**operation**](DefaultApi.md#operation) | **GET** / | | +| [**operationWithHttpInfo**](DefaultApi.md#operationWithHttpInfo) | **GET** / | | diff --git a/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectProperty.md b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectProperty.md index c90685b97d61..216830d67234 100644 --- a/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectProperty.md +++ b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectProperty.md @@ -5,13 +5,13 @@ ## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**propertyName** | [**PropertyType**](PropertyType.md) | | [optional] -**propertyName30** | [**PropertyType**](PropertyType.md) | | [optional] -**propertyName31** | [**PropertyType**](PropertyType.md) | | [optional] -**nonNullableProperty** | [**OneOfstringnumber**](OneOfstringnumber.md) | | [optional] -**propertyWithNullAndTwoTypes** | [**OneOfnullPropertyTypeOtherPropertyType**](OneOfnullPropertyTypeOtherPropertyType.md) | | [optional] +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**propertyName** | [**PropertyType**](PropertyType.md) | | [optional] | +|**propertyName30** | [**ModelWithNullableObjectPropertyPropertyName30**](ModelWithNullableObjectPropertyPropertyName30.md) | | [optional] | +|**propertyName31** | [**ModelWithNullableObjectPropertyPropertyName31**](ModelWithNullableObjectPropertyPropertyName31.md) | | [optional] | +|**nonNullableProperty** | [**ModelWithNullableObjectPropertyNonNullableProperty**](ModelWithNullableObjectPropertyNonNullableProperty.md) | | [optional] | +|**propertyWithNullAndTwoTypes** | [**ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes**](ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md) | | [optional] | diff --git a/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyNonNullableProperty.md b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyNonNullableProperty.md new file mode 100644 index 000000000000..ff959bf0530f --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyNonNullableProperty.md @@ -0,0 +1,37 @@ + + +# ModelWithNullableObjectPropertyNonNullableProperty + +## oneOf schemas +* [BigDecimal](BigDecimal.md) +* [String](String.md) + +## Example +```java +// Import classes: +import org.openapitools.client.model.ModelWithNullableObjectPropertyNonNullableProperty; +import org.openapitools.client.model.BigDecimal; +import org.openapitools.client.model.String; + +public class Example { + public static void main(String[] args) { + ModelWithNullableObjectPropertyNonNullableProperty exampleModelWithNullableObjectPropertyNonNullableProperty = new ModelWithNullableObjectPropertyNonNullableProperty(); + + // create a new BigDecimal + BigDecimal exampleBigDecimal = new BigDecimal(); + // set ModelWithNullableObjectPropertyNonNullableProperty to BigDecimal + exampleModelWithNullableObjectPropertyNonNullableProperty.setActualInstance(exampleBigDecimal); + // to get back the BigDecimal set earlier + BigDecimal testBigDecimal = (BigDecimal) exampleModelWithNullableObjectPropertyNonNullableProperty.getActualInstance(); + + // create a new String + String exampleString = new String(); + // set ModelWithNullableObjectPropertyNonNullableProperty to String + exampleModelWithNullableObjectPropertyNonNullableProperty.setActualInstance(exampleString); + // to get back the String set earlier + String testString = (String) exampleModelWithNullableObjectPropertyNonNullableProperty.getActualInstance(); + } +} +``` + + diff --git a/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyName30.md b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyName30.md new file mode 100644 index 000000000000..a2187c55b732 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyName30.md @@ -0,0 +1,30 @@ + + +# ModelWithNullableObjectPropertyPropertyName30 + +## oneOf schemas +* [PropertyType](PropertyType.md) + +NOTE: this class is nullable. + +## Example +```java +// Import classes: +import org.openapitools.client.model.ModelWithNullableObjectPropertyPropertyName30; +import org.openapitools.client.model.PropertyType; + +public class Example { + public static void main(String[] args) { + ModelWithNullableObjectPropertyPropertyName30 exampleModelWithNullableObjectPropertyPropertyName30 = new ModelWithNullableObjectPropertyPropertyName30(); + + // create a new PropertyType + PropertyType examplePropertyType = new PropertyType(); + // set ModelWithNullableObjectPropertyPropertyName30 to PropertyType + exampleModelWithNullableObjectPropertyPropertyName30.setActualInstance(examplePropertyType); + // to get back the PropertyType set earlier + PropertyType testPropertyType = (PropertyType) exampleModelWithNullableObjectPropertyPropertyName30.getActualInstance(); + } +} +``` + + diff --git a/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyName31.md b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyName31.md new file mode 100644 index 000000000000..efe1796d05bc --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyName31.md @@ -0,0 +1,30 @@ + + +# ModelWithNullableObjectPropertyPropertyName31 + +## oneOf schemas +* [PropertyType](PropertyType.md) + +NOTE: this class is nullable. + +## Example +```java +// Import classes: +import org.openapitools.client.model.ModelWithNullableObjectPropertyPropertyName31; +import org.openapitools.client.model.PropertyType; + +public class Example { + public static void main(String[] args) { + ModelWithNullableObjectPropertyPropertyName31 exampleModelWithNullableObjectPropertyPropertyName31 = new ModelWithNullableObjectPropertyPropertyName31(); + + // create a new PropertyType + PropertyType examplePropertyType = new PropertyType(); + // set ModelWithNullableObjectPropertyPropertyName31 to PropertyType + exampleModelWithNullableObjectPropertyPropertyName31.setActualInstance(examplePropertyType); + // to get back the PropertyType set earlier + PropertyType testPropertyType = (PropertyType) exampleModelWithNullableObjectPropertyPropertyName31.getActualInstance(); + } +} +``` + + diff --git a/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md new file mode 100644 index 000000000000..2a6c7ad70944 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md @@ -0,0 +1,39 @@ + + +# ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes + +## oneOf schemas +* [OtherPropertyType](OtherPropertyType.md) +* [PropertyType](PropertyType.md) + +NOTE: this class is nullable. + +## Example +```java +// Import classes: +import org.openapitools.client.model.ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes; +import org.openapitools.client.model.OtherPropertyType; +import org.openapitools.client.model.PropertyType; + +public class Example { + public static void main(String[] args) { + ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes exampleModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes = new ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes(); + + // create a new OtherPropertyType + OtherPropertyType exampleOtherPropertyType = new OtherPropertyType(); + // set ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes to OtherPropertyType + exampleModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.setActualInstance(exampleOtherPropertyType); + // to get back the OtherPropertyType set earlier + OtherPropertyType testOtherPropertyType = (OtherPropertyType) exampleModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.getActualInstance(); + + // create a new PropertyType + PropertyType examplePropertyType = new PropertyType(); + // set ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes to PropertyType + exampleModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.setActualInstance(examplePropertyType); + // to get back the PropertyType set earlier + PropertyType testPropertyType = (PropertyType) exampleModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.getActualInstance(); + } +} +``` + + diff --git a/samples/client/petstore/java/nullable-object-property/docs/OtherPropertyType.md b/samples/client/petstore/java/nullable-object-property/docs/OtherPropertyType.md index 592c0a86568e..f10876a3a792 100644 --- a/samples/client/petstore/java/nullable-object-property/docs/OtherPropertyType.md +++ b/samples/client/petstore/java/nullable-object-property/docs/OtherPropertyType.md @@ -5,9 +5,9 @@ ## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**bar** | **String** | | [optional] +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] | diff --git a/samples/client/petstore/java/nullable-object-property/docs/PropertyType.md b/samples/client/petstore/java/nullable-object-property/docs/PropertyType.md index 4990ed224799..55357b02ada1 100644 --- a/samples/client/petstore/java/nullable-object-property/docs/PropertyType.md +++ b/samples/client/petstore/java/nullable-object-property/docs/PropertyType.md @@ -5,9 +5,9 @@ ## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**foo** | **String** | | [optional] +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**foo** | **String** | | [optional] | diff --git a/samples/client/petstore/java/nullable-object-property/pom.xml b/samples/client/petstore/java/nullable-object-property/pom.xml index e0a6fa7c06eb..e60d182eb2df 100644 --- a/samples/client/petstore/java/nullable-object-property/pom.xml +++ b/samples/client/petstore/java/nullable-object-property/pom.xml @@ -105,7 +105,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.1.0 + 3.3.2 attach-javadocs @@ -214,9 +214,9 @@ 1.5.22 11 11 - 2.10.4 - 0.2.1 + 2.13.0 + 0.2.2 1.3.5 - 4.13.1 + 4.13.2 diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ApiClient.java index 0e2b6a7683c0..65cda6782190 100644 --- a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ApiClient.java @@ -23,6 +23,7 @@ import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; +import java.net.http.HttpConnectTimeoutException; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; @@ -63,6 +64,7 @@ public class ApiClient { private Consumer> responseInterceptor; private Consumer> asyncResponseInterceptor; private Duration readTimeout; + private Duration connectTimeout; private static String valueToString(Object value) { if (value == null) { @@ -81,7 +83,7 @@ private static String valueToString(Object value) { * @return URL-encoded representation of the input string. */ public static String urlEncode(String s) { - return URLEncoder.encode(s, UTF_8); + return URLEncoder.encode(s, UTF_8).replaceAll("\\+", "%20"); } /** @@ -159,7 +161,7 @@ public static List parameterToPairs( } /** - * Ctor. + * Create an instance of ApiClient. */ public ApiClient() { this.builder = createDefaultHttpClientBuilder(); @@ -167,12 +169,17 @@ public ApiClient() { updateBaseUri(getDefaultBaseUri()); interceptor = null; readTimeout = null; + connectTimeout = null; responseInterceptor = null; asyncResponseInterceptor = null; } /** - * Ctor. + * Create an instance of ApiClient. + * + * @param builder Http client builder. + * @param mapper Object mapper. + * @param baseUri Base URI */ public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri) { this.builder = builder; @@ -180,6 +187,7 @@ public ApiClient(HttpClient.Builder builder, ObjectMapper mapper, String baseUri updateBaseUri(baseUri != null ? baseUri : getDefaultBaseUri()); interceptor = null; readTimeout = null; + connectTimeout = null; responseInterceptor = null; asyncResponseInterceptor = null; } @@ -414,4 +422,35 @@ public ApiClient setReadTimeout(Duration readTimeout) { public Duration getReadTimeout() { return readTimeout; } + /** + * Sets the connect timeout (in milliseconds) for the http client. + * + *

In the case where a new connection needs to be established, if + * the connection cannot be established within the given {@code + * duration}, then {@link HttpClient#send(HttpRequest,BodyHandler) + * HttpClient::send} throws an {@link HttpConnectTimeoutException}, or + * {@link HttpClient#sendAsync(HttpRequest,BodyHandler) + * HttpClient::sendAsync} completes exceptionally with an + * {@code HttpConnectTimeoutException}. If a new connection does not + * need to be established, for example if a connection can be reused + * from a previous request, then this timeout duration has no effect. + * + * @param connectTimeout connection timeout in milliseconds + * + * @return This object. + */ + public ApiClient setConnectTimeout(Duration connectTimeout) { + this.connectTimeout = connectTimeout; + this.builder.connectTimeout(connectTimeout); + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public Duration getConnectTimeout() { + return connectTimeout; + } } diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/JSON.java index 04d3f7c17996..7a69ba9d61d5 100644 --- a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/JSON.java @@ -33,6 +33,7 @@ public JSON() { /** * Set the date format for JSON (de)serialization with Date properties. + * * @param dateFormat Date format */ public void setDateFormat(DateFormat dateFormat) { @@ -52,6 +53,8 @@ public void setDateFormat(DateFormat dateFormat) { * * @param node The input data. * @param modelClass The class that contains the discriminator mappings. + * + * @return the target model class. */ public static Class getClassForElement(JsonNode node, Class modelClass) { ClassDiscriminatorMapping cdm = modelDiscriminators.get(modelClass); @@ -111,6 +114,8 @@ String getDiscriminatorValue(JsonNode node) { * * @param node The input data. * @param visitedClasses The set of classes that have already been visited. + * + * @return the target model class. */ Class getClassForElement(JsonNode node, Set> visitedClasses) { if (visitedClasses.contains(modelClass)) { @@ -157,6 +162,9 @@ Class getClassForElement(JsonNode node, Set> visitedClasses) { * * @param modelClass A OpenAPI model class. * @param inst The instance object. + * @param visitedClasses The set of classes that have already been visited. + * + * @return true if inst is an instance of modelClass in the OpenAPI model hierarchy. */ public static boolean isInstanceOf(Class modelClass, Object inst, Set> visitedClasses) { if (modelClass.isInstance(inst)) { diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/Pair.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/Pair.java index 4d87262bb42f..2e29f6f31933 100644 --- a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/Pair.java +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/Pair.java @@ -52,10 +52,6 @@ private boolean isValidString(String arg) { return false; } - if (arg.trim().isEmpty()) { - return false; - } - return true; } } diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 3d729102e8d0..a1170edf7b43 100644 --- a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -18,6 +18,7 @@ import java.text.FieldPosition; import java.text.ParsePosition; import java.util.Date; +import java.text.DecimalFormat; import java.util.GregorianCalendar; import java.util.TimeZone; @@ -31,6 +32,7 @@ public class RFC3339DateFormat extends DateFormat { public RFC3339DateFormat() { this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); } @Override @@ -50,6 +52,6 @@ public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fie @Override public Object clone() { - return this; + return super.clone(); } } \ No newline at end of file diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ServerConfiguration.java index e08da9aac7dd..ca5c1187edf2 100644 --- a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ServerConfiguration.java +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -39,7 +39,7 @@ public String URL(Map variables) { if (variables != null && variables.containsKey(name)) { value = variables.get(name); if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { - throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); } } url = url.replaceAll("\\{" + name + "\\}", value); diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/api/DefaultApi.java index 0ef45d344c9b..685e46672008 100644 --- a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/api/DefaultApi.java +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -29,13 +29,13 @@ import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; -import java.util.function.Consumer; import java.util.ArrayList; import java.util.StringJoiner; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Consumer; @javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class DefaultApi { diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectProperty.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectProperty.java index e424ee66e50e..d8a2ea22eb80 100644 --- a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectProperty.java +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectProperty.java @@ -24,8 +24,10 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.openapitools.client.model.OneOfnullPropertyTypeOtherPropertyType; -import org.openapitools.client.model.OneOfstringnumber; +import org.openapitools.client.model.ModelWithNullableObjectPropertyNonNullableProperty; +import org.openapitools.client.model.ModelWithNullableObjectPropertyPropertyName30; +import org.openapitools.client.model.ModelWithNullableObjectPropertyPropertyName31; +import org.openapitools.client.model.ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes; import org.openapitools.client.model.PropertyType; import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -50,16 +52,16 @@ public class ModelWithNullableObjectProperty { private PropertyType propertyName; public static final String JSON_PROPERTY_PROPERTY_NAME30 = "propertyName30"; - private JsonNullable propertyName30 = JsonNullable.undefined(); + private JsonNullable propertyName30 = JsonNullable.undefined(); public static final String JSON_PROPERTY_PROPERTY_NAME31 = "propertyName31"; - private JsonNullable propertyName31 = JsonNullable.undefined(); + private ModelWithNullableObjectPropertyPropertyName31 propertyName31; public static final String JSON_PROPERTY_NON_NULLABLE_PROPERTY = "nonNullableProperty"; - private JsonNullable nonNullableProperty = JsonNullable.undefined(); + private ModelWithNullableObjectPropertyNonNullableProperty nonNullableProperty; public static final String JSON_PROPERTY_PROPERTY_WITH_NULL_AND_TWO_TYPES = "propertyWithNullAndTwoTypes"; - private JsonNullable propertyWithNullAndTwoTypes = JsonNullable.undefined(); + private ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes propertyWithNullAndTwoTypes; public ModelWithNullableObjectProperty() { } @@ -90,8 +92,8 @@ public void setPropertyName(PropertyType propertyName) { } - public ModelWithNullableObjectProperty propertyName30(PropertyType propertyName30) { - this.propertyName30 = JsonNullable.of(propertyName30); + public ModelWithNullableObjectProperty propertyName30(ModelWithNullableObjectPropertyPropertyName30 propertyName30) { + this.propertyName30 = JsonNullable.of(propertyName30); return this; } @@ -103,29 +105,29 @@ public ModelWithNullableObjectProperty propertyName30(PropertyType propertyName3 @ApiModelProperty(value = "") @JsonIgnore - public PropertyType getPropertyName30() { + public ModelWithNullableObjectPropertyPropertyName30 getPropertyName30() { return propertyName30.orElse(null); } @JsonProperty(JSON_PROPERTY_PROPERTY_NAME30) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public JsonNullable getPropertyName30_JsonNullable() { + public JsonNullable getPropertyName30_JsonNullable() { return propertyName30; } @JsonProperty(JSON_PROPERTY_PROPERTY_NAME30) - public void setPropertyName30_JsonNullable(JsonNullable propertyName30) { + public void setPropertyName30_JsonNullable(JsonNullable propertyName30) { this.propertyName30 = propertyName30; } - public void setPropertyName30(PropertyType propertyName30) { - this.propertyName30 = JsonNullable.of(propertyName30); + public void setPropertyName30(ModelWithNullableObjectPropertyPropertyName30 propertyName30) { + this.propertyName30 = JsonNullable.of(propertyName30); } - public ModelWithNullableObjectProperty propertyName31(PropertyType propertyName31) { - this.propertyName31 = JsonNullable.of(propertyName31); + public ModelWithNullableObjectProperty propertyName31(ModelWithNullableObjectPropertyPropertyName31 propertyName31) { + this.propertyName31 = propertyName31; return this; } @@ -135,31 +137,23 @@ public ModelWithNullableObjectProperty propertyName31(PropertyType propertyName3 **/ @javax.annotation.Nullable @ApiModelProperty(value = "") - @JsonIgnore - - public PropertyType getPropertyName31() { - return propertyName31.orElse(null); - } - @JsonProperty(JSON_PROPERTY_PROPERTY_NAME31) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public JsonNullable getPropertyName31_JsonNullable() { + public ModelWithNullableObjectPropertyPropertyName31 getPropertyName31() { return propertyName31; } - + + @JsonProperty(JSON_PROPERTY_PROPERTY_NAME31) - public void setPropertyName31_JsonNullable(JsonNullable propertyName31) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setPropertyName31(ModelWithNullableObjectPropertyPropertyName31 propertyName31) { this.propertyName31 = propertyName31; } - public void setPropertyName31(PropertyType propertyName31) { - this.propertyName31 = JsonNullable.of(propertyName31); - } - - public ModelWithNullableObjectProperty nonNullableProperty(OneOfstringnumber nonNullableProperty) { - this.nonNullableProperty = JsonNullable.of(nonNullableProperty); + public ModelWithNullableObjectProperty nonNullableProperty(ModelWithNullableObjectPropertyNonNullableProperty nonNullableProperty) { + this.nonNullableProperty = nonNullableProperty; return this; } @@ -169,31 +163,23 @@ public ModelWithNullableObjectProperty nonNullableProperty(OneOfstringnumber non **/ @javax.annotation.Nullable @ApiModelProperty(value = "") - @JsonIgnore - - public OneOfstringnumber getNonNullableProperty() { - return nonNullableProperty.orElse(null); - } - @JsonProperty(JSON_PROPERTY_NON_NULLABLE_PROPERTY) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public JsonNullable getNonNullableProperty_JsonNullable() { + public ModelWithNullableObjectPropertyNonNullableProperty getNonNullableProperty() { return nonNullableProperty; } - + + @JsonProperty(JSON_PROPERTY_NON_NULLABLE_PROPERTY) - public void setNonNullableProperty_JsonNullable(JsonNullable nonNullableProperty) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNonNullableProperty(ModelWithNullableObjectPropertyNonNullableProperty nonNullableProperty) { this.nonNullableProperty = nonNullableProperty; } - public void setNonNullableProperty(OneOfstringnumber nonNullableProperty) { - this.nonNullableProperty = JsonNullable.of(nonNullableProperty); - } - - public ModelWithNullableObjectProperty propertyWithNullAndTwoTypes(OneOfnullPropertyTypeOtherPropertyType propertyWithNullAndTwoTypes) { - this.propertyWithNullAndTwoTypes = JsonNullable.of(propertyWithNullAndTwoTypes); + public ModelWithNullableObjectProperty propertyWithNullAndTwoTypes(ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes propertyWithNullAndTwoTypes) { + this.propertyWithNullAndTwoTypes = propertyWithNullAndTwoTypes; return this; } @@ -203,28 +189,20 @@ public ModelWithNullableObjectProperty propertyWithNullAndTwoTypes(OneOfnullProp **/ @javax.annotation.Nullable @ApiModelProperty(value = "") - @JsonIgnore - - public OneOfnullPropertyTypeOtherPropertyType getPropertyWithNullAndTwoTypes() { - return propertyWithNullAndTwoTypes.orElse(null); - } - @JsonProperty(JSON_PROPERTY_PROPERTY_WITH_NULL_AND_TWO_TYPES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public JsonNullable getPropertyWithNullAndTwoTypes_JsonNullable() { + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes getPropertyWithNullAndTwoTypes() { return propertyWithNullAndTwoTypes; } - + + @JsonProperty(JSON_PROPERTY_PROPERTY_WITH_NULL_AND_TWO_TYPES) - public void setPropertyWithNullAndTwoTypes_JsonNullable(JsonNullable propertyWithNullAndTwoTypes) { + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setPropertyWithNullAndTwoTypes(ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes propertyWithNullAndTwoTypes) { this.propertyWithNullAndTwoTypes = propertyWithNullAndTwoTypes; } - public void setPropertyWithNullAndTwoTypes(OneOfnullPropertyTypeOtherPropertyType propertyWithNullAndTwoTypes) { - this.propertyWithNullAndTwoTypes = JsonNullable.of(propertyWithNullAndTwoTypes); - } - /** * Return true if this ModelWithNullableObjectProperty object is equal to o. @@ -240,9 +218,9 @@ public boolean equals(Object o) { ModelWithNullableObjectProperty modelWithNullableObjectProperty = (ModelWithNullableObjectProperty) o; return Objects.equals(this.propertyName, modelWithNullableObjectProperty.propertyName) && equalsNullable(this.propertyName30, modelWithNullableObjectProperty.propertyName30) && - equalsNullable(this.propertyName31, modelWithNullableObjectProperty.propertyName31) && - equalsNullable(this.nonNullableProperty, modelWithNullableObjectProperty.nonNullableProperty) && - equalsNullable(this.propertyWithNullAndTwoTypes, modelWithNullableObjectProperty.propertyWithNullAndTwoTypes); + Objects.equals(this.propertyName31, modelWithNullableObjectProperty.propertyName31) && + Objects.equals(this.nonNullableProperty, modelWithNullableObjectProperty.nonNullableProperty) && + Objects.equals(this.propertyWithNullAndTwoTypes, modelWithNullableObjectProperty.propertyWithNullAndTwoTypes); } private static boolean equalsNullable(JsonNullable a, JsonNullable b) { @@ -251,7 +229,7 @@ private static boolean equalsNullable(JsonNullable a, JsonNullable b) @Override public int hashCode() { - return Objects.hash(propertyName, hashCodeNullable(propertyName30), hashCodeNullable(propertyName31), hashCodeNullable(nonNullableProperty), hashCodeNullable(propertyWithNullAndTwoTypes)); + return Objects.hash(propertyName, hashCodeNullable(propertyName30), propertyName31, nonNullableProperty, propertyWithNullAndTwoTypes); } private static int hashCodeNullable(JsonNullable a) { diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyNonNullableProperty.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyNonNullableProperty.java new file mode 100644 index 000000000000..86f8758a9c02 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyNonNullableProperty.java @@ -0,0 +1,237 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.openapitools.client.JSON; + +@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +@JsonDeserialize(using = ModelWithNullableObjectPropertyNonNullableProperty.ModelWithNullableObjectPropertyNonNullablePropertyDeserializer.class) +@JsonSerialize(using = ModelWithNullableObjectPropertyNonNullableProperty.ModelWithNullableObjectPropertyNonNullablePropertySerializer.class) +public class ModelWithNullableObjectPropertyNonNullableProperty extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ModelWithNullableObjectPropertyNonNullableProperty.class.getName()); + + public static class ModelWithNullableObjectPropertyNonNullablePropertySerializer extends StdSerializer { + public ModelWithNullableObjectPropertyNonNullablePropertySerializer(Class t) { + super(t); + } + + public ModelWithNullableObjectPropertyNonNullablePropertySerializer() { + this(null); + } + + @Override + public void serialize(ModelWithNullableObjectPropertyNonNullableProperty value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class ModelWithNullableObjectPropertyNonNullablePropertyDeserializer extends StdDeserializer { + public ModelWithNullableObjectPropertyNonNullablePropertyDeserializer() { + this(ModelWithNullableObjectPropertyNonNullableProperty.class); + } + + public ModelWithNullableObjectPropertyNonNullablePropertyDeserializer(Class vc) { + super(vc); + } + + @Override + public ModelWithNullableObjectPropertyNonNullableProperty deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize BigDecimal + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (BigDecimal.class.equals(Integer.class) || BigDecimal.class.equals(Long.class) || BigDecimal.class.equals(Float.class) || BigDecimal.class.equals(Double.class) || BigDecimal.class.equals(Boolean.class) || BigDecimal.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((BigDecimal.class.equals(Integer.class) || BigDecimal.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((BigDecimal.class.equals(Float.class) || BigDecimal.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (BigDecimal.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (BigDecimal.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(BigDecimal.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'BigDecimal'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'BigDecimal'", e); + } + + // deserialize String + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (String.class.equals(Integer.class) || String.class.equals(Long.class) || String.class.equals(Float.class) || String.class.equals(Double.class) || String.class.equals(Boolean.class) || String.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((String.class.equals(Integer.class) || String.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((String.class.equals(Float.class) || String.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (String.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (String.class.equals(String.class) && token == JsonToken.VALUE_STRING); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(String.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + if (match == 1) { + ModelWithNullableObjectPropertyNonNullableProperty ret = new ModelWithNullableObjectPropertyNonNullableProperty(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for ModelWithNullableObjectPropertyNonNullableProperty: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public ModelWithNullableObjectPropertyNonNullableProperty getNullValue(DeserializationContext ctxt) throws JsonMappingException { + throw new JsonMappingException(ctxt.getParser(), "ModelWithNullableObjectPropertyNonNullableProperty cannot be null"); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public ModelWithNullableObjectPropertyNonNullableProperty() { + super("oneOf", Boolean.FALSE); + } + + public ModelWithNullableObjectPropertyNonNullableProperty(BigDecimal o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public ModelWithNullableObjectPropertyNonNullableProperty(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("BigDecimal", BigDecimal.class); + schemas.put("String", String.class); + JSON.registerDescendants(ModelWithNullableObjectPropertyNonNullableProperty.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return ModelWithNullableObjectPropertyNonNullableProperty.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * BigDecimal, String + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(BigDecimal.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(String.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be BigDecimal, String"); + } + + /** + * Get the actual instance, which can be the following: + * BigDecimal, String + * + * @return The actual instance (BigDecimal, String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `BigDecimal`. If the actual instance is not `BigDecimal`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `BigDecimal` + * @throws ClassCastException if the instance is not `BigDecimal` + */ + public BigDecimal getBigDecimal() throws ClassCastException { + return (BigDecimal)super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName30.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName30.java new file mode 100644 index 000000000000..f401e268bb47 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName30.java @@ -0,0 +1,203 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.PropertyType; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.openapitools.client.JSON; + +@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +@JsonDeserialize(using = ModelWithNullableObjectPropertyPropertyName30.ModelWithNullableObjectPropertyPropertyName30Deserializer.class) +@JsonSerialize(using = ModelWithNullableObjectPropertyPropertyName30.ModelWithNullableObjectPropertyPropertyName30Serializer.class) +public class ModelWithNullableObjectPropertyPropertyName30 extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ModelWithNullableObjectPropertyPropertyName30.class.getName()); + + public static class ModelWithNullableObjectPropertyPropertyName30Serializer extends StdSerializer { + public ModelWithNullableObjectPropertyPropertyName30Serializer(Class t) { + super(t); + } + + public ModelWithNullableObjectPropertyPropertyName30Serializer() { + this(null); + } + + @Override + public void serialize(ModelWithNullableObjectPropertyPropertyName30 value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class ModelWithNullableObjectPropertyPropertyName30Deserializer extends StdDeserializer { + public ModelWithNullableObjectPropertyPropertyName30Deserializer() { + this(ModelWithNullableObjectPropertyPropertyName30.class); + } + + public ModelWithNullableObjectPropertyPropertyName30Deserializer(Class vc) { + super(vc); + } + + @Override + public ModelWithNullableObjectPropertyPropertyName30 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize PropertyType + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (PropertyType.class.equals(Integer.class) || PropertyType.class.equals(Long.class) || PropertyType.class.equals(Float.class) || PropertyType.class.equals(Double.class) || PropertyType.class.equals(Boolean.class) || PropertyType.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((PropertyType.class.equals(Integer.class) || PropertyType.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((PropertyType.class.equals(Float.class) || PropertyType.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (PropertyType.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (PropertyType.class.equals(String.class) && token == JsonToken.VALUE_STRING); + attemptParsing |= (token == JsonToken.VALUE_NULL); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(PropertyType.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'PropertyType'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'PropertyType'", e); + } + + if (match == 1) { + ModelWithNullableObjectPropertyPropertyName30 ret = new ModelWithNullableObjectPropertyPropertyName30(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for ModelWithNullableObjectPropertyPropertyName30: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public ModelWithNullableObjectPropertyPropertyName30 getNullValue(DeserializationContext ctxt) throws JsonMappingException { + return null; + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public ModelWithNullableObjectPropertyPropertyName30() { + super("oneOf", Boolean.TRUE); + } + + public ModelWithNullableObjectPropertyPropertyName30(PropertyType o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + static { + schemas.put("PropertyType", PropertyType.class); + JSON.registerDescendants(ModelWithNullableObjectPropertyPropertyName30.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return ModelWithNullableObjectPropertyPropertyName30.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * PropertyType + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(PropertyType.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be PropertyType"); + } + + /** + * Get the actual instance, which can be the following: + * PropertyType + * + * @return The actual instance (PropertyType) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `PropertyType`. If the actual instance is not `PropertyType`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `PropertyType` + * @throws ClassCastException if the instance is not `PropertyType` + */ + public PropertyType getPropertyType() throws ClassCastException { + return (PropertyType)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName31.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName31.java new file mode 100644 index 000000000000..2128f69a7b73 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName31.java @@ -0,0 +1,203 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.PropertyType; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.openapitools.client.JSON; + +@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +@JsonDeserialize(using = ModelWithNullableObjectPropertyPropertyName31.ModelWithNullableObjectPropertyPropertyName31Deserializer.class) +@JsonSerialize(using = ModelWithNullableObjectPropertyPropertyName31.ModelWithNullableObjectPropertyPropertyName31Serializer.class) +public class ModelWithNullableObjectPropertyPropertyName31 extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ModelWithNullableObjectPropertyPropertyName31.class.getName()); + + public static class ModelWithNullableObjectPropertyPropertyName31Serializer extends StdSerializer { + public ModelWithNullableObjectPropertyPropertyName31Serializer(Class t) { + super(t); + } + + public ModelWithNullableObjectPropertyPropertyName31Serializer() { + this(null); + } + + @Override + public void serialize(ModelWithNullableObjectPropertyPropertyName31 value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class ModelWithNullableObjectPropertyPropertyName31Deserializer extends StdDeserializer { + public ModelWithNullableObjectPropertyPropertyName31Deserializer() { + this(ModelWithNullableObjectPropertyPropertyName31.class); + } + + public ModelWithNullableObjectPropertyPropertyName31Deserializer(Class vc) { + super(vc); + } + + @Override + public ModelWithNullableObjectPropertyPropertyName31 deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize PropertyType + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (PropertyType.class.equals(Integer.class) || PropertyType.class.equals(Long.class) || PropertyType.class.equals(Float.class) || PropertyType.class.equals(Double.class) || PropertyType.class.equals(Boolean.class) || PropertyType.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((PropertyType.class.equals(Integer.class) || PropertyType.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((PropertyType.class.equals(Float.class) || PropertyType.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (PropertyType.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (PropertyType.class.equals(String.class) && token == JsonToken.VALUE_STRING); + attemptParsing |= (token == JsonToken.VALUE_NULL); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(PropertyType.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'PropertyType'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'PropertyType'", e); + } + + if (match == 1) { + ModelWithNullableObjectPropertyPropertyName31 ret = new ModelWithNullableObjectPropertyPropertyName31(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for ModelWithNullableObjectPropertyPropertyName31: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public ModelWithNullableObjectPropertyPropertyName31 getNullValue(DeserializationContext ctxt) throws JsonMappingException { + return null; + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public ModelWithNullableObjectPropertyPropertyName31() { + super("oneOf", Boolean.TRUE); + } + + public ModelWithNullableObjectPropertyPropertyName31(PropertyType o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + static { + schemas.put("PropertyType", PropertyType.class); + JSON.registerDescendants(ModelWithNullableObjectPropertyPropertyName31.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return ModelWithNullableObjectPropertyPropertyName31.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * PropertyType + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(PropertyType.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be PropertyType"); + } + + /** + * Get the actual instance, which can be the following: + * PropertyType + * + * @return The actual instance (PropertyType) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `PropertyType`. If the actual instance is not `PropertyType`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `PropertyType` + * @throws ClassCastException if the instance is not `PropertyType` + */ + public PropertyType getPropertyType() throws ClassCastException { + return (PropertyType)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.java b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.java new file mode 100644 index 000000000000..6366fe07c273 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/main/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.java @@ -0,0 +1,253 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import java.util.Map; +import java.util.HashMap; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.OtherPropertyType; +import org.openapitools.client.model.PropertyType; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import com.fasterxml.jackson.core.type.TypeReference; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import org.openapitools.client.JSON; + +@javax.annotation.processing.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +@JsonDeserialize(using = ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesDeserializer.class) +@JsonSerialize(using = ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesSerializer.class) +public class ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.class.getName()); + + public static class ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesSerializer extends StdSerializer { + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesSerializer(Class t) { + super(t); + } + + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesSerializer() { + this(null); + } + + @Override + public void serialize(ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { + jgen.writeObject(value.getActualInstance()); + } + } + + public static class ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesDeserializer extends StdDeserializer { + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesDeserializer() { + this(ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.class); + } + + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesDeserializer(Class vc) { + super(vc); + } + + @Override + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { + JsonNode tree = jp.readValueAsTree(); + Object deserialized = null; + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + int match = 0; + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + // deserialize OtherPropertyType + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (OtherPropertyType.class.equals(Integer.class) || OtherPropertyType.class.equals(Long.class) || OtherPropertyType.class.equals(Float.class) || OtherPropertyType.class.equals(Double.class) || OtherPropertyType.class.equals(Boolean.class) || OtherPropertyType.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((OtherPropertyType.class.equals(Integer.class) || OtherPropertyType.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((OtherPropertyType.class.equals(Float.class) || OtherPropertyType.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (OtherPropertyType.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (OtherPropertyType.class.equals(String.class) && token == JsonToken.VALUE_STRING); + attemptParsing |= (token == JsonToken.VALUE_NULL); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(OtherPropertyType.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'OtherPropertyType'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'OtherPropertyType'", e); + } + + // deserialize PropertyType + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if (PropertyType.class.equals(Integer.class) || PropertyType.class.equals(Long.class) || PropertyType.class.equals(Float.class) || PropertyType.class.equals(Double.class) || PropertyType.class.equals(Boolean.class) || PropertyType.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= ((PropertyType.class.equals(Integer.class) || PropertyType.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= ((PropertyType.class.equals(Float.class) || PropertyType.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= (PropertyType.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= (PropertyType.class.equals(String.class) && token == JsonToken.VALUE_STRING); + attemptParsing |= (token == JsonToken.VALUE_NULL); + } + } + if (attemptParsing) { + deserialized = tree.traverse(jp.getCodec()).readValueAs(PropertyType.class); + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema 'PropertyType'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'PropertyType'", e); + } + + if (match == 1) { + ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes ret = new ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes(); + ret.setActualInstance(deserialized); + return ret; + } + throw new IOException(String.format("Failed deserialization for ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes: %d classes match result, expected 1", match)); + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes getNullValue(DeserializationContext ctxt) throws JsonMappingException { + return null; + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes() { + super("oneOf", Boolean.TRUE); + } + + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes(OtherPropertyType o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + public ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes(PropertyType o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + static { + schemas.put("OtherPropertyType", OtherPropertyType.class); + schemas.put("PropertyType", PropertyType.class); + JSON.registerDescendants(ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.class, Collections.unmodifiableMap(schemas)); + } + + @Override + public Map> getSchemas() { + return ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * OtherPropertyType, PropertyType + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(OtherPropertyType.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(PropertyType.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be OtherPropertyType, PropertyType"); + } + + /** + * Get the actual instance, which can be the following: + * OtherPropertyType, PropertyType + * + * @return The actual instance (OtherPropertyType, PropertyType) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `OtherPropertyType`. If the actual instance is not `OtherPropertyType`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `OtherPropertyType` + * @throws ClassCastException if the instance is not `OtherPropertyType` + */ + public OtherPropertyType getOtherPropertyType() throws ClassCastException { + return (OtherPropertyType)super.getActualInstance(); + } + + /** + * Get the actual instance of `PropertyType`. If the actual instance is not `PropertyType`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `PropertyType` + * @throws ClassCastException if the instance is not `PropertyType` + */ + public PropertyType getPropertyType() throws ClassCastException { + return (PropertyType)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyNonNullablePropertyTest.java b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyNonNullablePropertyTest.java new file mode 100644 index 000000000000..42b0b34326bd --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyNonNullablePropertyTest.java @@ -0,0 +1,35 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ModelWithNullableObjectPropertyNonNullableProperty + */ +public class ModelWithNullableObjectPropertyNonNullablePropertyTest { + private final ModelWithNullableObjectPropertyNonNullableProperty model = new ModelWithNullableObjectPropertyNonNullableProperty(); + + /** + * Model tests for ModelWithNullableObjectPropertyNonNullableProperty + */ + @Test + public void testModelWithNullableObjectPropertyNonNullableProperty() { + // TODO: test ModelWithNullableObjectPropertyNonNullableProperty + } + +} diff --git a/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName30Test.java b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName30Test.java new file mode 100644 index 000000000000..2929d394c255 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName30Test.java @@ -0,0 +1,51 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.PropertyType; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ModelWithNullableObjectPropertyPropertyName30 + */ +public class ModelWithNullableObjectPropertyPropertyName30Test { + private final ModelWithNullableObjectPropertyPropertyName30 model = new ModelWithNullableObjectPropertyPropertyName30(); + + /** + * Model tests for ModelWithNullableObjectPropertyPropertyName30 + */ + @Test + public void testModelWithNullableObjectPropertyPropertyName30() { + // TODO: test ModelWithNullableObjectPropertyPropertyName30 + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName31Test.java b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName31Test.java new file mode 100644 index 000000000000..29973b5e9634 --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyName31Test.java @@ -0,0 +1,51 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.PropertyType; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ModelWithNullableObjectPropertyPropertyName31 + */ +public class ModelWithNullableObjectPropertyPropertyName31Test { + private final ModelWithNullableObjectPropertyPropertyName31 model = new ModelWithNullableObjectPropertyPropertyName31(); + + /** + * Model tests for ModelWithNullableObjectPropertyPropertyName31 + */ + @Test + public void testModelWithNullableObjectPropertyPropertyName31() { + // TODO: test ModelWithNullableObjectPropertyPropertyName31 + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesTest.java b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesTest.java new file mode 100644 index 000000000000..a55d2a184bfd --- /dev/null +++ b/samples/client/petstore/java/nullable-object-property/src/test/java/org/openapitools/client/model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesTest.java @@ -0,0 +1,60 @@ +/* + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.openapitools.client.model.OtherPropertyType; +import org.openapitools.client.model.PropertyType; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes + */ +public class ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesTest { + private final ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes model = new ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes(); + + /** + * Model tests for ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes + */ + @Test + public void testModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes() { + // TODO: test ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + +} diff --git a/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/FILES b/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/FILES index 1b848bb49952..e40d749fa91e 100644 --- a/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/FILES @@ -2,6 +2,10 @@ README.md build.gradle docs/DefaultApi.md docs/ModelWithNullableObjectProperty.md +docs/ModelWithNullableObjectPropertyNonNullableProperty.md +docs/ModelWithNullableObjectPropertyPropertyName30.md +docs/ModelWithNullableObjectPropertyPropertyName31.md +docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md docs/OtherPropertyType.md docs/PropertyType.md gradle/wrapper/gradle-wrapper.jar @@ -12,7 +16,7 @@ settings.gradle src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt -src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt +src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt @@ -20,6 +24,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -27,5 +32,9 @@ src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectProperty.kt +src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyNonNullableProperty.kt +src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName30.kt +src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName31.kt +src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.kt src/main/kotlin/org/openapitools/client/models/OtherPropertyType.kt src/main/kotlin/org/openapitools/client/models/PropertyType.kt diff --git a/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/VERSION b/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/VERSION index 4077803655c0..89648de3311c 100644 --- a/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-nullable-object-propery/.openapi-generator/VERSION @@ -1 +1 @@ -5.3.1-SNAPSHOT \ No newline at end of file +6.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable-object-propery/README.md b/samples/client/petstore/kotlin-nullable-object-propery/README.md index 986adb619857..91235a072074 100644 --- a/samples/client/petstore/kotlin-nullable-object-propery/README.md +++ b/samples/client/petstore/kotlin-nullable-object-propery/README.md @@ -42,6 +42,10 @@ Class | Method | HTTP request | Description ## Documentation for Models - [org.openapitools.client.models.ModelWithNullableObjectProperty](docs/ModelWithNullableObjectProperty.md) + - [org.openapitools.client.models.ModelWithNullableObjectPropertyNonNullableProperty](docs/ModelWithNullableObjectPropertyNonNullableProperty.md) + - [org.openapitools.client.models.ModelWithNullableObjectPropertyPropertyName30](docs/ModelWithNullableObjectPropertyPropertyName30.md) + - [org.openapitools.client.models.ModelWithNullableObjectPropertyPropertyName31](docs/ModelWithNullableObjectPropertyPropertyName31.md) + - [org.openapitools.client.models.ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes](docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md) - [org.openapitools.client.models.OtherPropertyType](docs/OtherPropertyType.md) - [org.openapitools.client.models.PropertyType](docs/PropertyType.md) diff --git a/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectProperty.md b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectProperty.md index 4a769947077a..68cdd26d8a3a 100644 --- a/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectProperty.md +++ b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectProperty.md @@ -5,10 +5,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **propertyName** | [**PropertyType**](PropertyType.md) | | [optional] -**propertyName30** | [**PropertyType**](PropertyType.md) | | [optional] -**propertyName31** | [**PropertyType**](PropertyType.md) | | [optional] -**nonNullableProperty** | [**OneOfLessThanStringCommaNumberGreaterThan**](OneOfLessThanStringCommaNumberGreaterThan.md) | | [optional] -**propertyWithNullAndTwoTypes** | [**OneOfLessThanNullCommaPropertyTypeCommaOtherPropertyTypeGreaterThan**](OneOfLessThanNullCommaPropertyTypeCommaOtherPropertyTypeGreaterThan.md) | | [optional] +**propertyName30** | [**ModelWithNullableObjectPropertyPropertyName30**](ModelWithNullableObjectPropertyPropertyName30.md) | | [optional] +**propertyName31** | [**ModelWithNullableObjectPropertyPropertyName31**](ModelWithNullableObjectPropertyPropertyName31.md) | | [optional] +**nonNullableProperty** | [**ModelWithNullableObjectPropertyNonNullableProperty**](ModelWithNullableObjectPropertyNonNullableProperty.md) | | [optional] +**propertyWithNullAndTwoTypes** | [**ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes**](ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md) | | [optional] diff --git a/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyNonNullableProperty.md b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyNonNullableProperty.md new file mode 100644 index 000000000000..aeed01ed68e4 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyNonNullableProperty.md @@ -0,0 +1,9 @@ + +# ModelWithNullableObjectPropertyNonNullableProperty + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyName30.md b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyName30.md new file mode 100644 index 000000000000..161efa261d10 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyName30.md @@ -0,0 +1,10 @@ + +# ModelWithNullableObjectPropertyPropertyName30 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyName31.md b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyName31.md new file mode 100644 index 000000000000..5ad87c455cde --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyName31.md @@ -0,0 +1,10 @@ + +# ModelWithNullableObjectPropertyPropertyName31 + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md new file mode 100644 index 000000000000..a4bbfe2c6986 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/docs/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md @@ -0,0 +1,11 @@ + +# ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **kotlin.String** | | [optional] +**bar** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt index a068250cb397..fedc8575066c 100644 --- a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt @@ -20,22 +20,28 @@ package org.openapitools.client.apis +import java.io.IOException +import okhttp3.OkHttpClient + import org.openapitools.client.models.ModelWithNullableObjectProperty +import com.squareup.moshi.Json + import org.openapitools.client.infrastructure.ApiClient -import org.openapitools.client.infrastructure.ApiInfrastructureResponse +import org.openapitools.client.infrastructure.ApiResponse import org.openapitools.client.infrastructure.ClientException import org.openapitools.client.infrastructure.ClientError import org.openapitools.client.infrastructure.ServerException import org.openapitools.client.infrastructure.ServerError import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.PartConfig import org.openapitools.client.infrastructure.RequestConfig import org.openapitools.client.infrastructure.RequestMethod import org.openapitools.client.infrastructure.ResponseType import org.openapitools.client.infrastructure.Success import org.openapitools.client.infrastructure.toMultiValue -class DefaultApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) { +class DefaultApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { companion object { @JvmStatic val defaultBasePath: String by lazy { @@ -44,15 +50,17 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath } /** - * - * - * @return ModelWithNullableObjectProperty or null - * @throws UnsupportedOperationException If the API returns an informational or redirection response - * @throws ClientException If the API returns a client error response - * @throws ServerException If the API returns a server error response - */ + * + * + * @return ModelWithNullableObjectProperty or null + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ @Suppress("UNCHECKED_CAST") - @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) fun operation() : ModelWithNullableObjectProperty? { val localVarResponse = operationWithHttpInfo() @@ -72,16 +80,15 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath } /** - * - * - * @return ApiInfrastructureResponse - * @throws UnsupportedOperationException If the API returns an informational or redirection response - * @throws ClientException If the API returns a client error response - * @throws ServerException If the API returns a server error response - */ + * + * + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ @Suppress("UNCHECKED_CAST") - @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class) - fun operationWithHttpInfo() : ApiInfrastructureResponse { + @Throws(IllegalStateException::class, IOException::class) + fun operationWithHttpInfo() : ApiResponse { val localVariableConfig = operationRequestConfig() return request( @@ -90,14 +97,15 @@ class DefaultApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath } /** - * To obtain the request config of the operation operation - * - * @return RequestConfig - */ + * To obtain the request config of the operation operation + * + * @return RequestConfig + */ fun operationRequestConfig() : RequestConfig { val localVariableBody = null val localVariableQuery: MultiValueMap = mutableMapOf() val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" return RequestConfig( method = RequestMethod.GET, diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 634abe57b900..bfd00ac6a2ef 100644 --- a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -10,6 +10,7 @@ import okhttp3.ResponseBody import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.Request import okhttp3.Headers +import okhttp3.Headers.Companion.toHeaders import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback @@ -25,11 +26,10 @@ import java.time.LocalDateTime import java.time.LocalTime import java.time.OffsetDateTime import java.time.OffsetTime -import java.util.Date import java.util.Locale import com.squareup.moshi.adapter -open class ApiClient(val baseUrl: String) { +open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" protected const val Accept = "Accept" @@ -47,7 +47,7 @@ open class ApiClient(val baseUrl: String) { const val baseUrlKey = "org.openapitools.client.baseUrl" @JvmStatic - val client: OkHttpClient by lazy { + val defaultClient: OkHttpClient by lazy { builder.build() } @@ -66,55 +66,47 @@ open class ApiClient(val baseUrl: String) { return contentType ?: "application/octet-stream" } - protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = + protected inline fun requestBody(content: T, mediaType: String?): RequestBody = when { - content is File -> content.asRequestBody(mediaType.toMediaTypeOrNull()) - mediaType == FormDataMediaType -> { + mediaType == FormDataMediaType -> MultipartBody.Builder() .setType(MultipartBody.FORM) .apply { - // content's type *must* be Map + // content's type *must* be Map> @Suppress("UNCHECKED_CAST") - (content as Map).forEach { (key, value) -> - if (value is File) { - val partHeaders = Headers.headersOf( - "Content-Disposition", - "form-data; name=\"$key\"; filename=\"${value.name}\"" - ) - val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull() - addPart(partHeaders, value.asRequestBody(fileMediaType)) - } else { - val partHeaders = Headers.headersOf( - "Content-Disposition", - "form-data; name=\"$key\"" - ) - addPart( - partHeaders, - parameterToString(value).toRequestBody(null) - ) + (content as Map>).forEach { (name, part) -> + val contentType = part.headers.remove("Content-Type") + val bodies = if (part.body is Iterable<*>) part.body else listOf(part.body) + bodies.forEach { body -> + val headers = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"" + if (body is File) "; filename=\"${body.name}\"" else "") + addPart(headers.toHeaders(), + requestSingleBody(body, contentType)) } } }.build() - } + else -> requestSingleBody(content, mediaType) + } + + protected inline fun requestSingleBody(content: T, mediaType: String?): RequestBody = + when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) mediaType == FormUrlEncMediaType -> { FormBody.Builder().apply { - // content's type *must* be Map + // content's type *must* be Map> @Suppress("UNCHECKED_CAST") - (content as Map).forEach { (key, value) -> - add(key, parameterToString(value)) + (content as Map>).forEach { (name, part) -> + add(name, parameterToString(part.body)) } }.build() } - mediaType == JsonMediaType -> { + mediaType == null || mediaType.startsWith("application/") && mediaType.endsWith("json") -> if (content == null) { EMPTY_REQUEST } else { Serializer.moshi.adapter(T::class.java).toJson(content) - .toRequestBody( - mediaType.toMediaTypeOrNull() - ) + .toRequestBody((mediaType ?: JsonMediaType).toMediaTypeOrNull()) } - } mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.") // TODO: this should be extended with other serializers else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.") @@ -125,27 +117,31 @@ open class ApiClient(val baseUrl: String) { if(body == null) { return null } + if (T::class.java == File::class.java) { + // return tempFile + // Attention: if you are developing an android app that supports API Level 25 and bellow, please check flag supportAndroidApiLevel25AndBelow in https://openapi-generator.tech/docs/generators/kotlin#config-options + val tempFile = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + tempFile.deleteOnExit() + body.byteStream().use { inputStream -> + tempFile.outputStream().use { tempFileOutputStream -> + inputStream.copyTo(tempFileOutputStream) + } + } + return tempFile as T + } val bodyContent = body.string() if (bodyContent.isEmpty()) { return null } - if (T::class.java == File::class.java) { - // return tempfile - val f = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() - f.deleteOnExit() - val out = BufferedWriter(FileWriter(f)) - out.write(bodyContent) - out.close() - return f as T - } - return when(mediaType) { - JsonMediaType -> Serializer.moshi.adapter().fromJson(bodyContent) + return when { + mediaType==null || (mediaType.startsWith("application/") && mediaType.endsWith("json")) -> + Serializer.moshi.adapter().fromJson(bodyContent) else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") } } - protected inline fun request(requestConfig: RequestConfig): ApiInfrastructureResponse { + protected inline fun request(requestConfig: RequestConfig): ApiResponse { val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") val url = httpUrl.newBuilder() @@ -167,11 +163,11 @@ open class ApiClient(val baseUrl: String) { } val headers = requestConfig.headers - if(headers[ContentType] ?: "" == "") { + if(headers[ContentType].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") } - if(headers[Accept] ?: "" == "") { + if(headers[Accept].isNullOrEmpty()) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } @@ -229,7 +225,7 @@ open class ApiClient(val baseUrl: String) { null -> "" is Array<*> -> toMultiValue(value, "csv").toString() is Iterable<*> -> toMultiValue(value, "csv").toString() - is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime -> parseDateToQueryString(value) else -> value.toString() } diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt new file mode 100644 index 000000000000..20ac25b12500 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiResponse(val responseType: ResponseType): Response { + abstract val statusCode: Int + abstract val headers: Map> +} + +class Success( + val data: T?, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +): ApiResponse(ResponseType.Success) + +class Informational( + val statusText: String, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.Informational) + +class Redirection( + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.Redirection) + +class ClientError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.ClientError) + +class ServerError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> +): ApiResponse(ResponseType.ServerError) diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt new file mode 100644 index 000000000000..be00e38fbaee --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt @@ -0,0 +1,11 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectProperty.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectProperty.kt index 959505477f7d..b6a46f1fa2c4 100644 --- a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectProperty.kt +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectProperty.kt @@ -20,8 +20,10 @@ package org.openapitools.client.models -import org.openapitools.client.models.OneOfLessThanNullCommaPropertyTypeCommaOtherPropertyTypeGreaterThan -import org.openapitools.client.models.OneOfLessThanStringCommaNumberGreaterThan +import org.openapitools.client.models.ModelWithNullableObjectPropertyNonNullableProperty +import org.openapitools.client.models.ModelWithNullableObjectPropertyPropertyName30 +import org.openapitools.client.models.ModelWithNullableObjectPropertyPropertyName31 +import org.openapitools.client.models.ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes import org.openapitools.client.models.PropertyType import com.squareup.moshi.Json @@ -43,16 +45,16 @@ data class ModelWithNullableObjectProperty ( val propertyName: PropertyType? = null, @Json(name = "propertyName30") - val propertyName30: PropertyType? = null, + val propertyName30: ModelWithNullableObjectPropertyPropertyName30? = null, @Json(name = "propertyName31") - val propertyName31: PropertyType? = null, + val propertyName31: ModelWithNullableObjectPropertyPropertyName31? = null, @Json(name = "nonNullableProperty") - val nonNullableProperty: OneOfLessThanStringCommaNumberGreaterThan? = null, + val nonNullableProperty: ModelWithNullableObjectPropertyNonNullableProperty? = null, @Json(name = "propertyWithNullAndTwoTypes") - val propertyWithNullAndTwoTypes: OneOfLessThanNullCommaPropertyTypeCommaOtherPropertyTypeGreaterThan? = null + val propertyWithNullAndTwoTypes: ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes? = null ) : Serializable { companion object { diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyNonNullableProperty.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyNonNullableProperty.kt new file mode 100644 index 000000000000..3da0d02cc9d8 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyNonNullableProperty.kt @@ -0,0 +1,38 @@ +/** + * Title + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import java.io.Serializable + +/** + * + * + */ + +data class ModelWithNullableObjectPropertyNonNullableProperty ( + +) : Serializable companion object { + private const val serialVersionUID: Long = 123 + } + + diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName30.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName30.kt new file mode 100644 index 000000000000..c83445965d4f --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName30.kt @@ -0,0 +1,45 @@ +/** + * Title + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.PropertyType + +import com.squareup.moshi.Json +import java.io.Serializable + +/** + * + * + * @param foo + */ + +data class ModelWithNullableObjectPropertyPropertyName30 ( + + @Json(name = "foo") + val foo: kotlin.String? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName31.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName31.kt new file mode 100644 index 000000000000..316c26d3abc4 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyName31.kt @@ -0,0 +1,45 @@ +/** + * Title + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.PropertyType + +import com.squareup.moshi.Json +import java.io.Serializable + +/** + * + * + * @param foo + */ + +data class ModelWithNullableObjectPropertyPropertyName31 ( + + @Json(name = "foo") + val foo: kotlin.String? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.kt b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.kt new file mode 100644 index 000000000000..3764f9c1ca70 --- /dev/null +++ b/samples/client/petstore/kotlin-nullable-object-propery/src/main/kotlin/org/openapitools/client/models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.kt @@ -0,0 +1,50 @@ +/** + * Title + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.OtherPropertyType +import org.openapitools.client.models.PropertyType + +import com.squareup.moshi.Json +import java.io.Serializable + +/** + * + * + * @param foo + * @param bar + */ + +data class ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes ( + + @Json(name = "foo") + val foo: kotlin.String? = null, + + @Json(name = "bar") + val bar: kotlin.String? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/php/nullable-object-property-php/.gitignore b/samples/client/petstore/php/nullable-object-property-php/.gitignore index 92f7fdeff58a..9f1681c2be8d 100644 --- a/samples/client/petstore/php/nullable-object-property-php/.gitignore +++ b/samples/client/petstore/php/nullable-object-property-php/.gitignore @@ -9,6 +9,7 @@ composer.phar # php-cs-fixer cache .php_cs.cache +.php-cs-fixer.cache # PHPUnit cache .phpunit.result.cache diff --git a/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/FILES b/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/FILES index 31c47988258c..8d45a4bdf877 100644 --- a/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/FILES +++ b/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/FILES @@ -1,10 +1,14 @@ .gitignore -.php_cs +.php-cs-fixer.dist.php .travis.yml README.md composer.json docs/Api/DefaultApi.md docs/Model/ModelWithNullableObjectProperty.md +docs/Model/ModelWithNullableObjectPropertyNonNullableProperty.md +docs/Model/ModelWithNullableObjectPropertyPropertyName30.md +docs/Model/ModelWithNullableObjectPropertyPropertyName31.md +docs/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md docs/Model/OtherPropertyType.md docs/Model/PropertyType.md git_push.sh @@ -14,6 +18,10 @@ lib/Configuration.php lib/HeaderSelector.php lib/Model/ModelInterface.php lib/Model/ModelWithNullableObjectProperty.php +lib/Model/ModelWithNullableObjectPropertyNonNullableProperty.php +lib/Model/ModelWithNullableObjectPropertyPropertyName30.php +lib/Model/ModelWithNullableObjectPropertyPropertyName31.php +lib/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.php lib/Model/OtherPropertyType.php lib/Model/PropertyType.php lib/ObjectSerializer.php diff --git a/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/VERSION b/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/VERSION index 4077803655c0..89648de3311c 100644 --- a/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/VERSION +++ b/samples/client/petstore/php/nullable-object-property-php/.openapi-generator/VERSION @@ -1 +1 @@ -5.3.1-SNAPSHOT \ No newline at end of file +6.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/php/nullable-object-property-php/.php-cs-fixer.dist.php b/samples/client/petstore/php/nullable-object-property-php/.php-cs-fixer.dist.php new file mode 100644 index 000000000000..af9cf39fddb0 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/.php-cs-fixer.dist.php @@ -0,0 +1,29 @@ +in(__DIR__) + ->exclude('vendor') + ->exclude('test') + ->exclude('tests') +; + +$config = new PhpCsFixer\Config(); +return $config->setRules([ + '@PSR12' => true, + 'phpdoc_order' => true, + 'array_syntax' => [ 'syntax' => 'short' ], + 'strict_comparison' => true, + 'strict_param' => true, + 'no_trailing_whitespace' => false, + 'no_trailing_whitespace_in_comment' => false, + 'braces' => false, + 'single_blank_line_at_eof' => false, + 'blank_line_after_namespace' => false, + 'no_leading_import_slash' => false, + ]) + ->setFinder($finder) +; diff --git a/samples/client/petstore/php/nullable-object-property-php/.travis.yml b/samples/client/petstore/php/nullable-object-property-php/.travis.yml index 714772ee9310..667b81565308 100644 --- a/samples/client/petstore/php/nullable-object-property-php/.travis.yml +++ b/samples/client/petstore/php/nullable-object-property-php/.travis.yml @@ -3,7 +3,6 @@ language: php # https://docs.travis-ci.com/user/reference/bionic/#php-support dist: bionic php: - - 7.3 - 7.4 before_install: "composer install" script: "vendor/bin/phpunit" diff --git a/samples/client/petstore/php/nullable-object-property-php/README.md b/samples/client/petstore/php/nullable-object-property-php/README.md index 87f06a7d37f8..120619424a20 100644 --- a/samples/client/petstore/php/nullable-object-property-php/README.md +++ b/samples/client/petstore/php/nullable-object-property-php/README.md @@ -7,8 +7,8 @@ No description provided (generated by Openapi Generator https://github.com/opena ### Requirements -PHP 7.3 and later. -Should also work with PHP 8.0 but has not been tested. +PHP 7.4 and later. +Should also work with PHP 8.0. ### Composer @@ -76,6 +76,10 @@ Class | Method | HTTP request | Description ## Models - [ModelWithNullableObjectProperty](docs/Model/ModelWithNullableObjectProperty.md) +- [ModelWithNullableObjectPropertyNonNullableProperty](docs/Model/ModelWithNullableObjectPropertyNonNullableProperty.md) +- [ModelWithNullableObjectPropertyPropertyName30](docs/Model/ModelWithNullableObjectPropertyPropertyName30.md) +- [ModelWithNullableObjectPropertyPropertyName31](docs/Model/ModelWithNullableObjectPropertyPropertyName31.md) +- [ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes](docs/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md) - [OtherPropertyType](docs/Model/OtherPropertyType.md) - [PropertyType](docs/Model/PropertyType.md) diff --git a/samples/client/petstore/php/nullable-object-property-php/composer.json b/samples/client/petstore/php/nullable-object-property-php/composer.json index 2421a729e0b6..cccbe610e36b 100644 --- a/samples/client/petstore/php/nullable-object-property-php/composer.json +++ b/samples/client/petstore/php/nullable-object-property-php/composer.json @@ -18,16 +18,16 @@ } ], "require": { - "php": "^7.3 || ^8.0", + "php": "^7.4 || ^8.0", "ext-curl": "*", "ext-json": "*", "ext-mbstring": "*", "guzzlehttp/guzzle": "^7.3", - "guzzlehttp/psr7": "^2.0" + "guzzlehttp/psr7": "^1.7 || ^2.0" }, "require-dev": { "phpunit/phpunit": "^8.0 || ^9.0", - "friendsofphp/php-cs-fixer": "^2.12" + "friendsofphp/php-cs-fixer": "^3.5" }, "autoload": { "psr-4": { "OpenAPI\\Client\\" : "lib/" } diff --git a/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectProperty.md b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectProperty.md index 9604ca98da04..6f8943a49c1d 100644 --- a/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectProperty.md +++ b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectProperty.md @@ -5,9 +5,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **property_name** | [**\OpenAPI\Client\Model\PropertyType**](PropertyType.md) | | [optional] -**property_name30** | [**\OpenAPI\Client\Model\PropertyType**](PropertyType.md) | | [optional] -**property_name31** | [**\OpenAPI\Client\Model\PropertyType**](PropertyType.md) | | [optional] -**non_nullable_property** | [**OneOfStringNumber**](OneOfStringNumber.md) | | [optional] -**property_with_null_and_two_types** | [**OneOfNullPropertyTypeOtherPropertyType**](OneOfNullPropertyTypeOtherPropertyType.md) | | [optional] +**property_name30** | [**\OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName30**](ModelWithNullableObjectPropertyPropertyName30.md) | | [optional] +**property_name31** | [**\OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName31**](ModelWithNullableObjectPropertyPropertyName31.md) | | [optional] +**non_nullable_property** | [**\OpenAPI\Client\Model\ModelWithNullableObjectPropertyNonNullableProperty**](ModelWithNullableObjectPropertyNonNullableProperty.md) | | [optional] +**property_with_null_and_two_types** | [**\OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes**](ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md) | | [optional] [[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyNonNullableProperty.md b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyNonNullableProperty.md new file mode 100644 index 000000000000..b65ab88861bd --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyNonNullableProperty.md @@ -0,0 +1,8 @@ +# # ModelWithNullableObjectPropertyNonNullableProperty + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyName30.md b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyName30.md new file mode 100644 index 000000000000..4f896a0638b7 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyName30.md @@ -0,0 +1,9 @@ +# # ModelWithNullableObjectPropertyPropertyName30 + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **string** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyName31.md b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyName31.md new file mode 100644 index 000000000000..830d4d1e47cd --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyName31.md @@ -0,0 +1,9 @@ +# # ModelWithNullableObjectPropertyPropertyName31 + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **string** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md new file mode 100644 index 000000000000..30ea2a999085 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/docs/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.md @@ -0,0 +1,10 @@ +# # ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**foo** | **string** | | [optional] +**bar** | **string** | | [optional] + +[[Back to Model list]](../../README.md#models) [[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/Api/DefaultApi.php b/samples/client/petstore/php/nullable-object-property-php/lib/Api/DefaultApi.php index b7db18bf0e62..5e7ec6cd7004 100644 --- a/samples/client/petstore/php/nullable-object-property-php/lib/Api/DefaultApi.php +++ b/samples/client/petstore/php/nullable-object-property-php/lib/Api/DefaultApi.php @@ -1,7 +1,7 @@ getBody(); //stream goes to serializer } else { $content = (string) $response->getBody(); + if ('\OpenAPI\Client\Model\ModelWithNullableObjectProperty' !== 'string') { + $content = json_decode($content); + } } return [ @@ -196,6 +199,9 @@ public function operationWithHttpInfo() $content = $response->getBody(); //stream goes to serializer } else { $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } } return [ @@ -256,6 +262,9 @@ function ($response) use ($returnType) { $content = $response->getBody(); //stream goes to serializer } else { $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } } return [ @@ -334,7 +343,7 @@ public function operationRequest() } else { // for HTTP post (form) - $httpBody = \GuzzleHttp\Psr7\Query::build($formParams); + $httpBody = ObjectSerializer::buildQuery($formParams); } } @@ -350,7 +359,7 @@ public function operationRequest() $headers ); - $query = \GuzzleHttp\Psr7\Query::build($queryParams); + $query = ObjectSerializer::buildQuery($queryParams); return new Request( 'GET', $this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''), diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/ApiException.php b/samples/client/petstore/php/nullable-object-property-php/lib/ApiException.php index 55445615ded1..2569463ec230 100644 --- a/samples/client/petstore/php/nullable-object-property-php/lib/ApiException.php +++ b/samples/client/petstore/php/nullable-object-property-php/lib/ApiException.php @@ -1,7 +1,7 @@ accessToken; } + /** + * Sets boolean format for query string. + * + * @param string $booleanFormatForQueryString Boolean format for query string + * + * @return $this + */ + public function setBooleanFormatForQueryString(string $booleanFormat) + { + $this->booleanFormatForQueryString = $booleanFormat; + + return $this; + } + + /** + * Gets boolean format for query string. + * + * @return string Boolean format for query string + */ + public function getBooleanFormatForQueryString(): string + { + return $this->booleanFormatForQueryString; + } + /** * Sets the username for HTTP basic authentication * diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/HeaderSelector.php b/samples/client/petstore/php/nullable-object-property-php/lib/HeaderSelector.php index fa265d7fb9eb..e639eeecd5e2 100644 --- a/samples/client/petstore/php/nullable-object-property-php/lib/HeaderSelector.php +++ b/samples/client/petstore/php/nullable-object-property-php/lib/HeaderSelector.php @@ -1,7 +1,7 @@ - * @template TKey int|null - * @template TValue mixed|null + * @implements \ArrayAccess */ class ModelWithNullableObjectProperty implements ModelInterface, ArrayAccess, \JsonSerializable { @@ -60,10 +58,10 @@ class ModelWithNullableObjectProperty implements ModelInterface, ArrayAccess, \J */ protected static $openAPITypes = [ 'property_name' => '\OpenAPI\Client\Model\PropertyType', - 'property_name30' => '\OpenAPI\Client\Model\PropertyType', - 'property_name31' => '\OpenAPI\Client\Model\PropertyType', - 'non_nullable_property' => 'OneOfStringNumber', - 'property_with_null_and_two_types' => 'OneOfNullPropertyTypeOtherPropertyType' + 'property_name30' => '\OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName30', + 'property_name31' => '\OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName31', + 'non_nullable_property' => '\OpenAPI\Client\Model\ModelWithNullableObjectPropertyNonNullableProperty', + 'property_with_null_and_two_types' => '\OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes' ]; /** @@ -256,7 +254,7 @@ public function setPropertyName($property_name) /** * Gets property_name30 * - * @return \OpenAPI\Client\Model\PropertyType|null + * @return \OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName30|null */ public function getPropertyName30() { @@ -266,7 +264,7 @@ public function getPropertyName30() /** * Sets property_name30 * - * @param \OpenAPI\Client\Model\PropertyType|null $property_name30 property_name30 + * @param \OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName30|null $property_name30 property_name30 * * @return self */ @@ -280,7 +278,7 @@ public function setPropertyName30($property_name30) /** * Gets property_name31 * - * @return \OpenAPI\Client\Model\PropertyType|null + * @return \OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName31|null */ public function getPropertyName31() { @@ -290,7 +288,7 @@ public function getPropertyName31() /** * Sets property_name31 * - * @param \OpenAPI\Client\Model\PropertyType|null $property_name31 property_name31 + * @param \OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyName31|null $property_name31 property_name31 * * @return self */ @@ -304,7 +302,7 @@ public function setPropertyName31($property_name31) /** * Gets non_nullable_property * - * @return OneOfStringNumber|null + * @return \OpenAPI\Client\Model\ModelWithNullableObjectPropertyNonNullableProperty|null */ public function getNonNullableProperty() { @@ -314,7 +312,7 @@ public function getNonNullableProperty() /** * Sets non_nullable_property * - * @param OneOfStringNumber|null $non_nullable_property non_nullable_property + * @param \OpenAPI\Client\Model\ModelWithNullableObjectPropertyNonNullableProperty|null $non_nullable_property non_nullable_property * * @return self */ @@ -328,7 +326,7 @@ public function setNonNullableProperty($non_nullable_property) /** * Gets property_with_null_and_two_types * - * @return OneOfNullPropertyTypeOtherPropertyType|null + * @return \OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes|null */ public function getPropertyWithNullAndTwoTypes() { @@ -338,7 +336,7 @@ public function getPropertyWithNullAndTwoTypes() /** * Sets property_with_null_and_two_types * - * @param OneOfNullPropertyTypeOtherPropertyType|null $property_with_null_and_two_types property_with_null_and_two_types + * @param \OpenAPI\Client\Model\ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes|null $property_with_null_and_two_types property_with_null_and_two_types * * @return self */ @@ -355,7 +353,7 @@ public function setPropertyWithNullAndTwoTypes($property_with_null_and_two_types * * @return boolean */ - public function offsetExists($offset) + public function offsetExists($offset): bool { return isset($this->container[$offset]); } @@ -367,6 +365,7 @@ public function offsetExists($offset) * * @return mixed|null */ + #[\ReturnTypeWillChange] public function offsetGet($offset) { return $this->container[$offset] ?? null; @@ -380,7 +379,7 @@ public function offsetGet($offset) * * @return void */ - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { if (is_null($offset)) { $this->container[] = $value; @@ -396,7 +395,7 @@ public function offsetSet($offset, $value) * * @return void */ - public function offsetUnset($offset) + public function offsetUnset($offset): void { unset($this->container[$offset]); } @@ -408,6 +407,7 @@ public function offsetUnset($offset) * @return mixed Returns data which can be serialized by json_encode(), which is a value * of any type other than a resource. */ + #[\ReturnTypeWillChange] public function jsonSerialize() { return ObjectSerializer::sanitizeForSerialization($this); diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyNonNullableProperty.php b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyNonNullableProperty.php new file mode 100644 index 000000000000..bae83149e4d4 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyNonNullableProperty.php @@ -0,0 +1,295 @@ + + */ +class ModelWithNullableObjectPropertyNonNullableProperty implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'ModelWithNullableObjectProperty_nonNullableProperty'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyName30.php b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyName30.php new file mode 100644 index 000000000000..372f35dc0b6a --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyName30.php @@ -0,0 +1,320 @@ + + */ +class ModelWithNullableObjectPropertyPropertyName30 implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'ModelWithNullableObjectProperty_propertyName30'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'foo' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'foo' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'foo' => 'foo' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'foo' => 'setFoo' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'foo' => 'getFoo' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['foo'] = $data['foo'] ?? null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets foo + * + * @return string|null + */ + public function getFoo() + { + return $this->container['foo']; + } + + /** + * Sets foo + * + * @param string|null $foo foo + * + * @return self + */ + public function setFoo($foo) + { + $this->container['foo'] = $foo; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyName31.php b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyName31.php new file mode 100644 index 000000000000..040810fcdff6 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyName31.php @@ -0,0 +1,320 @@ + + */ +class ModelWithNullableObjectPropertyPropertyName31 implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'ModelWithNullableObjectProperty_propertyName31'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'foo' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'foo' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'foo' => 'foo' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'foo' => 'setFoo' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'foo' => 'getFoo' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['foo'] = $data['foo'] ?? null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets foo + * + * @return string|null + */ + public function getFoo() + { + return $this->container['foo']; + } + + /** + * Sets foo + * + * @param string|null $foo foo + * + * @return self + */ + public function setFoo($foo) + { + $this->container['foo'] = $foo; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.php b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.php new file mode 100644 index 000000000000..d72d1289fa4d --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/lib/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.php @@ -0,0 +1,350 @@ + + */ +class ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes implements ModelInterface, ArrayAccess, \JsonSerializable +{ + public const DISCRIMINATOR = null; + + /** + * The original name of the model. + * + * @var string + */ + protected static $openAPIModelName = 'ModelWithNullableObjectProperty_propertyWithNullAndTwoTypes'; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @var string[] + */ + protected static $openAPITypes = [ + 'foo' => 'string', + 'bar' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @var string[] + * @phpstan-var array + * @psalm-var array + */ + protected static $openAPIFormats = [ + 'foo' => null, + 'bar' => null + ]; + + /** + * Array of property to type mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPITypes() + { + return self::$openAPITypes; + } + + /** + * Array of property to format mappings. Used for (de)serialization + * + * @return array + */ + public static function openAPIFormats() + { + return self::$openAPIFormats; + } + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @var string[] + */ + protected static $attributeMap = [ + 'foo' => 'foo', + 'bar' => 'bar' + ]; + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @var string[] + */ + protected static $setters = [ + 'foo' => 'setFoo', + 'bar' => 'setBar' + ]; + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @var string[] + */ + protected static $getters = [ + 'foo' => 'getFoo', + 'bar' => 'getBar' + ]; + + /** + * Array of attributes where the key is the local name, + * and the value is the original name + * + * @return array + */ + public static function attributeMap() + { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * + * @return array + */ + public static function setters() + { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * + * @return array + */ + public static function getters() + { + return self::$getters; + } + + /** + * The original name of the model. + * + * @return string + */ + public function getModelName() + { + return self::$openAPIModelName; + } + + + /** + * Associative array for storing property values + * + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * + * @param mixed[] $data Associated array of property values + * initializing the model + */ + public function __construct(array $data = null) + { + $this->container['foo'] = $data['foo'] ?? null; + $this->container['bar'] = $data['bar'] ?? null; + } + + /** + * Show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalidProperties = []; + + return $invalidProperties; + } + + /** + * Validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + return count($this->listInvalidProperties()) === 0; + } + + + /** + * Gets foo + * + * @return string|null + */ + public function getFoo() + { + return $this->container['foo']; + } + + /** + * Sets foo + * + * @param string|null $foo foo + * + * @return self + */ + public function setFoo($foo) + { + $this->container['foo'] = $foo; + + return $this; + } + + /** + * Gets bar + * + * @return string|null + */ + public function getBar() + { + return $this->container['bar']; + } + + /** + * Sets bar + * + * @param string|null $bar bar + * + * @return self + */ + public function setBar($bar) + { + $this->container['bar'] = $bar; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * + * @param integer $offset Offset + * + * @return boolean + */ + public function offsetExists($offset): bool + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * + * @param integer $offset Offset + * + * @return mixed|null + */ + #[\ReturnTypeWillChange] + public function offsetGet($offset) + { + return $this->container[$offset] ?? null; + } + + /** + * Sets value based on offset. + * + * @param int|null $offset Offset + * @param mixed $value Value to be set + * + * @return void + */ + public function offsetSet($offset, $value): void + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * + * @param integer $offset Offset + * + * @return void + */ + public function offsetUnset($offset): void + { + unset($this->container[$offset]); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php + * + * @return mixed Returns data which can be serialized by json_encode(), which is a value + * of any type other than a resource. + */ + #[\ReturnTypeWillChange] + public function jsonSerialize() + { + return ObjectSerializer::sanitizeForSerialization($this); + } + + /** + * Gets the string presentation of the object + * + * @return string + */ + public function __toString() + { + return json_encode( + ObjectSerializer::sanitizeForSerialization($this), + JSON_PRETTY_PRINT + ); + } + + /** + * Gets a header-safe presentation of the object + * + * @return string + */ + public function toHeaderValue() + { + return json_encode(ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/Model/OtherPropertyType.php b/samples/client/petstore/php/nullable-object-property-php/lib/Model/OtherPropertyType.php index 1c001e8d9de5..6c5d4d238d59 100644 --- a/samples/client/petstore/php/nullable-object-property-php/lib/Model/OtherPropertyType.php +++ b/samples/client/petstore/php/nullable-object-property-php/lib/Model/OtherPropertyType.php @@ -2,7 +2,7 @@ /** * OtherPropertyType * - * PHP version 7.3 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: latest * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.3.1-SNAPSHOT + * OpenAPI Generator version: 6.0.1-SNAPSHOT */ /** @@ -38,9 +38,7 @@ * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech - * @implements \ArrayAccess - * @template TKey int|null - * @template TValue mixed|null + * @implements \ArrayAccess */ class OtherPropertyType implements ModelInterface, ArrayAccess, \JsonSerializable { @@ -235,7 +233,7 @@ public function setBar($bar) * * @return boolean */ - public function offsetExists($offset) + public function offsetExists($offset): bool { return isset($this->container[$offset]); } @@ -247,6 +245,7 @@ public function offsetExists($offset) * * @return mixed|null */ + #[\ReturnTypeWillChange] public function offsetGet($offset) { return $this->container[$offset] ?? null; @@ -260,7 +259,7 @@ public function offsetGet($offset) * * @return void */ - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { if (is_null($offset)) { $this->container[] = $value; @@ -276,7 +275,7 @@ public function offsetSet($offset, $value) * * @return void */ - public function offsetUnset($offset) + public function offsetUnset($offset): void { unset($this->container[$offset]); } @@ -288,6 +287,7 @@ public function offsetUnset($offset) * @return mixed Returns data which can be serialized by json_encode(), which is a value * of any type other than a resource. */ + #[\ReturnTypeWillChange] public function jsonSerialize() { return ObjectSerializer::sanitizeForSerialization($this); diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/Model/PropertyType.php b/samples/client/petstore/php/nullable-object-property-php/lib/Model/PropertyType.php index 8029b6736e64..ba6479af9814 100644 --- a/samples/client/petstore/php/nullable-object-property-php/lib/Model/PropertyType.php +++ b/samples/client/petstore/php/nullable-object-property-php/lib/Model/PropertyType.php @@ -2,7 +2,7 @@ /** * PropertyType * - * PHP version 7.3 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: latest * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.3.1-SNAPSHOT + * OpenAPI Generator version: 6.0.1-SNAPSHOT */ /** @@ -38,9 +38,7 @@ * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech - * @implements \ArrayAccess - * @template TKey int|null - * @template TValue mixed|null + * @implements \ArrayAccess */ class PropertyType implements ModelInterface, ArrayAccess, \JsonSerializable { @@ -235,7 +233,7 @@ public function setFoo($foo) * * @return boolean */ - public function offsetExists($offset) + public function offsetExists($offset): bool { return isset($this->container[$offset]); } @@ -247,6 +245,7 @@ public function offsetExists($offset) * * @return mixed|null */ + #[\ReturnTypeWillChange] public function offsetGet($offset) { return $this->container[$offset] ?? null; @@ -260,7 +259,7 @@ public function offsetGet($offset) * * @return void */ - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { if (is_null($offset)) { $this->container[] = $value; @@ -276,7 +275,7 @@ public function offsetSet($offset, $value) * * @return void */ - public function offsetUnset($offset) + public function offsetUnset($offset): void { unset($this->container[$offset]); } @@ -288,6 +287,7 @@ public function offsetUnset($offset) * @return mixed Returns data which can be serialized by json_encode(), which is a value * of any type other than a resource. */ + #[\ReturnTypeWillChange] public function jsonSerialize() { return ObjectSerializer::sanitizeForSerialization($this); diff --git a/samples/client/petstore/php/nullable-object-property-php/lib/ObjectSerializer.php b/samples/client/petstore/php/nullable-object-property-php/lib/ObjectSerializer.php index 5b0308479775..740c5e7e1cfb 100644 --- a/samples/client/petstore/php/nullable-object-property-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/nullable-object-property-php/lib/ObjectSerializer.php @@ -2,7 +2,7 @@ /** * ObjectSerializer * - * PHP version 7.3 + * PHP version 7.4 * * @category Class * @package OpenAPI\Client @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: latest * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 5.3.1-SNAPSHOT + * OpenAPI Generator version: 6.0.1-SNAPSHOT */ /** @@ -28,6 +28,7 @@ namespace OpenAPI\Client; +use GuzzleHttp\Psr7\Utils; use OpenAPI\Client\Model\ModelInterface; /** @@ -129,6 +130,20 @@ public static function sanitizeFilename($filename) } } + /** + * Shorter timestamp microseconds to 6 digits length. + * + * @param string $timestamp Original timestamp + * + * @return string the shorten timestamp + */ + public static function sanitizeTimestamp($timestamp) + { + if (!is_string($timestamp)) return $timestamp; + + return preg_replace('/(:\d{2}.\d{6})\d*/', '$1', $timestamp); + } + /** * Take value and turn it into a string suitable for inclusion in * the path, by url-encoding. @@ -143,22 +158,91 @@ public static function toPathValue($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. + * Take query parameter properties and turn it into an array suitable for + * native http_build_query or GuzzleHttp\Psr7\Query::build. * - * @param string[]|string|\DateTime $object an object to be serialized to a string + * @param mixed $value Parameter value + * @param string $paramName Parameter name + * @param string $openApiType OpenAPIType eg. array or object + * @param string $style Parameter serialization style + * @param bool $explode Parameter explode option + * @param bool $required Whether query param is required or not * - * @return string the serialized object + * @return array */ - public static function toQueryValue($object) + public static function toQueryValue( + $value, + string $paramName, + string $openApiType = 'string', + string $style = 'form', + bool $explode = true, + bool $required = true + ): array { + if ( + empty($value) + && ($value !== false || $openApiType !== 'boolean') // if $value === false and $openApiType ==='boolean' it isn't empty + ) { + if ($required) { + return ["{$paramName}" => '']; + } else { + return []; + } + } + + $query = []; + $value = (in_array($openApiType, ['object', 'array'], true)) ? (array)$value : $value; + + // since \GuzzleHttp\Psr7\Query::build fails with nested arrays + // need to flatten array first + $flattenArray = function ($arr, $name, &$result = []) use (&$flattenArray, $style, $explode) { + if (!is_array($arr)) return $arr; + + foreach ($arr as $k => $v) { + $prop = ($style === 'deepObject') ? $prop = "{$name}[{$k}]" : $k; + + if (is_array($v)) { + $flattenArray($v, $prop, $result); + } else { + if ($style !== 'deepObject' && !$explode) { + // push key itself + $result[] = $prop; + } + $result[$prop] = $v; + } + } + return $result; + }; + + $value = $flattenArray($value, $paramName); + + if ($openApiType === 'object' && ($style === 'deepObject' || $explode)) { + return $value; + } + + if ('boolean' === $openApiType && is_bool($value)) { + $value = self::convertBoolToQueryStringFormat($value); + } + + // handle style in serializeCollection + $query[$paramName] = ($explode) ? $value : self::serializeCollection((array)$value, $style); + + return $query; + } + + /** + * Convert boolean value to format for query string. + * + * @param bool $value Boolean value + * + * @return int|string Boolean value in format + */ + public static function convertBoolToQueryStringFormat(bool $value) { - if (is_array($object)) { - return implode(',', $object); - } else { - return self::toString($object); + if (Configuration::BOOLEAN_FORMAT_STRING == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString()) { + return $value ? 'true' : 'false'; } + + return (int) $value; } /** @@ -215,7 +299,7 @@ public static function toString($value) } elseif (is_bool($value)) { return $value ? 'true' : 'false'; } else { - return $value; + return (string) $value; } } @@ -305,7 +389,7 @@ public static function deserialize($data, $class, $httpHeaders = null) if ($class === 'object') { settype($data, 'array'); return $data; - } else if ($class === 'mixed') { + } elseif ($class === 'mixed') { settype($data, gettype($data)); return $data; } @@ -322,28 +406,26 @@ public static function deserialize($data, $class, $httpHeaders = null) return new \DateTime($data); } catch (\Exception $exception) { // Some API's return a date-time with too high nanosecond - // precision for php's DateTime to handle. This conversion - // (string -> unix timestamp -> DateTime) is a workaround - // for the problem. - return (new \DateTime())->setTimestamp(strtotime($data)); + // precision for php's DateTime to handle. + // With provided regexp 6 digits of microseconds saved + return new \DateTime(self::sanitizeTimestamp($data)); } } else { return null; } } - /** @psalm-suppress ParadoxicalCondition */ - if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { - settype($data, $class); - return $data; - } - if ($class === '\SplFileObject') { + $data = Utils::streamFor($data); + /** @var \Psr\Http\Message\StreamInterface $data */ // determine file name - if (array_key_exists('Content-Disposition', $httpHeaders) && - preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { + if ( + is_array($httpHeaders) + && array_key_exists('Content-Disposition', $httpHeaders) + && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match) + ) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . DIRECTORY_SEPARATOR . self::sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); @@ -356,7 +438,16 @@ public static function deserialize($data, $class, $httpHeaders = null) fclose($file); return new \SplFileObject($filename, 'r'); - } elseif (method_exists($class, 'getAllowableEnumValues')) { + } + + /** @psalm-suppress ParadoxicalCondition */ + if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { + settype($data, $class); + return $data; + } + + + if (method_exists($class, 'getAllowableEnumValues')) { if (!in_array($data, $class::getAllowableEnumValues(), true)) { $imploded = implode("', '", $class::getAllowableEnumValues()); throw new \InvalidArgumentException("Invalid value for enum '$class', must be one of: '$imploded'"); @@ -390,4 +481,24 @@ public static function deserialize($data, $class, $httpHeaders = null) return $instance; } } + + /** + * Native `http_build_query` wrapper. + * @see https://www.php.net/manual/en/function.http-build-query + * + * @param array|object $data May be an array or object containing properties. + * @param string $numeric_prefix If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only. + * @param string|null $arg_separator arg_separator.output is used to separate arguments but may be overridden by specifying this parameter. + * @param int $encoding_type Encoding type. By default, PHP_QUERY_RFC1738. + * + * @return string + */ + public static function buildQuery( + $data, + string $numeric_prefix = '', + ?string $arg_separator = null, + int $encoding_type = \PHP_QUERY_RFC3986 + ): string { + return \GuzzleHttp\Psr7\Query::build($data, $encoding_type); + } } diff --git a/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyNonNullablePropertyTest.php b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyNonNullablePropertyTest.php new file mode 100644 index 000000000000..25325d324253 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyNonNullablePropertyTest.php @@ -0,0 +1,81 @@ +markTestIncomplete('Not implemented'); + } +} diff --git a/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyName30Test.php b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyName30Test.php new file mode 100644 index 000000000000..49697cf08fb9 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyName30Test.php @@ -0,0 +1,90 @@ +markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "foo" + */ + public function testPropertyFoo() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } +} diff --git a/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyName31Test.php b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyName31Test.php new file mode 100644 index 000000000000..85cfe072f5f4 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyName31Test.php @@ -0,0 +1,90 @@ +markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "foo" + */ + public function testPropertyFoo() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } +} diff --git a/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesTest.php b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesTest.php new file mode 100644 index 000000000000..72a390202c95 --- /dev/null +++ b/samples/client/petstore/php/nullable-object-property-php/test/Model/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesTest.php @@ -0,0 +1,99 @@ +markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "foo" + */ + public function testPropertyFoo() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } + + /** + * Test attribute "bar" + */ + public function testPropertyBar() + { + // TODO: implement + $this->markTestIncomplete('Not implemented'); + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/FILES b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/FILES index 9ff34cb31aa4..9b949e63056d 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/FILES +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/FILES @@ -2,6 +2,10 @@ apis/DefaultApi.ts apis/index.ts index.ts models/ModelWithNullableObjectProperty.ts +models/ModelWithNullableObjectPropertyNonNullableProperty.ts +models/ModelWithNullableObjectPropertyPropertyName30.ts +models/ModelWithNullableObjectPropertyPropertyName31.ts +models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.ts models/OtherPropertyType.ts models/PropertyType.ts models/index.ts diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/VERSION index 4077803655c0..89648de3311c 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/.openapi-generator/VERSION @@ -1 +1 @@ -5.3.1-SNAPSHOT \ No newline at end of file +6.0.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/apis/DefaultApi.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/apis/DefaultApi.ts index d2214a98c97b..bcb5a5eb820d 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/apis/DefaultApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/apis/DefaultApi.ts @@ -27,7 +27,7 @@ export class DefaultApi extends runtime.BaseAPI { /** */ - async operationRaw(initOverrides?: RequestInit): Promise> { + async operationRaw(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const queryParameters: any = {}; const headerParameters: runtime.HTTPHeaders = {}; @@ -44,7 +44,7 @@ export class DefaultApi extends runtime.BaseAPI { /** */ - async operation(initOverrides?: RequestInit): Promise { + async operation(initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { const response = await this.operationRaw(initOverrides); return await response.value(); } diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectProperty.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectProperty.ts index b7cfdf08bc8a..9e3482d88740 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectProperty.ts +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectProperty.ts @@ -14,11 +14,29 @@ import { exists, mapValues } from '../runtime'; import { - OtherPropertyType, - OtherPropertyTypeFromJSON, - OtherPropertyTypeFromJSONTyped, - OtherPropertyTypeToJSON, -} from './OtherPropertyType'; + ModelWithNullableObjectPropertyNonNullableProperty, + ModelWithNullableObjectPropertyNonNullablePropertyFromJSON, + ModelWithNullableObjectPropertyNonNullablePropertyFromJSONTyped, + ModelWithNullableObjectPropertyNonNullablePropertyToJSON, +} from './ModelWithNullableObjectPropertyNonNullableProperty'; +import { + ModelWithNullableObjectPropertyPropertyName30, + ModelWithNullableObjectPropertyPropertyName30FromJSON, + ModelWithNullableObjectPropertyPropertyName30FromJSONTyped, + ModelWithNullableObjectPropertyPropertyName30ToJSON, +} from './ModelWithNullableObjectPropertyPropertyName30'; +import { + ModelWithNullableObjectPropertyPropertyName31, + ModelWithNullableObjectPropertyPropertyName31FromJSON, + ModelWithNullableObjectPropertyPropertyName31FromJSONTyped, + ModelWithNullableObjectPropertyPropertyName31ToJSON, +} from './ModelWithNullableObjectPropertyPropertyName31'; +import { + ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes, + ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesFromJSON, + ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesFromJSONTyped, + ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesToJSON, +} from './ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes'; import { PropertyType, PropertyTypeFromJSON, @@ -40,28 +58,37 @@ export interface ModelWithNullableObjectProperty { propertyName?: PropertyType; /** * - * @type {PropertyType} + * @type {ModelWithNullableObjectPropertyPropertyName30} * @memberof ModelWithNullableObjectProperty */ - propertyName30?: PropertyType | null; + propertyName30?: ModelWithNullableObjectPropertyPropertyName30 | null; /** * - * @type {PropertyType} + * @type {ModelWithNullableObjectPropertyPropertyName31} * @memberof ModelWithNullableObjectProperty */ - propertyName31?: PropertyType | null; + propertyName31?: ModelWithNullableObjectPropertyPropertyName31; /** * - * @type {string | number} + * @type {ModelWithNullableObjectPropertyNonNullableProperty} * @memberof ModelWithNullableObjectProperty */ - nonNullableProperty?: string | number | null; + nonNullableProperty?: ModelWithNullableObjectPropertyNonNullableProperty; /** * - * @type {PropertyType | OtherPropertyType} + * @type {ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes} * @memberof ModelWithNullableObjectProperty */ - propertyWithNullAndTwoTypes?: PropertyType | OtherPropertyType | null; + propertyWithNullAndTwoTypes?: ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes; +} + +/** + * Check if a given object implements the ModelWithNullableObjectProperty interface. + */ +export function instanceOfModelWithNullableObjectProperty(value: object): boolean { + let isInstance = true; + + return isInstance; } export function ModelWithNullableObjectPropertyFromJSON(json: any): ModelWithNullableObjectProperty { @@ -75,10 +102,10 @@ export function ModelWithNullableObjectPropertyFromJSONTyped(json: any, ignoreDi return { 'propertyName': !exists(json, 'propertyName') ? undefined : PropertyTypeFromJSON(json['propertyName']), - 'propertyName30': !exists(json, 'propertyName30') ? undefined : PropertyTypeFromJSON(json['propertyName30']), - 'propertyName31': !exists(json, 'propertyName31') ? undefined : PropertyTypeFromJSON(json['propertyName31']), - 'nonNullableProperty': !exists(json, 'nonNullableProperty') ? undefined : string | numberFromJSON(json['nonNullableProperty']), - 'propertyWithNullAndTwoTypes': !exists(json, 'propertyWithNullAndTwoTypes') ? undefined : PropertyType | OtherPropertyTypeFromJSON(json['propertyWithNullAndTwoTypes']), + 'propertyName30': !exists(json, 'propertyName30') ? undefined : ModelWithNullableObjectPropertyPropertyName30FromJSON(json['propertyName30']), + 'propertyName31': !exists(json, 'propertyName31') ? undefined : ModelWithNullableObjectPropertyPropertyName31FromJSON(json['propertyName31']), + 'nonNullableProperty': !exists(json, 'nonNullableProperty') ? undefined : ModelWithNullableObjectPropertyNonNullablePropertyFromJSON(json['nonNullableProperty']), + 'propertyWithNullAndTwoTypes': !exists(json, 'propertyWithNullAndTwoTypes') ? undefined : ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesFromJSON(json['propertyWithNullAndTwoTypes']), }; } @@ -92,10 +119,10 @@ export function ModelWithNullableObjectPropertyToJSON(value?: ModelWithNullableO return { 'propertyName': PropertyTypeToJSON(value.propertyName), - 'propertyName30': PropertyTypeToJSON(value.propertyName30), - 'propertyName31': PropertyTypeToJSON(value.propertyName31), - 'nonNullableProperty': string | numberToJSON(value.nonNullableProperty), - 'propertyWithNullAndTwoTypes': PropertyType | OtherPropertyTypeToJSON(value.propertyWithNullAndTwoTypes), + 'propertyName30': ModelWithNullableObjectPropertyPropertyName30ToJSON(value.propertyName30), + 'propertyName31': ModelWithNullableObjectPropertyPropertyName31ToJSON(value.propertyName31), + 'nonNullableProperty': ModelWithNullableObjectPropertyNonNullablePropertyToJSON(value.nonNullableProperty), + 'propertyWithNullAndTwoTypes': ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesToJSON(value.propertyWithNullAndTwoTypes), }; } diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyNonNullableProperty.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyNonNullableProperty.ts new file mode 100644 index 000000000000..7ce073a9f4b1 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyNonNullableProperty.ts @@ -0,0 +1,50 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * @type ModelWithNullableObjectPropertyNonNullableProperty + * + * @export + */ +export type ModelWithNullableObjectPropertyNonNullableProperty = number | string; + +export function ModelWithNullableObjectPropertyNonNullablePropertyFromJSON(json: any): ModelWithNullableObjectPropertyNonNullableProperty { + return ModelWithNullableObjectPropertyNonNullablePropertyFromJSONTyped(json, false); +} + +export function ModelWithNullableObjectPropertyNonNullablePropertyFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelWithNullableObjectPropertyNonNullableProperty { + if ((json === undefined) || (json === null)) { + return json; + } + return { ...numberFromJSONTyped(json, true), ...stringFromJSONTyped(json, true) }; +} + +export function ModelWithNullableObjectPropertyNonNullablePropertyToJSON(value?: ModelWithNullableObjectPropertyNonNullableProperty | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + + if (instanceOfnumber(value)) { + return numberToJSON(value as number); + } + if (instanceOfstring(value)) { + return stringToJSON(value as string); + } + + return {}; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyName30.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyName30.ts new file mode 100644 index 000000000000..a34694d67ac7 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyName30.ts @@ -0,0 +1,55 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { + PropertyType, + instanceOfPropertyType, + PropertyTypeFromJSON, + PropertyTypeFromJSONTyped, + PropertyTypeToJSON, +} from './PropertyType'; + +/** + * @type ModelWithNullableObjectPropertyPropertyName30 + * + * @export + */ +export type ModelWithNullableObjectPropertyPropertyName30 = PropertyType; + +export function ModelWithNullableObjectPropertyPropertyName30FromJSON(json: any): ModelWithNullableObjectPropertyPropertyName30 { + return ModelWithNullableObjectPropertyPropertyName30FromJSONTyped(json, false); +} + +export function ModelWithNullableObjectPropertyPropertyName30FromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelWithNullableObjectPropertyPropertyName30 { + if ((json === undefined) || (json === null)) { + return json; + } + return { ...PropertyTypeFromJSONTyped(json, true) }; +} + +export function ModelWithNullableObjectPropertyPropertyName30ToJSON(value?: ModelWithNullableObjectPropertyPropertyName30 | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + + if (instanceOfPropertyType(value)) { + return PropertyTypeToJSON(value as PropertyType); + } + + return {}; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyName31.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyName31.ts new file mode 100644 index 000000000000..3a4f26d0e30f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyName31.ts @@ -0,0 +1,65 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { + Null, + instanceOfNull, + NullFromJSON, + NullFromJSONTyped, + NullToJSON, +} from './Null'; +import { + PropertyType, + instanceOfPropertyType, + PropertyTypeFromJSON, + PropertyTypeFromJSONTyped, + PropertyTypeToJSON, +} from './PropertyType'; + +/** + * @type ModelWithNullableObjectPropertyPropertyName31 + * + * @export + */ +export type ModelWithNullableObjectPropertyPropertyName31 = Null | PropertyType; + +export function ModelWithNullableObjectPropertyPropertyName31FromJSON(json: any): ModelWithNullableObjectPropertyPropertyName31 { + return ModelWithNullableObjectPropertyPropertyName31FromJSONTyped(json, false); +} + +export function ModelWithNullableObjectPropertyPropertyName31FromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelWithNullableObjectPropertyPropertyName31 { + if ((json === undefined) || (json === null)) { + return json; + } + return { ...NullFromJSONTyped(json, true), ...PropertyTypeFromJSONTyped(json, true) }; +} + +export function ModelWithNullableObjectPropertyPropertyName31ToJSON(value?: ModelWithNullableObjectPropertyPropertyName31 | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + + if (instanceOfNull(value)) { + return NullToJSON(value as Null); + } + if (instanceOfPropertyType(value)) { + return PropertyTypeToJSON(value as PropertyType); + } + + return {}; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.ts new file mode 100644 index 000000000000..69d954b5a9c0 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes.ts @@ -0,0 +1,75 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Title + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: latest + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +import { + Null, + instanceOfNull, + NullFromJSON, + NullFromJSONTyped, + NullToJSON, +} from './Null'; +import { + OtherPropertyType, + instanceOfOtherPropertyType, + OtherPropertyTypeFromJSON, + OtherPropertyTypeFromJSONTyped, + OtherPropertyTypeToJSON, +} from './OtherPropertyType'; +import { + PropertyType, + instanceOfPropertyType, + PropertyTypeFromJSON, + PropertyTypeFromJSONTyped, + PropertyTypeToJSON, +} from './PropertyType'; + +/** + * @type ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes + * + * @export + */ +export type ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes = Null | OtherPropertyType | PropertyType; + +export function ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesFromJSON(json: any): ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes { + return ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesFromJSONTyped(json, false); +} + +export function ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesFromJSONTyped(json: any, ignoreDiscriminator: boolean): ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes { + if ((json === undefined) || (json === null)) { + return json; + } + return { ...NullFromJSONTyped(json, true), ...OtherPropertyTypeFromJSONTyped(json, true), ...PropertyTypeFromJSONTyped(json, true) }; +} + +export function ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypesToJSON(value?: ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes | null): any { + if (value === undefined) { + return undefined; + } + if (value === null) { + return null; + } + + if (instanceOfNull(value)) { + return NullToJSON(value as Null); + } + if (instanceOfOtherPropertyType(value)) { + return OtherPropertyTypeToJSON(value as OtherPropertyType); + } + if (instanceOfPropertyType(value)) { + return PropertyTypeToJSON(value as PropertyType); + } + + return {}; +} + diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/OtherPropertyType.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/OtherPropertyType.ts index 3e18e6ea9667..758aa3f5d1a9 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/OtherPropertyType.ts +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/OtherPropertyType.ts @@ -27,6 +27,15 @@ export interface OtherPropertyType { bar?: string; } +/** + * Check if a given object implements the OtherPropertyType interface. + */ +export function instanceOfOtherPropertyType(value: object): boolean { + let isInstance = true; + + return isInstance; +} + export function OtherPropertyTypeFromJSON(json: any): OtherPropertyType { return OtherPropertyTypeFromJSONTyped(json, false); } diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/PropertyType.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/PropertyType.ts index 29ae4cf10f82..6b8af378205d 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/PropertyType.ts +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/PropertyType.ts @@ -27,6 +27,15 @@ export interface PropertyType { foo?: string; } +/** + * Check if a given object implements the PropertyType interface. + */ +export function instanceOfPropertyType(value: object): boolean { + let isInstance = true; + + return isInstance; +} + export function PropertyTypeFromJSON(json: any): PropertyType { return PropertyTypeFromJSONTyped(json, false); } diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/index.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/index.ts index b31809699bbe..ebab96f3b8af 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/index.ts +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/models/index.ts @@ -1,5 +1,9 @@ /* tslint:disable */ /* eslint-disable */ export * from './ModelWithNullableObjectProperty'; +export * from './ModelWithNullableObjectPropertyNonNullableProperty'; +export * from './ModelWithNullableObjectPropertyPropertyName30'; +export * from './ModelWithNullableObjectPropertyPropertyName31'; +export * from './ModelWithNullableObjectPropertyPropertyWithNullAndTwoTypes'; export * from './OtherPropertyType'; export * from './PropertyType'; diff --git a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/runtime.ts b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/runtime.ts index 940a39894aea..e77a4e0d0a03 100644 --- a/samples/client/petstore/typescript-fetch/builds/nullable-object-property/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/nullable-object-property/runtime.ts @@ -15,7 +15,76 @@ export const BASE_PATH = "http://localhost".replace(/\/+$/, ""); -const isBlob = (value: any) => typeof Blob !== 'undefined' && value instanceof Blob; +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | ((name: string) => string); // parameter for apiKey security + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + set config(configuration: Configuration) { + this.configuration = configuration; + } + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI | undefined { + return this.configuration.fetchApi; + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : async () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export const DefaultConfig = new Configuration(); /** * This is the base class for all generated API classes. @@ -24,7 +93,7 @@ export class BaseAPI { private middleware: Middleware[]; - constructor(protected configuration = new Configuration()) { + constructor(protected configuration = DefaultConfig) { this.middleware = configuration.middleware; } @@ -44,16 +113,16 @@ export class BaseAPI { return this.withMiddleware(...middlewares); } - protected async request(context: RequestOpts, initOverrides?: RequestInit): Promise { - const { url, init } = this.createFetchParams(context, initOverrides); + protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise { + const { url, init } = await this.createFetchParams(context, initOverrides); const response = await this.fetchApi(url, init); if (response.status >= 200 && response.status < 300) { return response; } - throw response; + throw new ResponseError(response, 'Response returned an error code'); } - private createFetchParams(context: RequestOpts, initOverrides?: RequestInit) { + private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) { let url = this.configuration.basePath + context.path; if (context.query !== undefined && Object.keys(context.query).length !== 0) { // only add the querystring to the URL if there are query parameters. @@ -61,18 +130,40 @@ export class BaseAPI { // do not handle correctly sometimes. url += '?' + this.configuration.queryParamsStringify(context.query); } - const body = ((typeof FormData !== "undefined" && context.body instanceof FormData) || context.body instanceof URLSearchParams || isBlob(context.body)) - ? context.body - : JSON.stringify(context.body); const headers = Object.assign({}, this.configuration.headers, context.headers); - const init = { + Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {}); + + const initOverrideFn = + typeof initOverrides === "function" + ? initOverrides + : async () => initOverrides; + + const initParams = { method: context.method, - headers: headers, - body, + headers, + body: context.body, credentials: this.configuration.credentials, - ...initOverrides }; + + const overridedInit: RequestInit = { + ...initParams, + ...(await initOverrideFn({ + init: initParams, + context, + })) + } + + const init: RequestInit = { + ...overridedInit, + body: + isFormData(overridedInit.body) || + overridedInit.body instanceof URLSearchParams || + isBlob(overridedInit.body) + ? overridedInit.body + : JSON.stringify(overridedInit.body), + }; + return { url, init }; } @@ -112,6 +203,21 @@ export class BaseAPI { } }; +function isBlob(value: any): value is Blob { + return typeof Blob !== 'undefined' && value instanceof Blob +} + +function isFormData(value: any): value is FormData { + return typeof FormData !== "undefined" && value instanceof FormData +} + +export class ResponseError extends Error { + name: "ResponseError" = "ResponseError"; + constructor(public response: Response, msg?: string) { + super(msg); + } +} + export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { @@ -126,80 +232,18 @@ export const COLLECTION_FORMATS = { pipes: "|", }; -export type FetchAPI = GlobalFetch['fetch']; - -export interface ConfigurationParameters { - basePath?: string; // override base path - fetchApi?: FetchAPI; // override for fetch implementation - middleware?: Middleware[]; // middleware to apply before/after fetch requests - queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings - username?: string; // parameter for basic security - password?: string; // parameter for basic security - apiKey?: string | ((name: string) => string); // parameter for apiKey security - accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string | Promise); // parameter for oauth2 security - headers?: HTTPHeaders; //header params we want to use on every request - credentials?: RequestCredentials; //value for the credentials param we want to use on each request -} - -export class Configuration { - constructor(private configuration: ConfigurationParameters = {}) {} - - get basePath(): string { - return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; - } - - get fetchApi(): FetchAPI | undefined { - return this.configuration.fetchApi; - } - - get middleware(): Middleware[] { - return this.configuration.middleware || []; - } - - get queryParamsStringify(): (params: HTTPQuery) => string { - return this.configuration.queryParamsStringify || querystring; - } - - get username(): string | undefined { - return this.configuration.username; - } - - get password(): string | undefined { - return this.configuration.password; - } - - get apiKey(): ((name: string) => string) | undefined { - const apiKey = this.configuration.apiKey; - if (apiKey) { - return typeof apiKey === 'function' ? apiKey : () => apiKey; - } - return undefined; - } - - get accessToken(): ((name?: string, scopes?: string[]) => string | Promise) | undefined { - const accessToken = this.configuration.accessToken; - if (accessToken) { - return typeof accessToken === 'function' ? accessToken : async () => accessToken; - } - return undefined; - } - - get headers(): HTTPHeaders | undefined { - return this.configuration.headers; - } - - get credentials(): RequestCredentials | undefined { - return this.configuration.credentials; - } -} +export type FetchAPI = WindowOrWorkerGlobalScope['fetch']; export type Json = any; export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; export type HTTPHeaders = { [key: string]: string }; -export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | HTTPQuery }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | Set | HTTPQuery }; export type HTTPBody = Json | FormData | URLSearchParams; +export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody } export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; +export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise + export interface FetchParams { url: string; init: RequestInit; @@ -220,26 +264,31 @@ export function exists(json: any, key: string) { export function querystring(params: HTTPQuery, prefix: string = ''): string { return Object.keys(params) - .map((key) => { - const fullKey = prefix + (prefix.length ? `[${key}]` : key); - const value = params[key]; - if (value instanceof Array) { - const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) - .join(`&${encodeURIComponent(fullKey)}=`); - return `${encodeURIComponent(fullKey)}=${multiValue}`; - } - if (value instanceof Date) { - return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; - } - if (value instanceof Object) { - return querystring(value as HTTPQuery, fullKey); - } - return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; - }) + .map(key => querystringSingleKey(key, params[key], prefix)) .filter(part => part.length > 0) .join('&'); } +function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array | Set | HTTPQuery, keyPrefix: string = ''): string { + const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key); + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Set) { + const valueAsArray = Array.from(value); + return querystringSingleKey(key, valueAsArray, keyPrefix); + } + if (value instanceof Date) { + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; +} + export function mapValues(data: any, fn: (item: any) => any) { return Object.keys(data).reduce( (acc, key) => ({ ...acc, [key]: fn(data[key]) }),