diff --git a/.github/workflows/samples-erlang.yaml b/.github/workflows/samples-erlang.yaml index c9e0981e49c4..95cda5dc5a3b 100644 --- a/.github/workflows/samples-erlang.yaml +++ b/.github/workflows/samples-erlang.yaml @@ -3,33 +3,33 @@ name: Samples Erlang on: push: paths: - # comment out due to errors - # ===> Compiling src/openapi_pet_handler.erl failed - # src/openapi_pet_handler.erl:278: function is_authorized/2 already defined - #- samples/server/petstore/erlang-server/** + - samples/server/echo_api/erlang-server/** + - samples/server/petstore/erlang-server/** - samples/client/petstore/erlang-client/** - samples/client/petstore/erlang-proper/** pull_request: paths: - #- samples/server/petstore/erlang-server/** + - samples/server/echo_api/erlang-server/** + - samples/server/petstore/erlang-server/** - samples/client/petstore/erlang-client/** - samples/client/petstore/erlang-proper/** jobs: build: name: Build Erlang projects - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: sample: - #- samples/server/petstore/erlang-server/ + - samples/server/echo_api/erlang-server/ + - samples/server/petstore/erlang-server/ - samples/client/petstore/erlang-client/ - samples/client/petstore/erlang-proper/ steps: - uses: actions/checkout@v4 - uses: erlef/setup-beam@v1 with: - otp-version: '22.2' - rebar3-version: '3.14.3' + otp-version: '27' + rebar3-version: '3.23.0' - run: rebar3 compile working-directory: ${{ matrix.sample }} diff --git a/.github/workflows/samples-go.yaml b/.github/workflows/samples-go.yaml index c1b8973ba067..26efd776d999 100644 --- a/.github/workflows/samples-go.yaml +++ b/.github/workflows/samples-go.yaml @@ -35,3 +35,27 @@ jobs: - name: Run test working-directory: ${{ matrix.sample }} run: go test -mod=mod -v + + verify: + name: Verify generated Go files with Go tests + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sample: + - samples/server/petstore/go-api-server/ + go-version: + - "1.18" + steps: + - uses: actions/checkout@v4 + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: ${{ matrix.go-version }} + - name: Install Dependencies + working-directory: ${{ matrix.sample }} + run: | + go mod tidy + - name: Run tests + working-directory: ${{ matrix.sample }} + run: go test ./samples_tests -v \ No newline at end of file diff --git a/README.md b/README.md index 42f6232b6c87..ddf8548b052a 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ If you find OpenAPI Generator useful for work, please consider asking your compa [](https://opensource.muenchen.de?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship) [](https://konghq.com/products/kong-konnect?utm_medium=referral&utm_source=github&utm_campaign=platform&utm_content=openapi-generator) [](https://route4me.com/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship) +[](https://www.dotcom-monitor.com/sponsoring-open-source-projects/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship) #### Thank you GoDaddy for sponsoring the domain names, Linode for sponsoring the VPS, Checkly for sponsoring the API monitoring and Gradle for sponsoring Develocity @@ -446,41 +447,7 @@ npm install @openapitools/openapi-generator-cli -D ``` -#### Use locally built JAR -In order to use a locally built jar of the generator CLI, you can copy the jar from your local build (i.e. if you were to `build` this repository it would be in `~/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar`) into `./node_modules/@openapitools/openapi-generator-cli/versions/` and change the `version` in the `openapitools.json` file to the base name of the jar file. -E.g.: -```sh -cd openapi-generator -./mvnw clean package -cp ./modules/openapi-generator-cli/target/openapi-generator-cli.jar /your/project/node_modules/@openapitools/openapi-generator-cli/versions/my-local-snapshot.jar -``` -and then: -```json -{ - "$schema": "./node_modules/@openapitools/openapi-generator-cli/config.schema.json", - "spaces": 2, - "generator-cli": { - "version": "my-local-snapshot", - } -} -``` - -#### Use nightly `SNAPSHOT` build -Change your `openapitools.json` to: - -```json -{ - "$schema": "node_modules/@openapitools/openapi-generator-cli/config.schema.json", - "spaces": 2, - "generator-cli": { - "version": "7.9.0-20240829.123431-22", - "repository": { - "downloadUrl": "https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.9.0-SNAPSHOT/openapi-generator-cli-${versionName}.jar" - } - } -} -``` -(example is with a snapshot of `7.9.0`, please change the `version` and `downloadUrl` accordingly) +You can use [locally built JARs](https://github.com/OpenAPITools/openapi-generator-cli?tab=readme-ov-file#use-locally-built-jar) or [`SNAPSHOT` versions](https://github.com/OpenAPITools/openapi-generator-cli?tab=readme-ov-file#use-nightly-snapshot-build) as well. ## [2 - Getting Started](#table-of-contents) @@ -1107,7 +1074,7 @@ Here is a list of template creators: * C++ (Qt5 QHttpEngine): @etherealjoy * C++ Pistache: @sebymiano * C++ Restbed: @stkrwork - * Erlang Server: @galaxie + * Erlang Server: @galaxie @nelsonvides * F# (Giraffe) Server: @nmfisher * Go Server: @guohuang * Go Server (refactored in 7.0.0): @lwj5 @@ -1218,7 +1185,7 @@ If you want to join the committee, please kindly apply by sending an email to te | Eiffel | @jvelilla (2017/09) | | Elixir | @mrmstn (2018/12) | | Elm | @eriktim (2018/09) | -| Erlang | @tsloughter (2017/11) @jfacorro (2018/10) @robertoaloi (2018/10) | +| Erlang | @tsloughter (2017/11) @jfacorro (2018/10) @robertoaloi (2018/10) @nelsonvides (2024/09) | | F# | @nmfisher (2019/05) | | Go | @antihax (2017/11) @grokify (2018/07) @kemokemo (2018/09) @jirikuncar (2021/01) @ph4r5h4d (2021/04) @lwj5 (2023/04) | | GraphQL | @renepardon (2018/12) | diff --git a/bin/configs/avro-schema-enums.yaml b/bin/configs/avro-schema-enums.yaml new file mode 100644 index 000000000000..32afa02e8c9d --- /dev/null +++ b/bin/configs/avro-schema-enums.yaml @@ -0,0 +1,4 @@ +generatorName: avro-schema +outputDir: samples/openapi3/schema/valid-enums/avro-schema-enum +inputSpec: modules/openapi-generator/src/test/resources/3_0/avro-schema/valid-enums.yaml +templateDir: modules/openapi-generator/src/main/resources/avro-schema diff --git a/bin/configs/erlang-server-echo.yaml b/bin/configs/erlang-server-echo.yaml new file mode 100644 index 000000000000..7ed821f1c3b1 --- /dev/null +++ b/bin/configs/erlang-server-echo.yaml @@ -0,0 +1,4 @@ +generatorName: erlang-server +outputDir: samples/server/echo_api/erlang-server +inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +templateDir: modules/openapi-generator/src/main/resources/erlang-server diff --git a/docs/debugging.md b/docs/debugging.md index bdf7e992c6e0..76ad96de1867 100644 --- a/docs/debugging.md +++ b/docs/debugging.md @@ -201,6 +201,23 @@ The steps are shown here for a specific version of the generator, but apply the ``` * Set breakpoints in code, and then attach your remote debugger from your IDE (see above). The generator will automatically unblock once the remote debugger is attached. You can now step through the code. + For VSCode you can use the following launch configuration (`launch.json`): + ```json + { + "version": "0.2.0", + "configurations": [ + { + "type": "java", + "name": "Debug (Attach)", + "request": "attach", + "hostName": "localhost", + "port": 5005 + } + ] + } + ``` + to attach the the suspended process above. + ## Logs You can try to enable debugging log with `-Dlog.level=debug` option to the `JAVA_OPTS` environment variable to see more information: diff --git a/docs/generators.md b/docs/generators.md index 1fe95d2ad933..6cf92be19458 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -89,6 +89,7 @@ The following generators are available: * [cpp-restbed-server-deprecated](generators/cpp-restbed-server-deprecated.md) * [csharp-functions](generators/csharp-functions.md) * [erlang-server](generators/erlang-server.md) +* [erlang-server-deprecated (deprecated)](generators/erlang-server-deprecated.md) * [fsharp-functions (beta)](generators/fsharp-functions.md) * [fsharp-giraffe-server (beta)](generators/fsharp-giraffe-server.md) * [go-echo-server (beta)](generators/go-echo-server.md) diff --git a/docs/generators/erlang-server-deprecated.md b/docs/generators/erlang-server-deprecated.md new file mode 100644 index 000000000000..b3f96ea6158c --- /dev/null +++ b/docs/generators/erlang-server-deprecated.md @@ -0,0 +1,190 @@ +--- +title: Documentation for the erlang-server-deprecated Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | erlang-server-deprecated | pass this to the generate command after -g | +| generator stability | DEPRECATED | | +| generator type | SERVER | | +| generator language | Erlang | | +| generator default templating engine | mustache | | +| helpTxt | Generates an Erlang server library (deprecated) using OpenAPI Generator (https://openapi-generator.tech). By default, it will also generate service classes, which can be disabled with the `-Dnoservice` environment variable. | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|openAPISpecName|Openapi Spec Name.| |openapi| +|packageName|Erlang package name (convention: lowercase).| |openapi| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✗|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 +|SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✗|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/docs/generators/erlang-server.md b/docs/generators/erlang-server.md index 66692f029e7d..824149119699 100644 --- a/docs/generators/erlang-server.md +++ b/docs/generators/erlang-server.md @@ -59,6 +59,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • fun
  • if
  • let
  • +
  • maybe
  • not
  • of
  • or
  • diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index 060b0d2c6260..05f6c4cbab04 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -25,6 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |collectionType|Option. Collection type to use|
    **array**
    kotlin.Array
    **list**
    kotlin.collections.List
    |list| |dateLibrary|Option. Date library to use|
    **threetenbp-localdatetime**
    Threetenbp - Backport of JSR310 (jvm only, for legacy app only)
    **kotlinx-datetime**
    kotlinx-datetime (preferred for multiplatform)
    **string**
    String
    **java8-localdatetime**
    Java 8 native JSR310 (jvm only, for legacy app only)
    **java8**
    Java 8 native JSR310 (jvm only, preferred for jdk 1.8+)
    **threetenbp**
    Threetenbp - Backport of JSR310 (jvm only, preferred for jdk < 1.8)
    |java8| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |original| +|failOnUnknownProperties|Fail Jackson de-serialization on unknown properties| |false| |generateOneOfAnyOfWrappers|Generate oneOf, anyOf schemas as wrappers.| |false| |generateRoomModels|Generate Android Room database models in addition to API models (JVM Volley library only)| |false| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java index 1c25a69f5dd3..27cd5b4ab0bd 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java @@ -256,6 +256,10 @@ public interface CodegenConfig { void setSkipOperationExample(boolean skipOperationExample); + boolean isSkipSortingOperations(); + + void setSkipSortingOperations(boolean skipSortingOperations); + public boolean isHideGenerationTimestamp(); public void setHideGenerationTimestamp(boolean hideGenerationTimestamp); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 6e252298d08a..dbd6ee46d960 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -224,6 +224,8 @@ apiTemplateFiles are for API outputs only (controllers/handlers). @Getter @Setter protected int removeOperationIdPrefixCount = 1; protected boolean skipOperationExample; + // sort operations by default + protected boolean skipSortingOperations = false; protected final static Pattern XML_MIME_PATTERN = Pattern.compile("(?i)application\\/(.*)[+]?xml(;.*)?"); protected final static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?"); @@ -6154,6 +6156,16 @@ public void setSkipOperationExample(boolean skipOperationExample) { this.skipOperationExample = skipOperationExample; } + @Override + public boolean isSkipSortingOperations() { + return this.skipSortingOperations; + } + + @Override + public void setSkipSortingOperations(boolean skipSortingOperations) { + this.skipSortingOperations = skipSortingOperations; + } + @Override public boolean isHideGenerationTimestamp() { return hideGenerationTimestamp; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index c5d220012155..04e7d06df3c2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -121,6 +121,7 @@ public Generator opts(ClientOptInput opts) { this.opts = opts; this.openAPI = opts.getOpenAPI(); this.config = opts.getConfig(); + List userFiles = opts.getUserDefinedTemplates(); if (userFiles != null) { this.userDefinedTemplates = Collections.unmodifiableList(userFiles); @@ -680,7 +681,10 @@ void generateApis(List files, List allOperations, List ops = paths.get(tag); - ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId)); + if(!this.config.isSkipSortingOperations()) { + // sort operations by operationId + ops.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId)); + } OperationsMap operation = processOperations(config, tag, ops, allModels); URL url = URLPathUtils.getServerURL(openAPI, config.serverVariableOverrides()); operation.put("basePath", basePath); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java index af33ba1f36a7..40d986a66504 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java @@ -684,6 +684,28 @@ public void setParameterExampleValue(CodegenParameter p) { p.example = example; } + @Override + protected void updateEnumVarsWithExtensions(List> enumVars, Map vendorExtensions, String dataType) { + if (vendorExtensions != null) { + if (vendorExtensions.containsKey("x-enum-varnames")) { + List values = (List) vendorExtensions.get("x-enum-varnames"); + int size = Math.min(enumVars.size(), values.size()); + + for (int i = 0; i < size; i++) { + enumVars.get(i).put("name", toEnumVarName(values.get(i), dataType)); + } + } + + if (vendorExtensions.containsKey("x-enum-descriptions")) { + List values = (List) vendorExtensions.get("x-enum-descriptions"); + int size = Math.min(enumVars.size(), values.size()); + for (int i = 0; i < size; i++) { + enumVars.get(i).put("enumDescription", values.get(i)); + } + } + } + } + @Override public String toEnumValue(String value, String datatype) { if ("int".equals(datatype) || "float".equals(datatype)) { @@ -704,11 +726,11 @@ public String toEnumVarName(String name, String datatype) { return enumNameMapping.get(name); } - if (name.length() == 0) { + if (name.isEmpty()) { return "EMPTY"; } - if (name.trim().length() == 0) { + if (name.trim().isEmpty()) { return "SPACE_" + name.length(); } @@ -719,11 +741,12 @@ public String toEnumVarName(String name, String datatype) { // number if ("int".equals(datatype) || "float".equals(datatype)) { - String varName = name; - varName = varName.replaceAll("-", "MINUS_"); - varName = varName.replaceAll("\\+", "PLUS_"); - varName = varName.replaceAll("\\.", "_DOT_"); - return varName; + if (name.matches("\\d.*")) { // starts with number + name = "NUMBER_" + name; + } + name = name.replaceAll("-", "MINUS_"); + name = name.replaceAll("\\+", "PLUS_"); + name = name.replaceAll("\\.", "_DOT_"); } // string diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java index 8918cd88fe06..69bcb447628d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java @@ -25,12 +25,20 @@ import java.io.File; import java.util.Arrays; +import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import static org.openapitools.codegen.utils.StringUtils.camelize; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class AvroSchemaCodegen extends DefaultCodegen implements CodegenConfig { + private final Logger LOGGER = LoggerFactory.getLogger(AvroSchemaCodegen.class); private static final String AVRO = "avro-schema"; protected String packageName = "model"; @@ -148,4 +156,44 @@ public String escapeQuotationMark(String input) { return input; } + @Override + protected List> buildEnumVars(List values, String dataType) { + List sanitizedValues = values.stream().map(Object::toString).map(this::sanitizeEnumValue) + .collect(Collectors.toList()); + removeEnumValueCollisions(sanitizedValues); + return super.buildEnumVars(sanitizedValues, dataType); + } + + /** + * Valid enums in Avro need to adhere to [A-Za-z_][A-Za-z0-9_]* + * See https://avro.apache.org/docs/1.12.0/specification/#enums + */ + private String sanitizeEnumValue(String value) { + // Replace any non-alphanumeric characters with an underscore + String sanitizedValue = value.replaceAll("[^A-Za-z0-9_]", "_"); + // If the enum starts with a number, prefix it with an underscore + sanitizedValue = sanitizedValue.replaceAll("^([0-9])", "_$1"); + return sanitizedValue; + } + + private void removeEnumValueCollisions(List values) { + Collections.reverse(values); + for (int i = 0; i < values.size(); i++) { + final String value = values.get(i).toString(); + long count = values.stream().filter(v1 -> v1.equals(value)).count(); + if (count > 1) { + String uniqueEnumValue = getUniqueEnumValue(value.toString(), values); + LOGGER.debug("Changing duplicate enumeration value from " + value + " to " + uniqueEnumValue); + values.set(i, uniqueEnumValue); + } + } + Collections.reverse(values); + } + + private String getUniqueEnumValue(String value, List values) { + long count = values.stream().filter(v -> v.equals(value)).count(); + return count > 1 + ? getUniqueEnumValue(value + count, values) + : value; + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java index d41136eb6761..5f8a50a312b0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java @@ -99,9 +99,9 @@ public ErlangServerCodegen() { */ setReservedWordsLowerCase( Arrays.asList( - "after", "and", "andalso", "band", "begin", "bnot", "bor", "bsl", "bsr", "bxor", "case", - "catch", "cond", "div", "end", "fun", "if", "let", "not", "of", "or", "orelse", "receive", - "rem", "try", "when", "xor" + "after", "and", "andalso", "band", "begin", "bnot", "bor", "bsl", "bsr", "bxor", + "case", "catch", "cond", "div", "end", "fun", "if", "let", "maybe", "not", + "of", "or", "orelse", "receive", "rem", "try", "when", "xor" ) ); @@ -172,10 +172,8 @@ public void processOpts() { supportingFiles.add(new SupportingFile("router.mustache", "", toSourceFilePath("router", "erl"))); supportingFiles.add(new SupportingFile("api.mustache", "", toSourceFilePath("api", "erl"))); supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", "erl"))); - supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", "erl"))); supportingFiles.add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl"))); supportingFiles.add(new SupportingFile("openapi.mustache", "", toPrivFilePath(this.openApiSpecName, "json"))); - supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", toSourceFilePath("default_logic_handler", "erl"))); supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath("logic_handler", "erl"))); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md") .doNotOverwrite()); @@ -223,7 +221,7 @@ public String getHelp() { @Override public String toApiName(String name) { if (name.length() == 0) { - return this.packageName + "_default_handler"; + return this.packageName + "_handler"; } return this.packageName + "_" + underscore(name) + "_handler"; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerDeprecatedCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerDeprecatedCodegen.java new file mode 100644 index 000000000000..650951028ccf --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerDeprecatedCodegen.java @@ -0,0 +1,337 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import lombok.Setter; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; + +import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; + +public class ErlangServerDeprecatedCodegen extends DefaultCodegen implements CodegenConfig { + + private final Logger LOGGER = LoggerFactory.getLogger(ErlangServerDeprecatedCodegen.class); + + protected String apiVersion = "1.0.0"; + protected String apiPath = "src"; + @Setter protected String packageName = "openapi"; + @Setter protected String openApiSpecName = "openapi"; + + public ErlangServerDeprecatedCodegen() { + super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata).stability(Stability.DEPRECATED).build(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) + .securityFeatures(EnumSet.of( + SecurityFeature.ApiKey, + SecurityFeature.OAuth2_Implicit + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + + // set the output folder here + outputFolder = "generated-code/erlang-server"; + + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.clear(); + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "handler.mustache", // the template to use + ".erl"); // the extension for each file to write + + /** + * Template Location. This is the location which templates will be read from. The generator + * will use the resource stream to attempt to read the templates. + */ + embeddedTemplateDir = templateDir = "erlang-server-deprecated"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + setReservedWordsLowerCase( + Arrays.asList( + "after", "and", "andalso", "band", "begin", "bnot", "bor", "bsl", "bsr", "bxor", "case", + "catch", "cond", "div", "end", "fun", "if", "let", "not", "of", "or", "orelse", "receive", + "rem", "try", "when", "xor" + ) + ); + + instantiationTypes.clear(); + + typeMapping.clear(); + typeMapping.put("enum", "binary"); + typeMapping.put("date", "date"); + typeMapping.put("datetime", "datetime"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "binary"); + typeMapping.put("integer", "integer"); + typeMapping.put("int", "integer"); + typeMapping.put("float", "integer"); + typeMapping.put("long", "integer"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "map"); + typeMapping.put("number", "integer"); + typeMapping.put("bigdecimal", "float"); + typeMapping.put("List", "list"); + typeMapping.put("object", "object"); + typeMapping.put("file", "file"); + typeMapping.put("binary", "binary"); + typeMapping.put("bytearray", "binary"); + typeMapping.put("byte", "binary"); + typeMapping.put("uuid", "binary"); + typeMapping.put("uri", "binary"); + typeMapping.put("password", "binary"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Erlang package name (convention: lowercase).") + .defaultValue(this.packageName)); + + cliOptions.add(new CliOption(CodegenConstants.OPEN_API_SPEC_NAME, "Openapi Spec Name.") + .defaultValue(this.openApiSpecName)); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + } + + if (additionalProperties.containsKey(CodegenConstants.OPEN_API_SPEC_NAME)) { + setOpenApiSpecName((String) additionalProperties.get(CodegenConstants.OPEN_API_SPEC_NAME)); + } else { + additionalProperties.put(CodegenConstants.OPEN_API_SPEC_NAME, openApiSpecName); + } + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("apiPath", apiPath); + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("rebar.config.mustache", "", "rebar.config")); + supportingFiles.add(new SupportingFile("app.src.mustache", "", "src" + File.separator + this.packageName + ".app.src")); + supportingFiles.add(new SupportingFile("router.mustache", "", toSourceFilePath("router", "erl"))); + supportingFiles.add(new SupportingFile("api.mustache", "", toSourceFilePath("api", "erl"))); + supportingFiles.add(new SupportingFile("server.mustache", "", toSourceFilePath("server", "erl"))); + supportingFiles.add(new SupportingFile("utils.mustache", "", toSourceFilePath("utils", "erl"))); + supportingFiles.add(new SupportingFile("auth.mustache", "", toSourceFilePath("auth", "erl"))); + supportingFiles.add(new SupportingFile("openapi.mustache", "", toPrivFilePath(this.openApiSpecName, "json"))); + supportingFiles.add(new SupportingFile("default_logic_handler.mustache", "", toSourceFilePath("default_logic_handler", "erl"))); + supportingFiles.add(new SupportingFile("logic_handler.mustache", "", toSourceFilePath("logic_handler", "erl"))); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md") + .doNotOverwrite()); + } + + @Override + public String apiPackage() { + return apiPath; + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see org.openapitools.codegen.CodegenType + */ + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + /** + * Configures a friendly name for the generator. This will be used by the generator + * to select the library with the -g flag. + * + * @return the friendly name for the generator + */ + @Override + public String getName() { + return "erlang-server-deprecated"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + @Override + public String getHelp() { + return "Generates an Erlang server library (deprecated) using OpenAPI Generator (https://openapi-generator.tech). By default, " + + "it will also generate service classes, which can be disabled with the `-Dnoservice` environment variable."; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return this.packageName + "_default_handler"; + } + return this.packageName + "_" + underscore(name) + "_handler"; + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reserved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String toModelName(String name) { + return camelize(toModelFilename(name)); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(operationId)) { + LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, camelize(sanitizeName("call_" + operationId))); + operationId = "call_" + operationId; + } + + return camelize(operationId); + } + + @Override + public String toApiFilename(String name) { + return toHandlerName(name); + } + + @Override + public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + OperationMap operations = objs.getOperations(); + List operationList = operations.getOperation(); + for (CodegenOperation op : operationList) { + if (op.path != null) { + op.path = op.path.replaceAll("\\{(.*?)\\}", ":$1"); + } + } + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + generateJSONSpecFile(objs); + return super.postProcessSupportingFileData(objs); + } + + protected String toHandlerName(String name) { + return toModuleName(name) + "_handler"; + } + + protected String toModuleName(String name) { + return this.packageName + "_" + underscore(name.replaceAll("-", "_")); + } + + protected String toSourceFilePath(String name, String extension) { + return "src" + File.separator + toModuleName(name) + "." + extension; + } + + protected String toIncludeFilePath(String name, String extension) { + return "include" + File.separator + toModuleName(name) + "." + extension; + } + + protected String toPrivFilePath(String name, String extension) { + return "priv" + File.separator + name + "." + extension; + } + + @Override + public String escapeQuotationMark(String input) { + // remove ' to avoid code injection + return input.replace("'", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + // ref: http://stackoverflow.com/a/30421295/677735 + return input.replace("-ifdef", "- if def").replace("-endif", "- end if"); + } + + @Override + public String addRegularExpressionDelimiter(String pattern) { + return pattern; + } + + @Override + public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.ERLANG; } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java index d38c62e5b2b5..1e8012916759 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java @@ -66,6 +66,9 @@ public class GoServerCodegen extends AbstractGoCodegen { public GoServerCodegen() { super(); + // skip sorting of operations to preserve the order found in the OpenAPI spec file + super.setSkipSortingOperations(true); + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index 6984956674a4..f6b48c7563b3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -85,6 +85,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { public static final String DATE_LIBRARY = "dateLibrary"; public static final String REQUEST_DATE_CONVERTER = "requestDateConverter"; public static final String COLLECTION_TYPE = "collectionType"; + public static final String FAIL_ON_UNKNOWN_PROPERTIES = "failOnUnknownProperties"; public static final String MOSHI_CODE_GEN = "moshiCodeGen"; @@ -108,6 +109,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { @Setter protected String roomModelPackage = ""; @Setter protected boolean omitGradleWrapper = false; @Setter protected boolean generateOneOfAnyOfWrappers = true; + @Getter @Setter protected boolean failOnUnknownProperties = false; protected String authFolder; @@ -259,6 +261,7 @@ public KotlinClientCodegen() { cliOptions.add(CliOption.newBoolean(IDEA, "Add IntellJ Idea plugin and mark Kotlin main and test folders as source folders.")); cliOptions.add(CliOption.newBoolean(MOSHI_CODE_GEN, "Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.")); + cliOptions.add(CliOption.newBoolean(FAIL_ON_UNKNOWN_PROPERTIES, "Fail Jackson de-serialization on unknown properties", false)); cliOptions.add(CliOption.newBoolean(NULLABLE_RETURN_TYPE, "Nullable return type")); @@ -438,6 +441,13 @@ public void processOpts() { setGenerateOneOfAnyOfWrappers(Boolean.parseBoolean(additionalProperties.get(GENERATE_ONEOF_ANYOF_WRAPPERS).toString())); } + if (additionalProperties.containsKey(FAIL_ON_UNKNOWN_PROPERTIES)) { + setFailOnUnknownProperties(Boolean.parseBoolean(additionalProperties.get(FAIL_ON_UNKNOWN_PROPERTIES).toString())); + } else { + additionalProperties.put(FAIL_ON_UNKNOWN_PROPERTIES, false); + setFailOnUnknownProperties(false); + } + commonSupportingFiles(); switch (getLibrary()) { @@ -583,12 +593,15 @@ private void processKotlinxDate() { typeMapping.put("date-time", "Instant"); typeMapping.put("date", "LocalDate"); + typeMapping.put("time", "LocalTime"); typeMapping.put("DateTime", "Instant"); typeMapping.put("Date", "LocalDate"); + typeMapping.put("Time", "LocalTime"); importMapping.put("Instant", "kotlinx.datetime.Instant"); importMapping.put("LocalDate", "kotlinx.datetime.LocalDate"); + importMapping.put("LocalTime", "kotlinx.datetime.LocalTime"); } private void processJVMRetrofit2Library(String infrastructureFolder) { @@ -654,7 +667,7 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder) supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); - addKotlinxDateTimeInstantAdapter(infrastructureFolder); + addKotlinxDateTimeAdapters(infrastructureFolder); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigDecimalAdapter.kt.mustache", infrastructureFolder, "BigDecimalAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigIntegerAdapter.kt.mustache", infrastructureFolder, "BigIntegerAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/URIAdapter.kt.mustache", infrastructureFolder, "URIAdapter.kt")); @@ -665,7 +678,7 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder) supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); - addKotlinxDateTimeInstantAdapter(infrastructureFolder); + addKotlinxDateTimeAdapters(infrastructureFolder); break; case jackson: @@ -689,9 +702,10 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder) } } - private void addKotlinxDateTimeInstantAdapter(final String infrastructureFolder) { + private void addKotlinxDateTimeAdapters(final String infrastructureFolder) { if (DateLibrary.KOTLINX_DATETIME.value.equals(dateLibrary)) { supportingFiles.add(new SupportingFile("jvm-common/infrastructure/InstantAdapter.kt.mustache", infrastructureFolder, "InstantAdapter.kt")); + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalTimeAdapter.kt.mustache", infrastructureFolder, "LocalTimeAdapter.kt")); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java index 59e191e75d13..9befedd4a485 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java @@ -374,22 +374,4 @@ public String toDefaultValue(Schema p) { public String toEnumDefaultValue(String value, String datatype) { return datatype + "::" + value; } - - @Override - public String toEnumVarName(String value, String datatype) { - if (value.length() == 0) { - return super.toEnumVarName(value, datatype); - } - - // number - if ("int".equals(datatype) || "float".equals(datatype)) { - String varName = "NUMBER_" + value; - varName = varName.replaceAll("-", "MINUS_"); - varName = varName.replaceAll("\\+", "PLUS_"); - varName = varName.replaceAll("\\.", "_DOT_"); - return varName; - } - - return super.toEnumVarName(value, datatype); - } } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/api.mustache index eecc6da74b20..cfcd9f04ce6b 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/api.mustache @@ -99,7 +99,7 @@ public class {{classname}} extends BaseApi { {{/required}}{{/allParams}} // create path and map variables String localVarPath = "{{{path}}}"{{#pathParams}} - .replaceAll("\\{" + "{{baseName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + .replaceAll("\\{" + "{{baseName}}" + "\\}", apiClient.escapeString(apiClient.parameterToString({{{paramName}}}))){{/pathParams}}; StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index f85a602f1c30..c222c57c6ba8 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -1356,7 +1356,11 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache index e8fb7b6bde03..f83bccd77049 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache @@ -1356,7 +1356,11 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom-sb3.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom-sb3.mustache index cc5a1e1632e0..1024ea0d6088 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom-sb3.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/pom-sb3.mustache @@ -11,18 +11,18 @@ ${java.version} UTF-8 {{#springDocDocumentationProvider}} - 2.2.0 + 2.6.0 {{/springDocDocumentationProvider}} {{^springDocDocumentationProvider}} {{#swagger2AnnotationLibrary}} - 2.2.15 + 2.2.22 {{/swagger2AnnotationLibrary}} {{/springDocDocumentationProvider}} {{#useSwaggerUI}} - 5.3.1 + 5.17.14 {{/useSwaggerUI}} {{#virtualService}} - 2.5.2 + 2.5.5 {{/virtualService}} {{#parentOverridden}} diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index ba2d139af981..00a51f289abe 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -30,6 +30,7 @@ org.openapitools.codegen.languages.ElmClientCodegen org.openapitools.codegen.languages.ErlangClientCodegen org.openapitools.codegen.languages.ErlangProperCodegen org.openapitools.codegen.languages.ErlangServerCodegen +org.openapitools.codegen.languages.ErlangServerDeprecatedCodegen org.openapitools.codegen.languages.FsharpFunctionsServerCodegen org.openapitools.codegen.languages.FsharpGiraffeServerCodegen org.openapitools.codegen.languages.GoClientCodegen diff --git a/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache index 28dddcc4cd98..5769512aa877 100644 --- a/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache @@ -39,10 +39,10 @@ {{#supportsRetry}} - + {{/supportsRetry}} {{#net80OrLater}} - + {{/net80OrLater}} {{^net60OrLater}} diff --git a/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache b/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache index 90d11eb8256b..eb8bd548d1e0 100644 --- a/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache @@ -9,9 +9,9 @@ - - - + + + diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/class.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/class.mustache index a670c63e880f..88a25b71783f 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/class.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/class.mustache @@ -46,7 +46,12 @@ class {{{classname}}} { {{#defaultValue}}defaultValue: {{{defaultValue}}},{{/defaultValue}} name: r'{{{baseName}}}', required: {{#required}}true{{/required}}{{^required}}false{{/required}}, - includeIfNull: {{#required}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/required}}{{^required}}false{{/required}} + includeIfNull: {{#required}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/required}}{{^required}}false{{/required}}, + {{#isEnumOrRef}} + {{#enumUnknownDefaultCase}} + unknownEnumValue: {{{datatypeWithEnum}}}.unknownDefaultOpenApi, + {{/enumUnknownDefaultCase}} + {{/isEnumOrRef}} ) {{/isBinary}} {{#isBinary}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/deserialize.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/deserialize.mustache index edb8887328cd..da750aa02b14 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/deserialize.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/deserialize.mustache @@ -52,13 +52,13 @@ final _regMap = RegExp(r'^Map$'); .toSet() as ReturnType; } if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - targetType = match![1]!; // ignore: parameter_assignments - return Map.fromIterables( - value.keys, + targetType = match![1]!.trim(); // ignore: parameter_assignments + return Map.fromIterables( + value.keys as Iterable, value.values.map((dynamic v) => deserialize(v, targetType, growable: growable)), ) as ReturnType; } break; - } + } throw Exception('Cannot deserialize'); } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum_inline.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum_inline.mustache index 53cd77098740..3b441c237c90 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum_inline.mustache @@ -6,9 +6,21 @@ enum {{{ enumName }}} { {{#allowableValues}} {{#enumVars}} - @JsonValue({{#isString}}r{{/isString}}{{{value}}}) - {{{name}}}, +{{^isNull}} +{{#description}} + /// {{{.}}} +{{/description}} +@JsonValue({{#isString}}r{{/isString}}{{{value}}}) +{{{name}}}({{^isString}}'{{/isString}}{{#isString}}r{{/isString}}{{{value}}}{{^isString}}'{{/isString}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} +{{/isNull}} {{/enumVars}} {{/allowableValues}} + +const {{{enumName}}}(this.value); + +final String value; + +@override +String toString() => value; } {{/enumName}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/README.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/README.mustache new file mode 100644 index 000000000000..5d36ca07576b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/README.mustache @@ -0,0 +1,57 @@ +# OpenAPI server library for Erlang + +## Overview + +An Erlang server stub generated by [OpenAPI Generator](https://openapi-generator.tech) given an OpenAPI spec. + +Dependency: [Cowboy](https://github.com/ninenines/cowboy) + +## Prerequisites + +TODO + +## Getting started +Use erlang-server with erlang.mk + + 1, Create an application by using erlang.mk + $ mkdir http_server + $ cd http_server + $ wget https://erlang.mk/erlang.mk + $ make -f erlang.mk bootstrap bootstrap-rel + $ make run + + 2, Modify the Makefile in the http_server directory to the following to introduce the dependency library: + PROJECT = http_server + PROJECT_DESCRIPTION = New project + PROJECT_VERSION = 0.1.0 + + DEPS = cowboy jesse jsx + dep_cowboy_commit = 2.5.0 + dep_jesse_commit = 1.5.2 + dep_jsx_commit = 2.9.0 + DEP_PLUGINS = cowboy jesse jsx + + PACKAGES += rfc3339 + pkg_rfc3339_name = rfc3339 + pkg_rfc3339_description = an erlang/elixir rfc3339 lib + pkg_rfc3339_homepage = https://github.com/talentdeficit/rfc3339 + pkg_rfc3339_fetch = git + pkg_rfc3339_repo = https://github.com/talentdeficit/rfc3339 + pkg_rfc3339_commit = master + + include erlang.mk + + 3, Generate erlang-server project using openapi-generator + https://github.com/OpenAPITools/openapi-generator#2---getting-started + + 4, Copy erlang-server file to http_server project,Don't forget the 'priv' folder. + + 5, Start in the http_server project: + 1, Introduce the following line in the http_server_app:start(_Type, _Args) function + openapi_server:start(http_server, #{ip=>{127,0,0,1}, port=>8080, net_opts=>[]}) + 2, Compilation http_server project + $ make + 3, Start erlang virtual machine + $erl -pa ./deps/cowboy/ebin -pa ./deps/cowlib/ebin -pa ./deps/ranch/ebin -pa ./deps/jsx/ebin -pa ./deps/jesse/ebin -pa ./deps/rfc3339/ebin -pa ./ebin + 4, Start project + application:ensure_all_started(http_server). diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/api.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/api.mustache new file mode 100644 index 000000000000..b97e4a2c5eca --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/api.mustache @@ -0,0 +1,363 @@ +-module({{packageName}}_api). + +-export([request_params/1]). +-export([request_param_info/2]). +-export([populate_request/3]). +-export([validate_response/4]). +%% exported to silence openapi complains +-export([get_value/3, validate_response_body/4]). + +-type operation_id() :: atom(). +-type request_param() :: atom(). + +-export_type([operation_id/0]). + +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}} +request_params('{{operationId}}') -> + [{{#allParams}}{{^isBodyParam}} + '{{baseName}}'{{/isBodyParam}}{{#isBodyParam}} + '{{dataType}}'{{/isBodyParam}}{{^-last}},{{/-last}}{{/allParams}} + ]; +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +request_params(_) -> + error(unknown_operation). + +-type rule() :: + {type, 'binary'} | + {type, 'integer'} | + {type, 'float'} | + {type, 'binary'} | + {type, 'boolean'} | + {type, 'date'} | + {type, 'datetime'} | + {enum, [atom()]} | + {max, Max :: number()} | + {exclusive_max, Max :: number()} | + {min, Min :: number()} | + {exclusive_min, Min :: number()} | + {max_length, MaxLength :: integer()} | + {min_length, MaxLength :: integer()} | + {pattern, Pattern :: string()} | + schema | + required | + not_required. + +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> #{ + source => qs_val | binding | header | body, + rules => [rule()] +}. + +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}}{{#allParams}} +request_param_info('{{operationId}}', {{^isBodyParam}}'{{baseName}}'{{/isBodyParam}}{{#isBodyParam}}'{{dataType}}'{{/isBodyParam}}) -> + #{ + source => {{#isQueryParam}}qs_val{{/isQueryParam}} {{#isPathParam}}binding{{/isPathParam}} {{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}{{#isFormParam}}body{{/isFormParam}}, + rules => [{{#isString}} + {type, 'binary'},{{/isString}}{{#isInteger}} + {type, 'integer'},{{/isInteger}}{{#isLong}} + {type, 'integer'},{{/isLong}}{{#isFloat}} + {type, 'float'},{{/isFloat}}{{#isDouble}} + {type, 'float'},{{/isDouble}}{{#isByteArray}} + {type, 'binary'},{{/isByteArray}}{{#isBinary}} + {type, 'binary'},{{/isBinary}}{{#isBoolean}} + {type, 'boolean'},{{/isBoolean}}{{#isDate}} + {type, 'date'},{{/isDate}}{{#isDateTime}} + {type, 'datetime'},{{/isDateTime}}{{#isEnum}} + {enum, [{{#allowableValues}}{{#values}}'{{.}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] },{{/isEnum}}{{#maximum}} + {max, {{maximum}} }, {{/maximum}}{{#exclusiveMaximum}} + {exclusive_max, {{exclusiveMaximum}} },{{/exclusiveMaximum}}{{#minimum}} + {min, {{minimum}} },{{/minimum}}{{#exclusiveMinimum}} + {exclusive_min, {{exclusiveMinimum}} },{{/exclusiveMinimum}}{{#maxLength}} + {max_length, {{maxLength}} },{{/maxLength}}{{#minLength}} + {min_length, {{minLength}} },{{/minLength}}{{#pattern}} + {pattern, "{{{pattern}}}" },{{/pattern}}{{#isBodyParam}} + schema,{{/isBodyParam}}{{#required}} + required{{/required}}{{^required}} + not_required{{/required}} + ] + }; +{{/allParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +request_param_info(OperationID, Name) -> + error({unknown_param, OperationID, Name}). + +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state() +) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. + +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). + +populate_request_params(_, [], Req, _, Model) -> + {ok, Model, Req}; + +populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> + case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of + {ok, K, V, Req} -> + populate_request_params(OperationID, T, Req, ValidatorState, maps:put(K, V, Model)); + Error -> + Error + end. + +populate_request_param(OperationID, Name, Req0, ValidatorState) -> + #{rules := Rules, source := Source} = request_param_info(OperationID, Name), + case get_value(Source, Name, Req0) of + {error, Reason, Req} -> + {error, Reason, Req}; + {Value, Req} -> + case prepare_param(Rules, Name, Value, ValidatorState) of + {ok, Result} -> {ok, Name, Result, Req}; + {error, Reason} -> + {error, Reason, Req} + end + end. + +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state() +) -> ok | no_return(). +{{#apiInfo}}{{#apis}} +{{#operations}}{{#operation}} +{{#responses}} +validate_response('{{operationId}}', {{code}}, Body, ValidatorState) -> + validate_response_body('{{dataType}}', '{{baseType}}', Body, ValidatorState); +{{/responses}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. + +validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> + [ + validate(schema, ReturnBaseType, Item, ValidatorState) + || Item <- Body]; + +validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> + validate(schema, ReturnBaseType, Body, ValidatorState). + +%%% +validate(Rule = required, Name, Value, _ValidatorState) -> + case Value of + undefined -> validation_error(Rule, Name); + _ -> ok + end; + +validate(not_required, _Name, _Value, _ValidatorState) -> + ok; + +validate(_, _Name, undefined, _ValidatorState) -> + ok; + +validate(Rule = {type, 'integer'}, Name, Value, _ValidatorState) -> + try + {ok, {{packageName}}_utils:to_int(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'float'}, Name, Value, _ValidatorState) -> + try + {ok, {{packageName}}_utils:to_float(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'binary'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(_Rule = {type, 'boolean'}, _Name, Value, _ValidatorState) when is_boolean(Value) -> + {ok, Value}; + +validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> + V = binary_to_lower(Value), + try + case binary_to_existing_atom(V, utf8) of + B when is_boolean(B) -> {ok, B}; + _ -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {type, 'date'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {type, 'datetime'}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> + try + FormattedValue = erlang:binary_to_existing_atom(Value, utf8), + case lists:member(FormattedValue, Values) of + true -> {ok, FormattedValue}; + false -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; + +validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> + case Value =< Max of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> + case Value > ExclusiveMax of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> + case Value >= Min of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> + case Value =< ExclusiveMin of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> + case size(Value) =< MaxLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> + case size(Value) >= MinLength of + true -> ok; + false -> validation_error(Rule, Name) + end; + +validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> + {ok, MP} = re:compile(Pattern), + case re:run(Value, MP) of + {match, _} -> ok; + _ -> validation_error(Rule, Name) + end; + +validate(Rule = schema, Name, Value, ValidatorState) -> + Definition = list_to_binary("#/components/schemas/" ++ {{packageName}}_utils:to_list(Name)), + try + _ = validate_with_schema(Value, Definition, ValidatorState), + ok + catch + throw:[{schema_invalid, _, Error} | _] -> + Info = #{ + type => schema_invalid, + error => Error + }, + validation_error(Rule, Name, Info); + throw:[{data_invalid, Schema, Error, _, Path} | _] -> + Info = #{ + type => data_invalid, + error => Error, + schema => Schema, + path => Path + }, + validation_error(Rule, Name, Info) + end; + +validate(Rule, Name, _Value, _ValidatorState) -> + error_logger:info_msg("Can't validate ~p with ~p", [Name, Rule]), + error({unknown_validation_rule, Rule}). + +-spec validation_error(Rule :: any(), Name :: any()) -> no_return(). + +validation_error(ViolatedRule, Name) -> + validation_error(ViolatedRule, Name, #{}). + +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{}) -> no_return(). + +validation_error(ViolatedRule, Name, Info) -> + throw({wrong_param, Name, ViolatedRule, Info}). + +-spec get_value(body | qs_val | header | binding, Name :: any(), Req0 :: cowboy_req:req()) -> + {Value :: any(), Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. +get_value(body, _Name, Req0) -> + {ok, Body, Req} = cowboy_req:read_body(Req0), + case prepare_body(Body) of + {error, Reason} -> + {error, Reason, Req}; + Value -> + {Value, Req} + end; + +get_value(qs_val, Name, Req) -> + QS = cowboy_req:parse_qs(Req), + Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_qs(Name), QS), + {Value, Req}; + +get_value(header, Name, Req) -> + Headers = cowboy_req:headers(Req), + Value = maps:get({{packageName}}_utils:to_header(Name), Headers, undefined), + {Value, Req}; + +get_value(binding, Name, Req) -> + Value = cowboy_req:binding({{packageName}}_utils:to_binding(Name), Req), + {Value, Req}. + +prepare_body(Body) -> + case Body of + <<"">> -> <<"">>; + _ -> + try + jsx:decode(Body, [return_maps]) + catch + error:_ -> + {error, {invalid_body, not_json, Body}} + end + end. + +validate_with_schema(Body, Definition, ValidatorState) -> + jesse_schema_validator:validate_with_state( + [{<<"$ref">>, Definition}], + Body, + ValidatorState + ). + +prepare_param(Rules, Name, Value, ValidatorState) -> + try + Result = lists:foldl( + fun(Rule, Acc) -> + case validate(Rule, Name, Acc, ValidatorState) of + ok -> Acc; + {ok, Prepared} -> Prepared + end + end, + Value, + Rules + ), + {ok, Result} + catch + throw:Reason -> + {error, Reason} + end. + +binary_to_lower(V) when is_binary(V) -> + list_to_binary(string:to_lower({{packageName}}_utils:to_list(V))). diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/app.src.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/app.src.mustache new file mode 100644 index 000000000000..a90c4e7cae77 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/app.src.mustache @@ -0,0 +1,19 @@ +{application, {{packageName}}, [ + {description, {{#appDescription}}"{{.}}"{{/appDescription}}{{^appDescription}}"OpenAPI rest server library"{{/appDescription}}}, + {vsn, "{{apiVersion}}"}, + {registered, []}, + {applications, [ + kernel, + stdlib, + ssl, + inets, + jsx, + jesse, + cowboy + ]}, + {env, [ + ]}, + {modules, []}, + {licenses, [{{#licenseInfo}}"{{.}}"{{/licenseInfo}}]}, + {links, [{{#infoUrl}}"{{.}}"{{/infoUrl}}]} +]}. diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/auth.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/auth.mustache new file mode 100644 index 000000000000..3159e352a9c5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/auth.mustache @@ -0,0 +1,52 @@ +-module({{packageName}}_auth). + +-export([authorize_api_key/5]). + +-spec authorize_api_key( + LogicHandler :: atom(), + OperationID :: {{packageName}}_api:operation_id(), + From :: header | qs_val, + KeyParam :: iodata() | atom(), + Req ::cowboy_req:req() +)-> {true, Context :: #{binary() => any()}, Req ::cowboy_req:req()} | + {false, AuthHeader :: binary(), Req ::cowboy_req:req()}. + +authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> + {ApiKey, Req} = get_api_key(From, KeyParam, Req0), + case ApiKey of + undefined -> + AuthHeader = <<"">>, + {false, AuthHeader, Req}; + _ -> + Result = {{packageName}}_logic_handler:authorize_api_key( + LogicHandler, + OperationID, + ApiKey + ), + case Result of + {{#authMethods}} + {{#isApiKey}} + {true, Context} -> + {true, Context, Req}; + {{/isApiKey}} + {{/authMethods}} + false -> + AuthHeader = <<"">>, + {false, AuthHeader, Req} + end + end. + +get_api_key(header, KeyParam, Req) -> + Headers = cowboy_req:headers(Req), + { + maps:get( + {{packageName}}_utils:to_header(KeyParam), + Headers, + undefined + ), + Req + }; + +get_api_key(qs_val, KeyParam, Req) -> + QS = cowboy_req:parse_qs(Req), + { {{packageName}}_utils:get_opt(KeyParam, QS), Req}. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/default_logic_handler.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/default_logic_handler.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/erlang-server/default_logic_handler.mustache rename to modules/openapi-generator/src/main/resources/erlang-server-deprecated/default_logic_handler.mustache diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/handler.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/handler.mustache new file mode 100644 index 000000000000..70756b2549ff --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/handler.mustache @@ -0,0 +1,252 @@ +%% basic handler +-module({{classname}}). + +%% Cowboy REST callbacks +-export([allowed_methods/2]). +-export([init/2]). +-export([allow_missing_post/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([known_content_type/2]). +-export([malformed_request/2]). +-export([valid_content_headers/2]). +-export([valid_entity_length/2]). + +%% Handlers +-export([handle_request_json/2]). + +-record(state, { + operation_id :: {{packageName}}_api:operation_id(), + logic_handler :: atom(), + validator_state :: jesse_state:state(), + context=#{} :: #{} +}). + +-type state() :: state(). + +-spec init(Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) -> + {cowboy_rest, Req :: cowboy_req:req(), State :: state()}. + +init(Req, {Operations, LogicHandler, ValidatorMod}) -> + Method = cowboy_req:method(Req), + OperationID = maps:get(Method, Operations, undefined), + + ValidatorState = ValidatorMod:get_validator_state(), + + error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), + + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + }, + {cowboy_rest, Req, State}. + +-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> + {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. + +{{#operations}}{{#operation}} +allowed_methods( + Req, + State = #state{ + operation_id = '{{operationId}}' + } +) -> + {[<<"{{httpMethod}}">>], Req, State}; +{{/operation}}{{/operations}} +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: true | {false, AuthHeader :: iodata()}, + Req :: cowboy_req:req(), + State :: state() + }. +{{#operations}} +{{#operation}} +{{#authMethods}} +is_authorized( + Req0, + State = #state{ + operation_id = '{{operationId}}' = OperationID, + logic_handler = LogicHandler + } +) -> + {{#isApiKey}} + From = {{#isKeyInQuery}}qs_val{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}, + Result = {{packageName}}_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "{{keyParamName}}", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + {{/isApiKey}} + {{#isOAuth}} + From = header, + Result = {{packageName}}_auth:authorize_api_key( + LogicHandler, + OperationID, + From, + "Authorization", + Req0 + ), + case Result of + {true, Context, Req} -> {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} + end; + {{/isOAuth}} +{{/authMethods}} +{{/operation}} +{{/operations}} +{{^authMethods}} +is_authorized(Req, State) -> + {true, Req, State}. +{{/authMethods}} +{{#authMethods}} +is_authorized(Req, State) -> + {{false, <<"">>}, Req, State}. +{{/authMethods}} + +-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), AcceptResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_accepted(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> + {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. +{{#operations}}{{#operation}} +valid_content_headers( + Req0, + State = #state{ + operation_id = '{{operationId}}' + } +) -> + Headers = [{{#headerParams}}"{{baseName}}"{{^-last}},{{/-last}}{{/headerParams}}], + {Result, Req} = validate_headers(Headers, Req0), + {Result, Req, State}; +{{/operation}}{{/operations}} +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> + { + Value :: [{binary(), ProvideResource :: atom()}], + Req :: cowboy_req:req(), + State :: state() + }. + +content_types_provided(Req, State) -> + {[ + {<<"application/json">>, handle_request_json} + ], Req, State}. + +-spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +malformed_request(Req, State) -> + {false, Req, State}. + +-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> + {Value :: false, Req :: cowboy_req:req(), State :: state()}. + +allow_missing_post(Req, State) -> + {false, Req, State}. + +-spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> + processed_response(). + +delete_resource(Req, State) -> + handle_request_json(Req, State). + +-spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +known_content_type(Req, State) -> + {true, Req, State}. + +-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> + {Value :: true, Req :: cowboy_req:req(), State :: state()}. + +valid_entity_length(Req, State) -> + %% @TODO check the length + {true, Req, State}. + +%%%% +-type result_ok() :: { + ok, + {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} +}. + +-type result_error() :: {error, Reason :: any()}. + +-type processed_response() :: {stop, cowboy_req:req(), state()}. + +-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> + processed_response(). + +process_response(Response, Req0, State = #state{operation_id = OperationID}) -> + case Response of + {ok, {Code, Headers, Body}} -> + Req = cowboy_req:reply(Code, Headers, Body, Req0), + {stop, Req, State}; + {error, Message} -> + error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), + + Req = cowboy_req:reply(400, Req0), + {stop, Req, State} + end. + +-spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). + +handle_request_json( + Req0, + State = #state{ + operation_id = OperationID, + logic_handler = LogicHandler, + validator_state = ValidatorState + } +) -> + case {{packageName}}_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = {{packageName}}_logic_handler:handle_request( + LogicHandler, + OperationID, + Req1, + maps:merge(State#state.context, Populated) + ), + _ = {{packageName}}_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = prepare_body(Code, Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. + +validate_headers(_, Req) -> {true, Req}. + +prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> + <<>>; +prepare_body(_Code, Body) -> + jsx:encode(Body). diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/logic_handler.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/logic_handler.mustache new file mode 100644 index 000000000000..eb0688e682ce --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/logic_handler.mustache @@ -0,0 +1,60 @@ +-module({{packageName}}_logic_handler). + +-export([handle_request/4]). +{{#authMethods}} +{{#isApiKey}} +{{#-first}} +-export([authorize_api_key/3]). +{{/-first}} +{{/isApiKey}} +{{/authMethods}} +{{^authMethods}} +-export([authorize_api_key/3]). +{{/authMethods}} +-type context() :: #{binary() => any()}. +-type handler_response() ::{ + Status :: cowboy:http_status(), + Headers :: cowboy:http_headers(), + Body :: jsx:json_term()}. + +-export_type([handler_response/0]). + +{{#authMethods}} + {{#isApiKey}} +-callback authorize_api_key( + OperationID :: {{packageName}}_api:operation_id(), + ApiKey :: binary() +) -> + Result :: boolean() | {boolean(), context()}. + {{/isApiKey}} +{{/authMethods}} + + +-callback handle_request(OperationID :: {{packageName}}_api:operation_id(), cowboy_req:req(), Context :: context()) -> + handler_response(). + +-spec handle_request( + Handler :: atom(), + OperationID :: {{packageName}}_api:operation_id(), + Request :: cowboy_req:req(), + Context :: context() +) -> + handler_response(). + +handle_request(Handler, OperationID, Req, Context) -> + Handler:handle_request(OperationID, Req, Context). + +{{#authMethods}} + {{#isApiKey}} +-spec authorize_api_key(Handler :: atom(), OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> + Result :: false | {true, context()}. +authorize_api_key(Handler, OperationID, ApiKey) -> + Handler:authorize_api_key(OperationID, ApiKey). + {{/isApiKey}} +{{/authMethods}} +{{^authMethods}} +-spec authorize_api_key(Handler :: atom(), OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> + Result :: false. +authorize_api_key(_Handler, _OperationID, _ApiKey) -> + false. +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/openapi.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/openapi.mustache new file mode 100644 index 000000000000..2c1b461cf000 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-json}}} diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/rebar.config.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/rebar.config.mustache new file mode 100644 index 000000000000..743b108f384a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/rebar.config.mustache @@ -0,0 +1,6 @@ +{deps, [ + {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.8.0"}}}, + {rfc3339, {git, "https://github.com/talentdeficit/rfc3339.git", {tag, "master"}}}, + {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "v3.1.0"}}}, + {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.6"}}} +]}. diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/router.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/router.mustache new file mode 100644 index 000000000000..e2efc2206bc1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/router.mustache @@ -0,0 +1,78 @@ +-module({{packageName}}_router). + +-export([get_paths/1, get_validator_state/0]). + +-type operations() :: #{ + Method :: binary() => {{packageName}}_api:operation_id() +}. + +-type init_opts() :: { + Operations :: operations(), + LogicHandler :: atom(), + ValidatorMod :: module() +}. + +-export_type([init_opts/0]). + +-spec get_paths(LogicHandler :: atom()) -> [{'_',[{ + Path :: string(), + Handler :: atom(), + InitOpts :: init_opts() +}]}]. + +get_paths(LogicHandler) -> + ValidatorState = prepare_validator(), + PreparedPaths = maps:fold( + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, + [], + group_paths() + ), + [ + {'_', + [{P, H, {O, LogicHandler, ValidatorState}} || {P, H, O} <- PreparedPaths] + } + ]. + +group_paths() -> + maps:fold( + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, + #{}, + get_operations() + ). + +get_operations() -> + #{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + '{{operationId}}' => #{ + path => "{{{basePathWithoutHost}}}{{{path}}}", + method => <<"{{httpMethod}}">>, + handler => '{{classname}}' + }{{^-last}},{{/-last}}{{/operation}}{{^-last}},{{/-last}}{{/operations}}{{/apis}}{{/apiInfo}} + }. + +get_validator_state() -> + persistent_term:get({?MODULE, validator_state}). + + +prepare_validator() -> + R = jsx:decode(element(2, file:read_file(get_openapi_path()))), + JesseState = jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]), + persistent_term:put({?MODULE, validator_state}, JesseState), + ?MODULE. + + +get_openapi_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join({{packageName}}_utils:priv_dir(AppName), "{{{openAPISpecName}}}.json"). diff --git a/modules/openapi-generator/src/main/resources/erlang-server-deprecated/server.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/server.mustache new file mode 100644 index 000000000000..cca0af57a84c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/server.mustache @@ -0,0 +1,67 @@ +-module({{packageName}}_server). + + +-define(DEFAULT_LOGIC_HANDLER, {{packageName}}_default_logic_handler). + +-export([start/2]). + +-spec start( ID :: any(), #{ + ip => inet:ip_address(), + port => inet:port_number(), + logic_handler => module(), + net_opts => [] +}) -> {ok, pid()} | {error, any()}. + +start(ID, #{ + ip := IP , + port := Port, + net_opts := NetOpts +} = Params) -> + {Transport, TransportOpts} = get_socket_transport(IP, Port, NetOpts), + LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), + ExtraOpts = maps:get(cowboy_extra_opts, Params, []), + CowboyOpts = get_cowboy_config(LogicHandler, ExtraOpts), + case Transport of + ssl -> + cowboy:start_tls(ID, TransportOpts, CowboyOpts); + tcp -> + cowboy:start_clear(ID, TransportOpts, CowboyOpts) + end. + +get_socket_transport(IP, Port, Options) -> + Opts = [ + {ip, IP}, + {port, Port} + ], + case {{packageName}}_utils:get_opt(ssl, Options) of + SslOpts = [_|_] -> + {ssl, Opts ++ SslOpts}; + undefined -> + {tcp, Opts} + end. + +get_cowboy_config(LogicHandler, ExtraOpts) -> + get_cowboy_config(LogicHandler, ExtraOpts, get_default_opts(LogicHandler)). + +get_cowboy_config(_LogicHandler, [], Opts) -> + Opts; + +get_cowboy_config(LogicHandler, [{env, Env} | Rest], Opts) -> + NewEnv = case proplists:get_value(dispatch, Env) of + undefined -> [get_default_dispatch(LogicHandler) | Env]; + _ -> Env + end, + get_cowboy_config(LogicHandler, Rest, store_key(env, NewEnv, Opts)); + +get_cowboy_config(LogicHandler, [{Key, Value}| Rest], Opts) -> + get_cowboy_config(LogicHandler, Rest, store_key(Key, Value, Opts)). + +get_default_dispatch(LogicHandler) -> + Paths = {{packageName}}_router:get_paths(LogicHandler), + #{dispatch => cowboy_router:compile(Paths)}. + +get_default_opts(LogicHandler) -> + #{env => get_default_dispatch(LogicHandler)}. + +store_key(Key, Value, Opts) -> + maps:put(Key, Value, Opts). diff --git a/modules/openapi-generator/src/main/resources/erlang-server/utils.mustache b/modules/openapi-generator/src/main/resources/erlang-server-deprecated/utils.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/erlang-server/utils.mustache rename to modules/openapi-generator/src/main/resources/erlang-server-deprecated/utils.mustache diff --git a/modules/openapi-generator/src/main/resources/erlang-server/README.mustache b/modules/openapi-generator/src/main/resources/erlang-server/README.mustache index 5d36ca07576b..887f730062fe 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/README.mustache @@ -4,54 +4,33 @@ An Erlang server stub generated by [OpenAPI Generator](https://openapi-generator.tech) given an OpenAPI spec. -Dependency: [Cowboy](https://github.com/ninenines/cowboy) +Dependencies: Erlang OTP/27 and rebar3. Also: +- [Cowboy](https://hex.pm/packages/cowboy) +- [Ranch](https://hex.pm/packages/ranch) +- [Jesse](https://hex.pm/packages/jesse) ## Prerequisites -TODO - ## Getting started -Use erlang-server with erlang.mk - - 1, Create an application by using erlang.mk - $ mkdir http_server - $ cd http_server - $ wget https://erlang.mk/erlang.mk - $ make -f erlang.mk bootstrap bootstrap-rel - $ make run - - 2, Modify the Makefile in the http_server directory to the following to introduce the dependency library: - PROJECT = http_server - PROJECT_DESCRIPTION = New project - PROJECT_VERSION = 0.1.0 - - DEPS = cowboy jesse jsx - dep_cowboy_commit = 2.5.0 - dep_jesse_commit = 1.5.2 - dep_jsx_commit = 2.9.0 - DEP_PLUGINS = cowboy jesse jsx - - PACKAGES += rfc3339 - pkg_rfc3339_name = rfc3339 - pkg_rfc3339_description = an erlang/elixir rfc3339 lib - pkg_rfc3339_homepage = https://github.com/talentdeficit/rfc3339 - pkg_rfc3339_fetch = git - pkg_rfc3339_repo = https://github.com/talentdeficit/rfc3339 - pkg_rfc3339_commit = master - - include erlang.mk - - 3, Generate erlang-server project using openapi-generator +Use erlang-server with rebar3 + + 1, Create an application by using rebar3 + $ rebar3 new app http_server + + 2, Generate erlang-server project using openapi-generator https://github.com/OpenAPITools/openapi-generator#2---getting-started - 4, Copy erlang-server file to http_server project,Don't forget the 'priv' folder. + 3, Copy erlang-server file to http_server project, and don't forget the 'priv' folder. - 5, Start in the http_server project: + 4, Start in the http_server project: 1, Introduce the following line in the http_server_app:start(_Type, _Args) function - openapi_server:start(http_server, #{ip=>{127,0,0,1}, port=>8080, net_opts=>[]}) - 2, Compilation http_server project - $ make + openapi_server:start(http_server, #{ip => {127,0,0,1}, port => 8080}) + 2, Compile your http_server project + $ rebar3 compile 3, Start erlang virtual machine - $erl -pa ./deps/cowboy/ebin -pa ./deps/cowlib/ebin -pa ./deps/ranch/ebin -pa ./deps/jsx/ebin -pa ./deps/jesse/ebin -pa ./deps/rfc3339/ebin -pa ./ebin + $ rebar3 shell 4, Start project application:ensure_all_started(http_server). + +To implement your own business logic, create a module called `http_server_logic` that implements the +behaviour `openapi_logic_handler`. Refer to `openapi_logic_handler` documentation for details. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/api.mustache b/modules/openapi-generator/src/main/resources/erlang-server/api.mustache index b97e4a2c5eca..ba8f13854f61 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/api.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/api.mustache @@ -1,37 +1,60 @@ -module({{packageName}}_api). +-moduledoc """ +This module offers an API for JSON schema validation, using `jesse` under the hood. + +If validation is desired, a jesse state can be loaded using `prepare_validator/1`, +and request and response can be validated using `populate_request/3` +and `validate_response/4` respectively. + +For example, the user-defined `Module:accept_callback/4` can be implemented as follows: +``` +-spec accept_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy:http_status(), cowboy:http_headers(), json:encode_value()}. +accept_callback(Class, OperationID, Req, Context) -> + ValidatorState = openapi_api:prepare_validator(), + case openapi_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = openapi_logic_handler:handle_request( + LogicHandler, + OperationID, + Req1, + maps:merge(State#state.context, Populated) + ), + _ = openapi_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = prepare_body(Code, Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. +``` +""". + +-export([prepare_validator/0, prepare_validator/1, prepare_validator/2]). +-export([populate_request/3, validate_response/4]). --export([request_params/1]). --export([request_param_info/2]). --export([populate_request/3]). --export([validate_response/4]). -%% exported to silence openapi complains --export([get_value/3, validate_response_body/4]). +-ignore_xref([populate_request/3, validate_response/4]). +-ignore_xref([prepare_validator/0, prepare_validator/1, prepare_validator/2]). -type operation_id() :: atom(). -type request_param() :: atom(). -export_type([operation_id/0]). --spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. -{{#apiInfo}}{{#apis}} -{{#operations}}{{#operation}} -request_params('{{operationId}}') -> - [{{#allParams}}{{^isBodyParam}} - '{{baseName}}'{{/isBodyParam}}{{#isBodyParam}} - '{{dataType}}'{{/isBodyParam}}{{^-last}},{{/-last}}{{/allParams}} - ]; -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} -request_params(_) -> - error(unknown_operation). +-dialyzer({nowarn_function, [to_binary/1, to_list/1, validate_response_body/4]}). -type rule() :: - {type, 'binary'} | - {type, 'integer'} | - {type, 'float'} | - {type, 'binary'} | - {type, 'boolean'} | - {type, 'date'} | - {type, 'datetime'} | + {type, binary} | + {type, integer} | + {type, float} | + {type, boolean} | + {type, date} | + {type, datetime} | {enum, [atom()]} | {max, Max :: number()} | {exclusive_max, Max :: number()} | @@ -44,59 +67,99 @@ request_params(_) -> required | not_required. --spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> #{ - source => qs_val | binding | header | body, - rules => [rule()] -}. +-doc #{equiv => prepare_validator/2}. +-spec prepare_validator() -> jesse_state:state(). +prepare_validator() -> + prepare_validator(<<"http://json-schema.org/draft-06/schema#">>). + +-doc #{equiv => prepare_validator/2}. +-spec prepare_validator(binary()) -> jesse_state:state(). +prepare_validator(SchemaVer) -> + prepare_validator(get_openapi_path(), SchemaVer). + +-doc """ +Loads the JSON schema and the desired validation draft into a `t:jesse_state:state()`. +""". +-spec prepare_validator(file:name_all(), binary()) -> jesse_state:state(). +prepare_validator(OpenApiPath, SchemaVer) -> + {ok, FileContents} = file:read_file(OpenApiPath), + R = json:decode(FileContents), + jesse_state:new(R, [{default_schema_ver, SchemaVer}]). + +-doc """ +Automatically loads the entire body from the cowboy req +and validates the JSON body against the schema. +""". +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state()) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). + +-doc """ +Validates that the provided `Code` and `Body` comply with the `ValidatorState` schema +for the `OperationID` operation. +""". +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state()) -> + ok | {ok, term()} | [ok | {ok, term()}] | no_return(). +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#responses}}validate_response('{{operationId}}', {{code}}, Body, ValidatorState) -> + validate_response_body('{{dataType}}', '{{baseType}}', Body, ValidatorState); +{{/responses}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. -{{#apiInfo}}{{#apis}} -{{#operations}}{{#operation}}{{#allParams}} -request_param_info('{{operationId}}', {{^isBodyParam}}'{{baseName}}'{{/isBodyParam}}{{#isBodyParam}}'{{dataType}}'{{/isBodyParam}}) -> +%%% +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}request_params('{{operationId}}') -> + [{{#allParams}}{{^isBodyParam}} + '{{baseName}}'{{/isBodyParam}}{{#isBodyParam}} + '{{dataType}}'{{/isBodyParam}}{{^-last}},{{/-last}}{{/allParams}} + ]; +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}request_params(_) -> + error(unknown_operation). + +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> + #{source => qs_val | binding | header | body, rules => [rule()]}. +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}{{#allParams}}request_param_info('{{operationId}}', {{^isBodyParam}}'{{baseName}}'{{/isBodyParam}}{{#isBodyParam}}'{{dataType}}'{{/isBodyParam}}) -> #{ - source => {{#isQueryParam}}qs_val{{/isQueryParam}} {{#isPathParam}}binding{{/isPathParam}} {{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}{{#isFormParam}}body{{/isFormParam}}, + source => {{#isQueryParam}}qs_val{{/isQueryParam}}{{#isPathParam}}binding{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}{{#isFormParam}}body{{/isFormParam}}, rules => [{{#isString}} - {type, 'binary'},{{/isString}}{{#isInteger}} - {type, 'integer'},{{/isInteger}}{{#isLong}} - {type, 'integer'},{{/isLong}}{{#isFloat}} - {type, 'float'},{{/isFloat}}{{#isDouble}} - {type, 'float'},{{/isDouble}}{{#isByteArray}} - {type, 'binary'},{{/isByteArray}}{{#isBinary}} - {type, 'binary'},{{/isBinary}}{{#isBoolean}} - {type, 'boolean'},{{/isBoolean}}{{#isDate}} - {type, 'date'},{{/isDate}}{{#isDateTime}} - {type, 'datetime'},{{/isDateTime}}{{#isEnum}} + {type, binary},{{/isString}}{{#isInteger}} + {type, integer},{{/isInteger}}{{#isLong}} + {type, integer},{{/isLong}}{{#isFloat}} + {type, float},{{/isFloat}}{{#isDouble}} + {type, float},{{/isDouble}}{{#isByteArray}} + {type, binary},{{/isByteArray}}{{#isBinary}} + {type, binary},{{/isBinary}}{{#isBoolean}} + {type, boolean},{{/isBoolean}}{{#isDate}} + {type, date},{{/isDate}}{{#isDateTime}} + {type, datetime},{{/isDateTime}}{{#isEnum}} {enum, [{{#allowableValues}}{{#values}}'{{.}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] },{{/isEnum}}{{#maximum}} - {max, {{maximum}} }, {{/maximum}}{{#exclusiveMaximum}} - {exclusive_max, {{exclusiveMaximum}} },{{/exclusiveMaximum}}{{#minimum}} - {min, {{minimum}} },{{/minimum}}{{#exclusiveMinimum}} - {exclusive_min, {{exclusiveMinimum}} },{{/exclusiveMinimum}}{{#maxLength}} - {max_length, {{maxLength}} },{{/maxLength}}{{#minLength}} - {min_length, {{minLength}} },{{/minLength}}{{#pattern}} - {pattern, "{{{pattern}}}" },{{/pattern}}{{#isBodyParam}} + {max, {{maximum}}},{{/maximum}}{{#exclusiveMaximum}} + {exclusive_max, {{exclusiveMaximum}}},{{/exclusiveMaximum}}{{#minimum}} + {min, {{minimum}}},{{/minimum}}{{#exclusiveMinimum}} + {exclusive_min, {{exclusiveMinimum}}},{{/exclusiveMinimum}}{{#maxLength}} + {max_length, {{maxLength}}},{{/maxLength}}{{#minLength}} + {min_length, {{minLength}}},{{/minLength}}{{#pattern}} + {pattern, "{{{pattern}}}"},{{/pattern}}{{#isBodyParam}} schema,{{/isBodyParam}}{{#required}} required{{/required}}{{^required}} not_required{{/required}} ] }; -{{/allParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} -request_param_info(OperationID, Name) -> +{{/allParams}}{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}request_param_info(OperationID, Name) -> error({unknown_param, OperationID, Name}). --spec populate_request( - OperationID :: operation_id(), - Req :: cowboy_req:req(), - ValidatorState :: jesse_state:state() -) -> - {ok, Model :: #{}, Req :: cowboy_req:req()} | - {error, Reason :: any(), Req :: cowboy_req:req()}. - -populate_request(OperationID, Req, ValidatorState) -> - Params = request_params(OperationID), - populate_request_params(OperationID, Params, Req, ValidatorState, #{}). - populate_request_params(_, [], Req, _, Model) -> {ok, Model, Req}; - populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of {ok, K, V, Req} -> @@ -118,24 +181,9 @@ populate_request_param(OperationID, Name, Req0, ValidatorState) -> end end. --spec validate_response( - OperationID :: operation_id(), - Code :: 200..599, - Body :: jesse:json_term(), - ValidatorState :: jesse_state:state() -) -> ok | no_return(). -{{#apiInfo}}{{#apis}} -{{#operations}}{{#operation}} -{{#responses}} -validate_response('{{operationId}}', {{code}}, Body, ValidatorState) -> - validate_response_body('{{dataType}}', '{{baseType}}', Body, ValidatorState); -{{/responses}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +-include_lib("kernel/include/logger.hrl"). -validate_response(_OperationID, _Code, _Body, _ValidatorState) -> - ok. - -validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> +validate_response_body(list, ReturnBaseType, Body, ValidatorState) -> [ validate(schema, ReturnBaseType, Item, ValidatorState) || Item <- Body]; @@ -143,45 +191,37 @@ validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> validate(schema, ReturnBaseType, Body, ValidatorState). -%%% validate(Rule = required, Name, Value, _ValidatorState) -> case Value of undefined -> validation_error(Rule, Name); _ -> ok end; - validate(not_required, _Name, _Value, _ValidatorState) -> ok; - validate(_, _Name, undefined, _ValidatorState) -> ok; - -validate(Rule = {type, 'integer'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, integer}, Name, Value, _ValidatorState) -> try - {ok, {{packageName}}_utils:to_int(Value)} + {ok, to_int(Value)} catch error:badarg -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'float'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, float}, Name, Value, _ValidatorState) -> try - {ok, {{packageName}}_utils:to_float(Value)} + {ok, to_float(Value)} catch error:badarg -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'binary'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, binary}, Name, Value, _ValidatorState) -> case is_binary(Value) of true -> ok; false -> validation_error(Rule, Name) end; - -validate(_Rule = {type, 'boolean'}, _Name, Value, _ValidatorState) when is_boolean(Value) -> +validate(_Rule = {type, boolean}, _Name, Value, _ValidatorState) when is_boolean(Value) -> {ok, Value}; - -validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, boolean}, Name, Value, _ValidatorState) -> V = binary_to_lower(Value), try case binary_to_existing_atom(V, utf8) of @@ -192,19 +232,16 @@ validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> error:badarg -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'date'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, date}, Name, Value, _ValidatorState) -> case is_binary(Value) of true -> ok; false -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'datetime'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, datetime}, Name, Value, _ValidatorState) -> case is_binary(Value) of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> try FormattedValue = erlang:binary_to_existing_atom(Value, utf8), @@ -216,52 +253,44 @@ validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> error:badarg -> validation_error(Rule, Name) end; - validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> case Value =< Max of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> case Value > ExclusiveMax of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> case Value >= Min of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> case Value =< ExclusiveMin of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> case size(Value) =< MaxLength of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> case size(Value) >= MinLength of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> {ok, MP} = re:compile(Pattern), case re:run(Value, MP) of {match, _} -> ok; _ -> validation_error(Rule, Name) end; - validate(Rule = schema, Name, Value, ValidatorState) -> - Definition = list_to_binary("#/components/schemas/" ++ {{packageName}}_utils:to_list(Name)), + Definition = list_to_binary("#/components/schemas/" ++ to_list(Name)), try _ = validate_with_schema(Value, Definition, ValidatorState), ok @@ -281,18 +310,15 @@ validate(Rule = schema, Name, Value, ValidatorState) -> }, validation_error(Rule, Name, Info) end; - validate(Rule, Name, _Value, _ValidatorState) -> - error_logger:info_msg("Can't validate ~p with ~p", [Name, Rule]), + ?LOG_INFO(#{what => "Cannot validate rule", name => Name, rule => Rule}), error({unknown_validation_rule, Rule}). -spec validation_error(Rule :: any(), Name :: any()) -> no_return(). - validation_error(ViolatedRule, Name) -> validation_error(ViolatedRule, Name, #{}). --spec validation_error(Rule :: any(), Name :: any(), Info :: #{}) -> no_return(). - +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{_ := _}) -> no_return(). validation_error(ViolatedRule, Name, Info) -> throw({wrong_param, Name, ViolatedRule, Info}). @@ -307,31 +333,26 @@ get_value(body, _Name, Req0) -> Value -> {Value, Req} end; - get_value(qs_val, Name, Req) -> QS = cowboy_req:parse_qs(Req), - Value = {{packageName}}_utils:get_opt({{packageName}}_utils:to_qs(Name), QS), + Value = get_opt(to_qs(Name), QS), {Value, Req}; - get_value(header, Name, Req) -> Headers = cowboy_req:headers(Req), - Value = maps:get({{packageName}}_utils:to_header(Name), Headers, undefined), + Value = maps:get(to_header(Name), Headers, undefined), {Value, Req}; - get_value(binding, Name, Req) -> - Value = cowboy_req:binding({{packageName}}_utils:to_binding(Name), Req), + Value = cowboy_req:binding(to_binding(Name), Req), {Value, Req}. +prepare_body(<<>>) -> + <<>>; prepare_body(Body) -> - case Body of - <<"">> -> <<"">>; - _ -> - try - jsx:decode(Body, [return_maps]) - catch - error:_ -> - {error, {invalid_body, not_json, Body}} - end + try + json:decode(Body) + catch + error:_ -> + {error, {invalid_body, not_json, Body}} end. validate_with_schema(Body, Definition, ValidatorState) -> @@ -359,5 +380,84 @@ prepare_param(Rules, Name, Value, ValidatorState) -> {error, Reason} end. +-spec to_binary(iodata() | atom() | number()) -> binary(). +to_binary(V) when is_binary(V) -> V; +to_binary(V) when is_list(V) -> iolist_to_binary(V); +to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); +to_binary(V) when is_integer(V) -> integer_to_binary(V); +to_binary(V) when is_float(V) -> float_to_binary(V). + +-spec to_list(iodata() | atom() | number()) -> binary(). +to_list(V) when is_list(V) -> V; +to_list(V) when is_binary(V) -> binary_to_list(V); +to_list(V) when is_atom(V) -> atom_to_list(V); +to_list(V) when is_integer(V) -> integer_to_list(V); +to_list(V) when is_float(V) -> float_to_list(V). + +-spec to_float(iodata()) -> float(). +to_float(V) -> + binary_to_float(iolist_to_binary([V])). + +-spec to_int(integer() | binary() | list()) -> integer(). +to_int(Data) when is_integer(Data) -> + Data; +to_int(Data) when is_binary(Data) -> + binary_to_integer(Data); +to_int(Data) when is_list(Data) -> + list_to_integer(Data). + +-spec to_header(iodata() | atom() | number()) -> binary(). +to_header(Name) -> + to_binary(string:lowercase(to_binary(Name))). + binary_to_lower(V) when is_binary(V) -> - list_to_binary(string:to_lower({{packageName}}_utils:to_list(V))). + string:lowercase(V). + +-spec to_qs(iodata() | atom() | number()) -> binary(). +to_qs(Name) -> + to_binary(Name). + +-spec to_binding(iodata() | atom() | number()) -> atom(). +to_binding(Name) -> + Prepared = to_binary(Name), + binary_to_existing_atom(Prepared, utf8). + +-spec get_opt(any(), []) -> any(). +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> Value; + false -> Default + end. + +get_openapi_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join(priv_dir(AppName), "{{{openAPISpecName}}}.json"). + +-include_lib("kernel/include/file.hrl"). + +-spec priv_dir(Application :: atom()) -> file:name_all(). +priv_dir(AppName) -> + case code:priv_dir(AppName) of + Value when is_list(Value) -> + Value ++ "/"; + _Error -> + select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) + end. + +select_priv_dir(Paths) -> + case lists:dropwhile(fun test_priv_dir/1, Paths) of + [Path | _] -> Path; + _ -> exit(no_priv_dir) + end. + +test_priv_dir(Path) -> + case file:read_file_info(Path) of + {ok, #file_info{type = directory}} -> + false; + _ -> + true + end. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/app.src.mustache b/modules/openapi-generator/src/main/resources/erlang-server/app.src.mustache index a90c4e7cae77..a7ab1dbc1492 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/app.src.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/app.src.mustache @@ -1,19 +1,11 @@ -{application, {{packageName}}, [ - {description, {{#appDescription}}"{{.}}"{{/appDescription}}{{^appDescription}}"OpenAPI rest server library"{{/appDescription}}}, - {vsn, "{{apiVersion}}"}, - {registered, []}, - {applications, [ - kernel, - stdlib, - ssl, - inets, - jsx, - jesse, - cowboy - ]}, - {env, [ - ]}, - {modules, []}, - {licenses, [{{#licenseInfo}}"{{.}}"{{/licenseInfo}}]}, - {links, [{{#infoUrl}}"{{.}}"{{/infoUrl}}]} -]}. +{application, + {{packageName}}, + [{description, + {{#appDescription}}"{{.}}"{{/appDescription}}{{^appDescription}}"OpenAPI rest server library"{{/appDescription}}}, + {vsn, "{{apiVersion}}"}, + {registered, []}, + {applications, [kernel, stdlib, public_key, ssl, inets, ranch, cowboy]}, + {env, []}, + {modules, []}, + {licenses, [{{#licenseInfo}}"{{.}}"{{/licenseInfo}}]}, + {links, [{{#infoUrl}}"{{.}}"{{/infoUrl}}]}]}. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/auth.mustache b/modules/openapi-generator/src/main/resources/erlang-server/auth.mustache index 3159e352a9c5..060cb0269bd2 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/auth.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/auth.mustache @@ -2,51 +2,44 @@ -export([authorize_api_key/5]). --spec authorize_api_key( - LogicHandler :: atom(), - OperationID :: {{packageName}}_api:operation_id(), - From :: header | qs_val, - KeyParam :: iodata() | atom(), - Req ::cowboy_req:req() -)-> {true, Context :: #{binary() => any()}, Req ::cowboy_req:req()} | - {false, AuthHeader :: binary(), Req ::cowboy_req:req()}. - -authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> +-spec authorize_api_key({{packageName}}_logic_handler:api_key_callback(), + {{packageName}}_api:operation_id(), + header | qs_val, + iodata() | atom(), + cowboy_req:req()) -> + {true, {{packageName}}_logic_handler:context(), cowboy_req:req()} | + {false, binary(), cowboy_req:req()}. +authorize_api_key(Handler, OperationID, From, KeyParam, Req0) -> {ApiKey, Req} = get_api_key(From, KeyParam, Req0), case ApiKey of undefined -> - AuthHeader = <<"">>, + AuthHeader = <<>>, {false, AuthHeader, Req}; _ -> - Result = {{packageName}}_logic_handler:authorize_api_key( - LogicHandler, - OperationID, - ApiKey - ), - case Result of - {{#authMethods}} - {{#isApiKey}} - {true, Context} -> + case Handler(OperationID, ApiKey) of + {true, Context} -> {true, Context, Req}; - {{/isApiKey}} - {{/authMethods}} - false -> - AuthHeader = <<"">>, + {false, AuthHeader} -> {false, AuthHeader, Req} end end. get_api_key(header, KeyParam, Req) -> Headers = cowboy_req:headers(Req), - { - maps:get( - {{packageName}}_utils:to_header(KeyParam), - Headers, - undefined - ), - Req - }; - + {maps:get(KeyParam, Headers, undefined), Req}; get_api_key(qs_val, KeyParam, Req) -> QS = cowboy_req:parse_qs(Req), - { {{packageName}}_utils:get_opt(KeyParam, QS), Req}. + {get_opt(KeyParam, QS), Req}. + +-spec get_opt(any(), []) -> any(). +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> + Value; + false -> + Default + end. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache b/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache index 70756b2549ff..c4de6d8e15c9 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/handler.mustache @@ -1,252 +1,129 @@ %% basic handler -module({{classname}}). +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + %% Cowboy REST callbacks --export([allowed_methods/2]). -export([init/2]). --export([allow_missing_post/2]). +-export([allowed_methods/2]). -export([content_types_accepted/2]). -export([content_types_provided/2]). -export([delete_resource/2]). -export([is_authorized/2]). --export([known_content_type/2]). --export([malformed_request/2]). -export([valid_content_headers/2]). --export([valid_entity_length/2]). - -%% Handlers --export([handle_request_json/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). --record(state, { - operation_id :: {{packageName}}_api:operation_id(), - logic_handler :: atom(), - validator_state :: jesse_state:state(), - context=#{} :: #{} -}). +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). --type state() :: state(). +-record(state, + {operation_id :: {{packageName}}_api:operation_id(), + accept_callback :: {{packageName}}_logic_handler:accept_callback(), + provide_callback :: {{packageName}}_logic_handler:provide_callback(), + api_key_handler :: {{packageName}}_logic_handler:api_key_callback(), + context = #{} :: {{packageName}}_logic_handler:context()}). --spec init(Req :: cowboy_req:req(), Opts :: {{packageName}}_router:init_opts()) -> - {cowboy_rest, Req :: cowboy_req:req(), State :: state()}. +-type state() :: #state{}. -init(Req, {Operations, LogicHandler, ValidatorMod}) -> +-spec init(cowboy_req:req(), {{packageName}}_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> Method = cowboy_req:method(Req), OperationID = maps:get(Method, Operations, undefined), - - ValidatorState = ValidatorMod:get_validator_state(), - - error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), - - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - }, + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, {cowboy_rest, Req, State}. --spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> - {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. - -{{#operations}}{{#operation}} -allowed_methods( - Req, - State = #state{ - operation_id = '{{operationId}}' - } -) -> +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +{{#operations}}{{#operation}}allowed_methods(Req, #state{operation_id = '{{operationId}}'} = State) -> {[<<"{{httpMethod}}">>], Req, State}; -{{/operation}}{{/operations}} -allowed_methods(Req, State) -> +{{/operation}}{{/operations}}allowed_methods(Req, State) -> {[], Req, State}. --spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: true | {false, AuthHeader :: iodata()}, - Req :: cowboy_req:req(), - State :: state() - }. +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. {{#operations}} {{#operation}} -{{#authMethods}} -is_authorized( - Req0, - State = #state{ - operation_id = '{{operationId}}' = OperationID, - logic_handler = LogicHandler - } -) -> - {{#isApiKey}} - From = {{#isKeyInQuery}}qs_val{{/isKeyInQuery}}{{#isKeyInHeader}}header{{/isKeyInHeader}}, - Result = {{packageName}}_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "{{keyParamName}}", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} - end; - {{/isApiKey}} - {{#isOAuth}} - From = header, - Result = {{packageName}}_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +{{#authMethods.size}} +is_authorized(Req0, + #state{operation_id = '{{operationId}}' = OperationID, + api_key_handler = Handler} = State) -> + case {{packageName}}_auth:authorize_api_key(Handler, OperationID, {{#isApiKey.isKeyInQuery}}qs_val, {{/isApiKey.isKeyInQuery}}{{^isApiKey.isKeyInQuery}}header, {{/isApiKey.isKeyInQuery}}{{#isApiKey}}"{{keyParamName}}", {{/isApiKey}}{{^isApiKey}}"authorization", {{/isApiKey}}Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; - {{/isOAuth}} -{{/authMethods}} +{{/authMethods.size}} {{/operation}} {{/operations}} -{{^authMethods}} is_authorized(Req, State) -> {true, Req, State}. -{{/authMethods}} -{{#authMethods}} -is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. -{{/authMethods}} - --spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), AcceptResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. -content_types_accepted(Req, State) -> +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +{{#operations}}{{#operation}}content_types_accepted(Req, #state{operation_id = '{{operationId}}'} = State) -> + {{^consumes.size}} + {[], Req, State}; + {{/consumes.size}} + {{#consumes.size}} {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. + {{#consumes}} + {<<"{{mediaType}}">>, handle_type_accepted}{{^-last}}{{#consumes.size}},{{/consumes.size}}{{/-last}} + {{/consumes}} + ], Req, State}; + {{/consumes.size}} +{{/operation}}{{/operations}}content_types_accepted(Req, State) -> + {[], Req, State}. --spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> - {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. -{{#operations}}{{#operation}} -valid_content_headers( - Req0, - State = #state{ - operation_id = '{{operationId}}' - } -) -> - Headers = [{{#headerParams}}"{{baseName}}"{{^-last}},{{/-last}}{{/headerParams}}], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; -{{/operation}}{{/operations}} -valid_content_headers(Req, State) -> +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +{{#operations}}{{#operation}}valid_content_headers(Req, #state{operation_id = '{{operationId}}'} = State) -> + {true, Req, State}; +{{/operation}}{{/operations}}valid_content_headers(Req, State) -> {false, Req, State}. --spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), ProvideResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. - -content_types_provided(Req, State) -> +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +{{#operations}}{{#operation}}content_types_provided(Req, #state{operation_id = '{{operationId}}'} = State) -> + {{^produces.size}} + {[], Req, State}; + {{/produces.size}} + {{#produces.size}} {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. - --spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -malformed_request(Req, State) -> - {false, Req, State}. - --spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -allow_missing_post(Req, State) -> - {false, Req, State}. - --spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> - processed_response(). + {{#produces}} + {<<"{{mediaType}}">>, handle_type_provided}{{^-last}}{{#produces.size}},{{/produces.size}}{{/-last}} + {{/produces}} + ], Req, State}; + {{/produces.size}} +{{/operation}}{{/operations}}content_types_provided(Req, State) -> + {[], Req, State}. +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. delete_resource(Req, State) -> - handle_request_json(Req, State). - --spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -known_content_type(Req, State) -> - {true, Req, State}. - --spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -valid_entity_length(Req, State) -> - %% @TODO check the length - {true, Req, State}. - -%%%% --type result_ok() :: { - ok, - {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} -}. - --type result_error() :: {error, Reason :: any()}. - --type processed_response() :: {stop, cowboy_req:req(), state()}. - --spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> - processed_response(). - -process_response(Response, Req0, State = #state{operation_id = OperationID}) -> - case Response of - {ok, {Code, Headers, Body}} -> - Req = cowboy_req:reply(Code, Headers, Body, Req0), - {stop, Req, State}; - {error, Message} -> - error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), - - Req = cowboy_req:reply(400, Req0), - {stop, Req, State} - end. - --spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). - -handle_request_json( - Req0, - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - } -) -> - case {{packageName}}_api:populate_request(OperationID, Req0, ValidatorState) of - {ok, Populated, Req1} -> - {Code, Headers, Body} = {{packageName}}_logic_handler:handle_request( - LogicHandler, - OperationID, - Req1, - maps:merge(State#state.context, Populated) - ), - _ = {{packageName}}_api:validate_response( - OperationID, - Code, - Body, - ValidatorState - ), - PreparedBody = prepare_body(Code, Body), - Response = {ok, {Code, Headers, PreparedBody}}, - process_response(Response, Req1, State); - {error, Reason, Req1} -> - process_response({error, Reason}, Req1, State) - end. - -validate_headers(_, Req) -> {true, Req}. - -prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(_Code, Body) -> - jsx:encode(Body). + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { {{packageName}}_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler({{operations.pathPrefix}}, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler({{operations.pathPrefix}}, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache b/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache index eb0688e682ce..1d33ec7e7293 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/logic_handler.mustache @@ -1,60 +1,63 @@ -module({{packageName}}_logic_handler). --export([handle_request/4]). -{{#authMethods}} -{{#isApiKey}} -{{#-first}} --export([authorize_api_key/3]). -{{/-first}} -{{/isApiKey}} -{{/authMethods}} -{{^authMethods}} --export([authorize_api_key/3]). -{{/authMethods}} --type context() :: #{binary() => any()}. --type handler_response() ::{ - Status :: cowboy:http_status(), - Headers :: cowboy:http_headers(), - Body :: jsx:json_term()}. - --export_type([handler_response/0]). - -{{#authMethods}} - {{#isApiKey}} --callback authorize_api_key( - OperationID :: {{packageName}}_api:operation_id(), - ApiKey :: binary() -) -> - Result :: boolean() | {boolean(), context()}. - {{/isApiKey}} -{{/authMethods}} - - --callback handle_request(OperationID :: {{packageName}}_api:operation_id(), cowboy_req:req(), Context :: context()) -> - handler_response(). - --spec handle_request( - Handler :: atom(), - OperationID :: {{packageName}}_api:operation_id(), - Request :: cowboy_req:req(), - Context :: context() -) -> - handler_response(). - -handle_request(Handler, OperationID, Req, Context) -> - Handler:handle_request(OperationID, Req, Context). - -{{#authMethods}} - {{#isApiKey}} --spec authorize_api_key(Handler :: atom(), OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> - Result :: false | {true, context()}. -authorize_api_key(Handler, OperationID, ApiKey) -> - Handler:authorize_api_key(OperationID, ApiKey). - {{/isApiKey}} -{{/authMethods}} -{{^authMethods}} --spec authorize_api_key(Handler :: atom(), OperationID :: {{packageName}}_api:operation_id(), ApiKey :: binary()) -> - Result :: false. -authorize_api_key(_Handler, _OperationID, _ApiKey) -> - false. -{{/authMethods}} +-include_lib("kernel/include/logger.hrl"). + +-type accept_callback_return() :: + stop + | boolean() + | {true, iodata()} + | {created, iodata()} + | {see_other, iodata()}. +-type api_key_callback() :: + fun(({{packageName}}_api:operation_id(), binary()) -> {true, context()} | {false, iodata()}). +-type accept_callback() :: + fun((atom(), {{packageName}}_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}). +-type provide_callback() :: + fun((atom(), {{packageName}}_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}). +-type context() :: #{_ := _}. + +-export_type([context/0, api_key_callback/0, + accept_callback_return/0, accept_callback/0, provide_callback/0]). + +-optional_callbacks([api_key_callback/2]). + +-callback api_key_callback({{packageName}}_api:operation_id(), binary()) -> + {true, context()} | {false, iodata()}. + +-callback accept_callback(atom(), {{packageName}}_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}. + +-callback provide_callback(atom(), {{packageName}}_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}. + +-export([api_key_callback/2, accept_callback/4, provide_callback/4]). +-ignore_xref([api_key_callback/2, accept_callback/4, provide_callback/4]). + +-spec api_key_callback({{packageName}}_api:operation_id(), binary()) -> {true, #{}}. +api_key_callback(OperationID, ApiKey) -> + ?LOG_ERROR(#{what => "Got not implemented api_key_callback request", + operation_id => OperationID, + api_key => ApiKey}), + {true, #{}}. + +-spec accept_callback(atom(), {{packageName}}_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}. +accept_callback(Class, OperationID, Req, Context) -> + ?LOG_ERROR(#{what => "Got not implemented request to process", + class => Class, + operation_id => OperationID, + request => Req, + context => Context}), + {false, Req, Context}. + +-spec provide_callback(atom(), {{packageName}}_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}. +provide_callback(Class, OperationID, Req, Context) -> + ?LOG_ERROR(#{what => "Got not implemented request to process", + class => Class, + operation_id => OperationID, + request => Req, + context => Context}), + {<<>>, Req, Context}. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache b/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache index 743b108f384a..50cd482ca39b 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/rebar.config.mustache @@ -1,6 +1,15 @@ +{minimum_otp_vsn, "27"}. + {deps, [ - {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.8.0"}}}, - {rfc3339, {git, "https://github.com/talentdeficit/rfc3339.git", {tag, "master"}}}, - {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "v3.1.0"}}}, - {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.6"}}} + {cowboy, "2.12.0"}, + {ranch, "2.1.0"}, + {jesse, "1.8.1"} ]}. + +{dialyzer, + [{plt_extra_apps, [cowboy, cowlib, ranch, jesse]}, + {warnings, [missing_return, unknown]} +]}. + +{xref_checks, + [undefined_function_calls, deprecated_function_calls, deprecated_functions]}. diff --git a/modules/openapi-generator/src/main/resources/erlang-server/router.mustache b/modules/openapi-generator/src/main/resources/erlang-server/router.mustache index e2efc2206bc1..2bc70bdac73c 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/router.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/router.mustache @@ -1,57 +1,36 @@ -module({{packageName}}_router). --export([get_paths/1, get_validator_state/0]). +-export([get_paths/1]). --type operations() :: #{ - Method :: binary() => {{packageName}}_api:operation_id() -}. - --type init_opts() :: { - Operations :: operations(), - LogicHandler :: atom(), - ValidatorMod :: module() -}. +-type method() :: binary(). +-type operations() :: #{method() => {{packageName}}_api:operation_id()}. +-type init_opts() :: {operations(), module()}. -export_type([init_opts/0]). --spec get_paths(LogicHandler :: atom()) -> [{'_',[{ - Path :: string(), - Handler :: atom(), - InitOpts :: init_opts() -}]}]. - +-spec get_paths(LogicHandler :: module()) -> cowboy_router:routes(). get_paths(LogicHandler) -> - ValidatorState = prepare_validator(), PreparedPaths = maps:fold( - fun(Path, #{operations := Operations, handler := Handler}, Acc) -> - [{Path, Handler, Operations} | Acc] - end, - [], - group_paths() - ), - [ - {'_', - [{P, H, {O, LogicHandler, ValidatorState}} || {P, H, O} <- PreparedPaths] - } - ]. + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, [], group_paths() + ), + [{'_', [{P, H, {O, LogicHandler}} || {P, H, O} <- PreparedPaths]}]. group_paths() -> maps:fold( - fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> - case maps:find(Path, Acc) of - {ok, PathInfo0 = #{operations := Operations0}} -> - Operations = Operations0#{Method => OperationID}, - PathInfo = PathInfo0#{operations => Operations}, - Acc#{Path => PathInfo}; - error -> - Operations = #{Method => OperationID}, - PathInfo = #{handler => Handler, operations => Operations}, - Acc#{Path => PathInfo} - end - end, - #{}, - get_operations() - ). + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, #{}, get_operations()). get_operations() -> #{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} @@ -61,18 +40,3 @@ get_operations() -> handler => '{{classname}}' }{{^-last}},{{/-last}}{{/operation}}{{^-last}},{{/-last}}{{/operations}}{{/apis}}{{/apiInfo}} }. - -get_validator_state() -> - persistent_term:get({?MODULE, validator_state}). - - -prepare_validator() -> - R = jsx:decode(element(2, file:read_file(get_openapi_path()))), - JesseState = jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]), - persistent_term:put({?MODULE, validator_state}, JesseState), - ?MODULE. - - -get_openapi_path() -> - {ok, AppName} = application:get_application(?MODULE), - filename:join({{packageName}}_utils:priv_dir(AppName), "{{{openAPISpecName}}}.json"). diff --git a/modules/openapi-generator/src/main/resources/erlang-server/server.mustache b/modules/openapi-generator/src/main/resources/erlang-server/server.mustache index cca0af57a84c..43ed54e5d230 100644 --- a/modules/openapi-generator/src/main/resources/erlang-server/server.mustache +++ b/modules/openapi-generator/src/main/resources/erlang-server/server.mustache @@ -1,26 +1,21 @@ -module({{packageName}}_server). - --define(DEFAULT_LOGIC_HANDLER, {{packageName}}_default_logic_handler). +-define(DEFAULT_LOGIC_HANDLER, {{packageName}}_logic_handler). -export([start/2]). - --spec start( ID :: any(), #{ - ip => inet:ip_address(), - port => inet:port_number(), - logic_handler => module(), - net_opts => [] -}) -> {ok, pid()} | {error, any()}. - -start(ID, #{ - ip := IP , - port := Port, - net_opts := NetOpts -} = Params) -> - {Transport, TransportOpts} = get_socket_transport(IP, Port, NetOpts), +-ignore_xref([start/2]). + +-spec start(term(), #{transport => tcp | ssl, + transport_opts => ranch:opts(), + protocol_opts => cowboy:opts(), + logic_handler => module()}) -> + {ok, pid()} | {error, any()}. +start(ID, Params) -> + Transport = maps:get(transport, Params, tcp), + TransportOpts = maps:get(transport_opts, Params, #{}), + ProtocolOpts = maps:get(procotol_opts, Params, #{}), LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), - ExtraOpts = maps:get(cowboy_extra_opts, Params, []), - CowboyOpts = get_cowboy_config(LogicHandler, ExtraOpts), + CowboyOpts = get_cowboy_config(LogicHandler, ProtocolOpts), case Transport of ssl -> cowboy:start_tls(ID, TransportOpts, CowboyOpts); @@ -28,33 +23,17 @@ start(ID, #{ cowboy:start_clear(ID, TransportOpts, CowboyOpts) end. -get_socket_transport(IP, Port, Options) -> - Opts = [ - {ip, IP}, - {port, Port} - ], - case {{packageName}}_utils:get_opt(ssl, Options) of - SslOpts = [_|_] -> - {ssl, Opts ++ SslOpts}; - undefined -> - {tcp, Opts} - end. - get_cowboy_config(LogicHandler, ExtraOpts) -> - get_cowboy_config(LogicHandler, ExtraOpts, get_default_opts(LogicHandler)). - -get_cowboy_config(_LogicHandler, [], Opts) -> - Opts; + DefaultOpts = get_default_opts(LogicHandler), + maps:fold(fun get_cowboy_config/3, DefaultOpts, ExtraOpts). -get_cowboy_config(LogicHandler, [{env, Env} | Rest], Opts) -> - NewEnv = case proplists:get_value(dispatch, Env) of - undefined -> [get_default_dispatch(LogicHandler) | Env]; - _ -> Env - end, - get_cowboy_config(LogicHandler, Rest, store_key(env, NewEnv, Opts)); - -get_cowboy_config(LogicHandler, [{Key, Value}| Rest], Opts) -> - get_cowboy_config(LogicHandler, Rest, store_key(Key, Value, Opts)). +get_cowboy_config(env, #{dispatch := _Dispatch} = Env, AccIn) -> + maps:put(env, Env, AccIn); +get_cowboy_config(env, NewEnv, #{env := OldEnv} = AccIn) -> + Env = maps:merge(OldEnv, NewEnv), + maps:put(env, Env, AccIn); +get_cowboy_config(Key, Value, AccIn) -> + maps:put(Key, Value, AccIn). get_default_dispatch(LogicHandler) -> Paths = {{packageName}}_router:get_paths(LogicHandler), @@ -62,6 +41,3 @@ get_default_dispatch(LogicHandler) -> get_default_opts(LogicHandler) -> #{env => get_default_dispatch(LogicHandler)}. - -store_key(Key, Value, Opts) -> - maps:put(Key, Value, Opts). diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache index af64f34593b3..6809c74c3a77 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateAdapter.kt.mustache @@ -21,36 +21,51 @@ import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.SerialDescriptor {{/kotlinx_serialization}} {{^threetenbp}} +{{^kotlinx-datetime}} import java.time.LocalDate import java.time.format.DateTimeFormatter +{{/kotlinx-datetime}} {{/threetenbp}} {{#threetenbp}} import org.threeten.bp.LocalDate import org.threeten.bp.format.DateTimeFormatter {{/threetenbp}} +{{#kotlinx-datetime}} +import kotlinx.datetime.LocalDate +{{/kotlinx-datetime}} {{#moshi}} {{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateAdapter { @ToJson fun toJson(value: LocalDate): String { + {{#kotlinx-datetime}} + return value.toString() + {{/kotlinx-datetime}} + {{^kotlinx-datetime}} return DateTimeFormatter.ISO_LOCAL_DATE.format(value) + {{/kotlinx-datetime}} } @FromJson fun fromJson(value: String): LocalDate { - return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + return LocalDate.parse(value{{^kotlinx-datetime}}, DateTimeFormatter.ISO_LOCAL_DATE{{/kotlinx-datetime}}) } } {{/moshi}} {{#gson}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE) : TypeAdapter() { +{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateAdapter({{^kotlinx-datetime}}private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE{{/kotlinx-datetime}}) : TypeAdapter() { @Throws(IOException::class) override fun write(out: JsonWriter?, value: LocalDate?) { if (value == null) { out?.nullValue() } else { + {{#kotlinx-datetime}} + out?.value(value.toString()) + {{/kotlinx-datetime}} + {{^kotlinx-datetime}} out?.value(formatter.format(value)) + {{/kotlinx-datetime}} } } @@ -64,13 +79,14 @@ import org.threeten.bp.format.DateTimeFormatter return null } else -> { - return LocalDate.parse(out.nextString(), formatter) + return LocalDate.parse(out.nextString(){{^kotlinx-datetime}}, formatter{{/kotlinx-datetime}}) } } } } {{/gson}} {{#kotlinx_serialization}} +{{^kotlinx-datetime}} @Serializer(forClass = LocalDate::class) {{#nonPublicApi}}internal {{/nonPublicApi}}object LocalDateAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING) @@ -83,4 +99,5 @@ import org.threeten.bp.format.DateTimeFormatter return LocalDate.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE) } } +{{/kotlinx-datetime}} {{/kotlinx_serialization}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache index 96e7168d0b1d..f56cf12d5b77 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache @@ -21,36 +21,51 @@ import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.SerialDescriptor {{/kotlinx_serialization}} {{^threetenbp}} +{{^kotlinx-datetime}} import java.time.LocalDateTime import java.time.format.DateTimeFormatter +{{/kotlinx-datetime}} {{/threetenbp}} {{#threetenbp}} import org.threeten.bp.LocalDateTime import org.threeten.bp.format.DateTimeFormatter {{/threetenbp}} +{{#kotlinx-datetime}} +import kotlinx.datetime.LocalDateTime +{{/kotlinx-datetime}} {{#moshi}} {{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateTimeAdapter { @ToJson fun toJson(value: LocalDateTime): String { + {{#kotlinx-datetime}} + return value.toString() + {{/kotlinx-datetime}} + {{^kotlinx-datetime}} return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) + {{/kotlinx-datetime}} } @FromJson fun fromJson(value: String): LocalDateTime { - return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + return LocalDateTime.parse(value{{^kotlinx-datetime}}, DateTimeFormatter.ISO_LOCAL_DATE_TIME{{/kotlinx-datetime}}) } } {{/moshi}} {{#gson}} -{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateTimeAdapter(private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME) : TypeAdapter() { +{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalDateTimeAdapter({{^kotlinx-datetime}}private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME{{/kotlinx-datetime}}) : TypeAdapter() { @Throws(IOException::class) override fun write(out: JsonWriter?, value: LocalDateTime?) { if (value == null) { out?.nullValue() } else { + {{#kotlinx-datetime}} + out?.value(value.toString()) + {{/kotlinx-datetime}} + {{^kotlinx-datetime}} out?.value(formatter.format(value)) + {{/kotlinx-datetime}} } } @@ -64,13 +79,14 @@ import org.threeten.bp.format.DateTimeFormatter return null } else -> { - return LocalDateTime.parse(out.nextString(), formatter) + return LocalDateTime.parse(out.nextString(){{^kotlinx-datetime}}, formatter{{/kotlinx-datetime}}) } } } } {{/gson}} {{#kotlinx_serialization}} +{{^kotlinx-datetime}} @Serializer(forClass = LocalDateTime::class) {{#nonPublicApi}}internal {{/nonPublicApi}}object LocalDateTimeAdapter : KSerializer { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING) @@ -83,4 +99,5 @@ import org.threeten.bp.format.DateTimeFormatter return LocalDateTime.parse(decoder.decodeString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME) } } +{{/kotlinx-datetime}} {{/kotlinx_serialization}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalTimeAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalTimeAdapter.kt.mustache new file mode 100644 index 000000000000..3a294f8ef7df --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/LocalTimeAdapter.kt.mustache @@ -0,0 +1,56 @@ +package {{packageName}}.infrastructure + +{{#moshi}} +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +{{/moshi}} +{{#gson}} +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import com.google.gson.stream.JsonToken.NULL +import java.io.IOException +{{/gson}} +import kotlinx.datetime.LocalTime + +{{#moshi}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalTimeAdapter { + @ToJson + fun toJson(value: LocalTime): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): LocalTime { + return LocalTime.parse(value) + } + +} +{{/moshi}} +{{#gson}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class LocalTimeAdapter : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: LocalTime?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(value.toString()) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): LocalTime? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return LocalTime.parse(out.nextString()) + } + } + } +} +{{/gson}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache index 57fe58a103f4..6b78b03b7af8 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache @@ -24,13 +24,12 @@ import org.threeten.bp.OffsetDateTime {{/threetenbp}} {{#kotlinx-datetime}} import kotlinx.datetime.Instant +import kotlinx.datetime.LocalTime {{/kotlinx-datetime}} import java.util.UUID {{/gson}} {{#jackson}} -{{#enumUnknownDefaultCase}} import com.fasterxml.jackson.databind.DeserializationFeature -{{/enumUnknownDefaultCase}} import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -66,6 +65,7 @@ import java.util.concurrent.atomic.AtomicLong .add(OffsetDateTimeAdapter()) {{#kotlinx-datetime}} .add(InstantAdapter()) + .add(LocalTimeAdapter()) {{/kotlinx-datetime}} .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) @@ -92,6 +92,7 @@ import java.util.concurrent.atomic.AtomicLong .registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter()) {{#kotlinx-datetime}} .registerTypeAdapter(Instant::class.java, InstantAdapter()) + .registerTypeAdapter(LocalTime::class.java, LocalTimeAdapter()) {{/kotlinx-datetime}} .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) @@ -111,6 +112,7 @@ import java.util.concurrent.atomic.AtomicLong .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) {{/enumUnknownDefaultCase}} .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, {{failOnUnknownProperties}}) {{/jackson}} {{#kotlinx_serialization}} @Deprecated("Use Serializer.kotlinxSerializationAdapters instead", replaceWith = ReplaceWith("Serializer.kotlinxSerializationAdapters")) @@ -122,9 +124,11 @@ import java.util.concurrent.atomic.AtomicLong val kotlinxSerializationAdapters = SerializersModule { contextual(BigDecimal::class, BigDecimalAdapter) contextual(BigInteger::class, BigIntegerAdapter) + {{^kotlinx-datetime}} contextual(LocalDate::class, LocalDateAdapter) contextual(LocalDateTime::class, LocalDateTimeAdapter) contextual(OffsetDateTime::class, OffsetDateTimeAdapter) + {{/kotlinx-datetime}} contextual(UUID::class, UUIDAdapter) contextual(AtomicInteger::class, AtomicIntegerAdapter) contextual(AtomicLong::class, AtomicLongAdapter) diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/exceptions.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/exceptions.mustache index 339e5d08e617..2a133d99d9e4 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/exceptions.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/exceptions.mustache @@ -1,5 +1,6 @@ package {{apiPackage}} +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("{{apiPackage}}.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/model_enum.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/model_enum.mustache index bb8e093f7aad..d0a24379e609 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/model_enum.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/model_enum.mustache @@ -2,8 +2,15 @@ enum {{classname}}: {{vendorExtensions.x-php-enum-type}} { {{#allowableValues}} {{#enumVars}} - case {{^isString}}NUMBER_{{/isString}}{{{name}}} = {{{value}}}; + {{#enumDescription}} + /** + * {{enumDescription}} + */ + {{/enumDescription}} + case {{{name}}} = {{{value}}}; +{{^-last}} +{{/-last}} {{/enumVars}} {{/allowableValues}} } diff --git a/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache b/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache index 9dba64f5345c..962a4cdb2d59 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache @@ -52,7 +52,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}} */ public function getSerialized{{nameInPascalCase}}(): string|null { - return $this->{{name}}?->value ? (string) $this->{{name}}->value : null; + return !is_null($this->{{name}}?->value) ? (string) $this->{{name}}->value : null; } /** diff --git a/modules/openapi-generator/src/main/resources/php/model_enum.mustache b/modules/openapi-generator/src/main/resources/php/model_enum.mustache index 77001f2e6058..86d022506db8 100644 --- a/modules/openapi-generator/src/main/resources/php/model_enum.mustache +++ b/modules/openapi-generator/src/main/resources/php/model_enum.mustache @@ -5,7 +5,12 @@ class {{classname}} */ {{#allowableValues}} {{#enumVars}} - public const {{^isString}}NUMBER_{{/isString}}{{{name}}} = {{{value}}}; + {{#enumDescription}} + /** + * {{enumDescription}} + */ + {{/enumDescription}} + public const {{{name}}} = {{{value}}}; {{/enumVars}} {{/allowableValues}} @@ -18,7 +23,7 @@ class {{classname}} return [ {{#allowableValues}} {{#enumVars}} - self::{{^isString}}NUMBER_{{/isString}}{{{name}}}{{^-last}}, + self::{{{name}}}{{^-last}}, {{/-last}} {{/enumVars}} {{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/model_anyof.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/model_anyof.mustache index 0d575011b268..b145f73ad13b 100644 --- a/modules/openapi-generator/src/main/resources/python-fastapi/model_anyof.mustache +++ b/modules/openapi-generator/src/main/resources/python-fastapi/model_anyof.mustache @@ -176,7 +176,8 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} if callable(to_json): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + # primitive type + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache index c97788d0c5cc..9be766ce5771 100644 --- a/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache @@ -143,6 +143,11 @@ class RESTClientObject: filename=v[0], content_type=v[2]) else: + # Ensures that dict objects are serialized + if isinstance(v, dict): + v = json.dumps(v) + elif isinstance(v, int): + v = str(v) data.add_field(k, v) args["data"] = data diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/model_anyof.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/model_anyof.mustache index adec7c418683..e76bd81c46d1 100644 --- a/modules/openapi-generator/src/main/resources/python-pydantic-v1/model_anyof.mustache +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/model_anyof.mustache @@ -166,7 +166,8 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} if callable(to_json): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + # primitive type + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache index 1d6d255d2cd5..845324e199b8 100644 --- a/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache @@ -190,6 +190,8 @@ class RESTClientObject: # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] r = self.pool_manager.request( method, url, fields=post_params, diff --git a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache index c3f8643687ab..9da1091f4f08 100644 --- a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache @@ -174,6 +174,11 @@ class RESTClientObject: content_type=v[2] ) else: + # Ensures that dict objects are serialized + if isinstance(v, dict): + v = json.dumps(v) + elif isinstance(v, int): + v = str(v) data.add_field(k, v) args["data"] = data @@ -198,8 +203,3 @@ class RESTClientObject: r = await pool_manager.request(**args) return RESTResponse(r) - - - - - diff --git a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache index 6d59f14e753c..92d0d1f95af7 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache @@ -155,9 +155,12 @@ extension KeyedEncodingContainerProtocol { } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encode(_ value: Decimal, forKey key: Self.Key) throws { - var mutableValue = value - let stringValue = NSDecimalString(&mutableValue, Locale(identifier: "en_US")) - try encode(stringValue, forKey: key) + let decimalNumber = NSDecimalNumber(decimal: value) + let numberFormatter = NumberFormatter() + numberFormatter.numberStyle = .decimal + numberFormatter.locale = Locale(identifier: "en_US") + let formattedString = numberFormatter.string(from: decimalNumber) ?? "\(value)" + try encode(formattedString, forKey: key) } {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws { diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache index e18f5c09859b..9f5b6b3323e1 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/modelEnum.mustache @@ -1,7 +1,7 @@ /** * {{{description}}} * @export - * @enum {string} + * @enum {{=<% %>=}}{<%&dataType%>}<%={{ }}=%> */ {{#isBoolean}} export type {{classname}} = {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}} | {{/-last}}{{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java index 6fa9b0ee2a3d..0f3945d8c0a7 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java @@ -90,7 +90,7 @@ private static CodegenConfigurator createDefaultCodegenConfigurator(File output) .setGeneratorName("go-gin-server") .setGitUserId("my-user") .setGitRepoId("my-repo") - .setPackageName("my-package") + .setPackageName("mypackage") .setOutputDir(output.getAbsolutePath().replace("\\", "/")); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/goserver/GoServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/goserver/GoServerCodegenTest.java new file mode 100644 index 000000000000..f573a8ef0f5a --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/goserver/GoServerCodegenTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.goserver; + +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +public class GoServerCodegenTest { + + @Test + public void verifyGoMod() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = createDefaultCodegenConfigurator(output) + .setInputSpec("src/test/resources/3_0/go-server/route-order.yaml"); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + files.forEach(File::deleteOnExit); + + TestUtils.assertFileExists(Paths.get(output + "/go.mod")); + TestUtils.assertFileContains(Paths.get(output + "/go.mod"), + "module github.com/my-user/my-repo"); + TestUtils.assertFileContains(Paths.get(output + "/go.mod"), + "require github.com/gorilla/mux v1.8.0"); + } + + @Test + public void verifyOrder() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = createDefaultCodegenConfigurator(output) + .setInputSpec("src/test/resources/3_0/go-server/route-order.yaml"); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + files.forEach(File::deleteOnExit); + + TestUtils.assertFileExists(Paths.get(output + "/go/routers.go")); + TestUtils.assertFileContains(Paths.get(output + "/go/routers.go"), + "type Routes map[string]Route"); + + TestUtils.assertFileExists(Paths.get(output + "/go/api_dev.go")); + // verify /getPath/latest is first route + Assert.assertEquals(Files.readAllLines(Paths.get(output + "/go/api_dev.go")).get(52), "\t\t\"GetLatest\": Route{"); + // verify /getPath/{id} is second route + Assert.assertEquals(Files.readAllLines(Paths.get(output + "/go/api_dev.go")).get(57), "\t\t\"GetById\": Route{"); + + } + + private static CodegenConfigurator createDefaultCodegenConfigurator(File output) { + return new CodegenConfigurator() + .setGeneratorName("go-server") + .setGitUserId("my-user") + .setGitRepoId("my-repo") + .setPackageName("mypackage") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + } + +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java index 0b4832d7942e..9bdbfcb4b544 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/KotlinClientCodegenModelTest.java @@ -34,6 +34,7 @@ import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.KotlinClientCodegen; +import org.openapitools.codegen.testutils.ConfigAssert; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -406,6 +407,32 @@ public void testOmitGradleWrapperDoesNotGenerateWrapper() throws IOException { TestUtils.assertFileNotExists(Paths.get(path, "gradle", "wrapper", "gradle-wrapper.jar")); } + @Test + public void testFailOnUnknownPropertiesAdditionalProperty() { + final KotlinClientCodegen codegen = new KotlinClientCodegen(); + + // Default case, nothing provided + codegen.processOpts(); + + ConfigAssert configAssert = new ConfigAssert(codegen.additionalProperties()); + // Default to false + configAssert.assertValue(KotlinClientCodegen.FAIL_ON_UNKNOWN_PROPERTIES, codegen::isFailOnUnknownProperties, Boolean.FALSE); + + // Provide true + codegen.additionalProperties().put(KotlinClientCodegen.FAIL_ON_UNKNOWN_PROPERTIES, true); + codegen.processOpts(); + + // Should be true + configAssert.assertValue(KotlinClientCodegen.FAIL_ON_UNKNOWN_PROPERTIES, codegen::isFailOnUnknownProperties, Boolean.TRUE); + + // Provide false + codegen.additionalProperties().put(KotlinClientCodegen.FAIL_ON_UNKNOWN_PROPERTIES, false); + codegen.processOpts(); + + // Should be false + configAssert.assertValue(KotlinClientCodegen.FAIL_ON_UNKNOWN_PROPERTIES, codegen::isFailOnUnknownProperties, Boolean.FALSE); + } + private static class ModelNameTest { private final String expectedName; private final String expectedClassName; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpModelTest.java index 39b3bb7870e8..d2bc34a33b57 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/php/PhpModelTest.java @@ -348,7 +348,7 @@ public void enumModelValueTest() { Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); HashMap one = new HashMap(); - one.put("name", "1"); + one.put("name", "NUMBER_1"); one.put("value", "1"); one.put("isString", false); HashMap minusOne = new HashMap(); diff --git a/modules/openapi-generator/src/test/resources/3_0/avro-schema/valid-enums.yaml b/modules/openapi-generator/src/test/resources/3_0/avro-schema/valid-enums.yaml new file mode 100644 index 000000000000..d1ebb181647c --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/avro-schema/valid-enums.yaml @@ -0,0 +1,30 @@ +openapi: 3.0.0 +info: + version: 1.0.0 + title: Test for valid enums +paths: + /test: + get: + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Sample' +components: + schemas: + Sample: + properties: + type: + enum: + - 'a' + - 'b' + # This enum is invalid for Avro schemas, as it contains a `-` + - 'uh-oh' + # This next one starts with a number, which is invalid for Avro schemas + - '0h_oh' + # The next two is to make sure collisions are resolved properly + - 'coll-ision' + - 'coll_ision' + type: 'string' \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/go-server/route-order.yaml b/modules/openapi-generator/src/test/resources/3_0/go-server/route-order.yaml new file mode 100644 index 000000000000..fcaf8f39d55c --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/go-server/route-order.yaml @@ -0,0 +1,33 @@ +openapi: 3.0.0 + +info: + version: 1.0.0 + title: Simple no path and body param spec + +paths: + /getPath/latest: + get: + tags: + - dev + summary: summary + description: description + operationId: getLatest + responses: + '204': + description: successful operation + /getPath/{id}: + get: + tags: + - dev + summary: summary + description: description + operationId: GetById + parameters: + - name: id + in: path + required: true + schema: + type: string + responses: + '204': + description: successful operation diff --git a/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml index 433bd56071e8..cebc271e1d5b 100644 --- a/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml @@ -2066,4 +2066,19 @@ components: ArrayRef: type: array items: - type: string \ No newline at end of file + type: string + EnumWithNameAndDescription: + type: integer + enum: + - 1 + - 2 + - 3 + - 4 + x-enum-varnames: + - ONE + - "2" + - " 3" + x-enum-descriptions: + - The word one + - The digit two + - The digit three prefixed by a space diff --git a/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml index 71e9f1525ed7..138e51a2f208 100644 --- a/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml @@ -2076,3 +2076,18 @@ components: type: string type_: type: string + EnumWithNameAndDescription: + type: integer + enum: + - 1 + - 2 + - 3 + - 4 + x-enum-varnames: + - ONE + - "2" + - " 3" + x-enum-descriptions: + - The word one + - The digit two + - The digit three prefixed by a space diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml index e6fc5fbf6fc0..bd071a0b132d 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1552,6 +1552,41 @@ paths: schema: type: string format: byte + /fake/upload_file_with_additional_properties: + post: + tags: + - fake + summary: uploads a file and additional properties using multipart/form-data + description: '' + operationId: uploadFileWithAdditionalProperties + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + file: + description: file to upload + type: string + format: binary + object: + description: Additional object + type: object + properties: + name: + type: string + count: + description: Integer count + type: integer + required: + - file /import_test/return_datetime: get: tags: diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 1a4c1c03365c..a381e6a2f3cf 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/PathApi.java b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/PathApi.java index 7eee07ae3e02..63748db9f33f 100644 --- a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/PathApi.java +++ b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/PathApi.java @@ -92,10 +92,10 @@ public String testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnu // create path and map variables String localVarPath = "/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}" - .replaceAll("\\{" + "path_string" + "\\}", apiClient.escapeString(pathString.toString())) - .replaceAll("\\{" + "path_integer" + "\\}", apiClient.escapeString(pathInteger.toString())) - .replaceAll("\\{" + "enum_nonref_string_path" + "\\}", apiClient.escapeString(enumNonrefStringPath.toString())) - .replaceAll("\\{" + "enum_ref_string_path" + "\\}", apiClient.escapeString(enumRefStringPath.toString())); + .replaceAll("\\{" + "path_string" + "\\}", apiClient.escapeString(apiClient.parameterToString(pathString))) + .replaceAll("\\{" + "path_integer" + "\\}", apiClient.escapeString(apiClient.parameterToString(pathInteger))) + .replaceAll("\\{" + "enum_nonref_string_path" + "\\}", apiClient.escapeString(apiClient.parameterToString(enumNonrefStringPath))) + .replaceAll("\\{" + "enum_ref_string_path" + "\\}", apiClient.escapeString(apiClient.parameterToString(enumRefStringPath))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; diff --git a/samples/client/echo_api/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/echo_api/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 6a09fd57f301..80783430664b 100644 --- a/samples/client/echo_api/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/echo_api/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -13,4 +13,5 @@ object Serializer { .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/echo_api/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/echo_api/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 6a09fd57f301..80783430664b 100644 --- a/samples/client/echo_api/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/echo_api/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -13,4 +13,5 @@ object Serializer { .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/echo_api/php-nextgen-streaming/src/Model/StringEnumRef.php b/samples/client/echo_api/php-nextgen-streaming/src/Model/StringEnumRef.php index 337fc1a3f8d0..8ab408d1baf3 100644 --- a/samples/client/echo_api/php-nextgen-streaming/src/Model/StringEnumRef.php +++ b/samples/client/echo_api/php-nextgen-streaming/src/Model/StringEnumRef.php @@ -42,7 +42,6 @@ enum StringEnumRef: string case FAILURE = 'failure'; case UNCLASSIFIED = 'unclassified'; - } diff --git a/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php b/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php index 337fc1a3f8d0..8ab408d1baf3 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php +++ b/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php @@ -42,7 +42,6 @@ enum StringEnumRef: string case FAILURE = 'failure'; case UNCLASSIFIED = 'unclassified'; - } diff --git a/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py b/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py index f4a710085985..8538f9ee5200 100644 --- a/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py +++ b/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py @@ -201,6 +201,8 @@ def request(self, method, url, query_params=None, headers=None, # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] r = self.pool_manager.request( method, url, fields=post_params, diff --git a/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java index 940798bede50..fc10d6f741da 100644 --- a/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java @@ -1112,7 +1112,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java index 940798bede50..fc10d6f741da 100644 --- a/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java @@ -1112,7 +1112,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/client/petstore/csharp/generichost/net4.7/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.7/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/generichost/net4.7/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.7/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.7/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.7/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/generichost/net4.7/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.7/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.7/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.7/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/generichost/net4.7/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.7/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.7/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.7/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/generichost/net4.7/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.7/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.7/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.7/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/generichost/net4.7/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.7/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/generichost/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/generichost/net4.7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/generichost/net4.8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/generichost/net4.8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/generichost/net4.8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/generichost/net4.8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/generichost/net4.8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/generichost/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net4.8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net4.8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/generichost/net4.8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net4.8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 9c99dddf55f5..05ce7e5830d8 100644 --- a/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2fa1be128ccf..fad95b68dbdd 100644 --- a/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/AllOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -25,8 +25,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 9c99dddf55f5..05ce7e5830d8 100644 --- a/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2fa1be128ccf..fad95b68dbdd 100644 --- a/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/AnyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -25,8 +25,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 9c99dddf55f5..05ce7e5830d8 100644 --- a/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 0c948f147ff4..9f99b6957b6d 100644 --- a/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/AnyOfNoCompare/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -24,8 +24,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 89a319139139..d8ddfad1b40c 100644 --- a/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj index a5ac63f5ad04..d3c06f120ffe 100644 --- a/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/FormModels/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -24,8 +24,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 9c99dddf55f5..05ce7e5830d8 100644 --- a/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2fa1be128ccf..fad95b68dbdd 100644 --- a/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/NullReferenceTypes/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -25,8 +25,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 9c99dddf55f5..05ce7e5830d8 100644 --- a/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2fa1be128ccf..fad95b68dbdd 100644 --- a/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/OneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -25,8 +25,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 89a319139139..d8ddfad1b40c 100644 --- a/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools/Org.OpenAPITools.csproj index a5ac63f5ad04..d3c06f120ffe 100644 --- a/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/Petstore/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -24,8 +24,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 9c99dddf55f5..05ce7e5830d8 100644 --- a/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2fa1be128ccf..fad95b68dbdd 100644 --- a/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/SourceGeneration/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -25,8 +25,8 @@ - - + + diff --git a/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 9c99dddf55f5..05ce7e5830d8 100644 --- a/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 0c948f147ff4..9f99b6957b6d 100644 --- a/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/generichost/net8/UseDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -24,8 +24,8 @@ - - + + diff --git a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 5c6fff45e26c..6e2e462b8a72 100644 --- a/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/restsharp/net4.7/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 66afad92ec4e..a136411ab795 100644 --- a/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/restsharp/net4.8/Petstore/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 1a4c1c03365c..a381e6a2f3cf 100644 --- a/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/restsharp/net6/ParameterMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index c4e70bd0020e..2bd81bb6826e 100644 --- a/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/restsharp/net7/EnumMappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index c4e70bd0020e..2bd81bb6826e 100644 --- a/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/restsharp/net7/UseDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/PetApi.java index 9523dca1711d..27ae144592a4 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/PetApi.java @@ -145,7 +145,7 @@ public void deletePet(Long petId, String apiKey, Map additionalH // create path and map variables String localVarPath = "/pet/{petId}" - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(apiClient.parameterToString(petId))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; @@ -375,7 +375,7 @@ public Pet getPetById(Long petId, Map additionalHeaders) throws // create path and map variables String localVarPath = "/pet/{petId}" - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(apiClient.parameterToString(petId))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; @@ -523,7 +523,7 @@ public void updatePetWithForm(Long petId, String name, String status, Map additionalHeaders) t // create path and map variables String localVarPath = "/store/order/{order_id}" - .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(orderId.toString())); + .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(apiClient.parameterToString(orderId))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; @@ -210,7 +210,7 @@ public Order getOrderById(Long orderId, Map additionalHeaders) t // create path and map variables String localVarPath = "/store/order/{order_id}" - .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(orderId.toString())); + .replaceAll("\\{" + "order_id" + "\\}", apiClient.escapeString(apiClient.parameterToString(orderId))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/UserApi.java index 73e32f24338e..eaa5ed28aa73 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/UserApi.java @@ -283,7 +283,7 @@ public void deleteUser(String username, Map additionalHeaders) t // create path and map variables String localVarPath = "/user/{username}" - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(apiClient.parameterToString(username))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; @@ -357,7 +357,7 @@ public User getUserByName(String username, Map additionalHeaders // create path and map variables String localVarPath = "/user/{username}" - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(apiClient.parameterToString(username))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; @@ -584,7 +584,7 @@ public void updateUser(String username, User user, Map additiona // create path and map variables String localVarPath = "/user/{username}" - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(apiClient.parameterToString(username))); StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); String localVarQueryParameterBaseName; diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java index 9148712ff91e..3c62b72c7d56 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java @@ -1269,7 +1269,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index 9148712ff91e..3c62b72c7d56 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -1269,7 +1269,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java index abcae1372273..1953e974bd2e 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java @@ -1351,7 +1351,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 6a09fd57f301..80783430664b 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -13,4 +13,5 @@ object Serializer { .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 6a09fd57f301..80783430664b 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -13,4 +13,5 @@ object Serializer { .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 6a09fd57f301..80783430664b 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -13,4 +13,5 @@ object Serializer { .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 6a09fd57f301..80783430664b 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -13,4 +13,5 @@ object Serializer { .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index 6a09fd57f301..80783430664b 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -13,4 +13,5 @@ object Serializer { .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index ece5c413e124..3fc7935a7bf6 100644 --- a/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,5 +1,6 @@ package org.openapitools.client.infrastructure +import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -11,4 +12,5 @@ object Serializer { .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/kotlin-jvm-vertx-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-vertx-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index ece5c413e124..3fc7935a7bf6 100644 --- a/samples/client/petstore/kotlin-jvm-vertx-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-vertx-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,5 +1,6 @@ package org.openapitools.client.infrastructure +import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -11,4 +12,5 @@ object Serializer { .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/FILES b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/FILES index b3104c03efb1..28c33db4a551 100644 --- a/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/FILES +++ b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/FILES @@ -27,6 +27,7 @@ src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt src/main/kotlin/org/openapitools/client/infrastructure/InstantAdapter.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/LocalTimeAdapter.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 diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt index b2e1654479a0..505108715e4c 100644 --- a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -2,18 +2,17 @@ package org.openapitools.client.infrastructure import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson -import java.time.LocalDate -import java.time.format.DateTimeFormatter +import kotlinx.datetime.LocalDate class LocalDateAdapter { @ToJson fun toJson(value: LocalDate): String { - return DateTimeFormatter.ISO_LOCAL_DATE.format(value) + return value.toString() } @FromJson fun fromJson(value: String): LocalDate { - return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + return LocalDate.parse(value) } } diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt index e082db94811d..aa8f3907d0d3 100644 --- a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -2,18 +2,17 @@ package org.openapitools.client.infrastructure import com.squareup.moshi.FromJson import com.squareup.moshi.ToJson -import java.time.LocalDateTime -import java.time.format.DateTimeFormatter +import kotlinx.datetime.LocalDateTime class LocalDateTimeAdapter { @ToJson fun toJson(value: LocalDateTime): String { - return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) + return value.toString() } @FromJson fun fromJson(value: String): LocalDateTime { - return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + return LocalDateTime.parse(value) } } diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalTimeAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalTimeAdapter.kt new file mode 100644 index 000000000000..7c97c1b8b13b --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalTimeAdapter.kt @@ -0,0 +1,18 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import kotlinx.datetime.LocalTime + +class LocalTimeAdapter { + @ToJson + fun toJson(value: LocalTime): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): LocalTime { + return LocalTime.parse(value) + } + +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index d191eb67d45d..2e8f453125ba 100644 --- a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -8,6 +8,7 @@ object Serializer { val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(OffsetDateTimeAdapter()) .add(InstantAdapter()) + .add(LocalTimeAdapter()) .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index ece5c413e124..3fc7935a7bf6 100644 --- a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,5 +1,6 @@ package org.openapitools.client.infrastructure +import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -11,4 +12,5 @@ object Serializer { .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/FILES b/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/FILES index ec822fdd8838..ebd39c9d9de9 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/FILES +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/FILES @@ -29,6 +29,7 @@ docs/Model/Dog.md docs/Model/EnumArrays.md docs/Model/EnumClass.md docs/Model/EnumTest.md +docs/Model/EnumWithNameAndDescription.md docs/Model/FakeBigDecimalMap200Response.md docs/Model/File.md docs/Model/FileSchemaTestClass.md @@ -91,6 +92,7 @@ src/Model/Dog.php src/Model/EnumArrays.php src/Model/EnumClass.php src/Model/EnumTest.php +src/Model/EnumWithNameAndDescription.php src/Model/FakeBigDecimalMap200Response.php src/Model/File.php src/Model/FileSchemaTestClass.php diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.php_cs b/samples/client/petstore/php-nextgen/OpenAPIClient-php/.php_cs deleted file mode 100644 index 4fbe53ec5ff1..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.php_cs +++ /dev/null @@ -1,23 +0,0 @@ -setUsingCache(true) - ->setRules([ - '@PSR2' => true, - 'ordered_imports' => 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, - ]) - ->setFinder( - PhpCsFixer\Finder::create() - ->exclude('test') - ->exclude('tests') - ->in(__DIR__) - ); diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.phplint.dist.yml b/samples/client/petstore/php-nextgen/OpenAPIClient-php/.phplint.dist.yml deleted file mode 100644 index 2c81c7a43080..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.phplint.dist.yml +++ /dev/null @@ -1,12 +0,0 @@ -path: - - ./lib - - ./test - - ./tests -jobs: 10 -extensions: - - php -exclude: - - vendor -warning: true -memory-limit: -1 -no-cache: true diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md b/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md index a9cdc4b822c7..6b60abeee5f9 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md @@ -138,6 +138,7 @@ Class | Method | HTTP request | Description - [EnumArrays](docs/Model/EnumArrays.md) - [EnumClass](docs/Model/EnumClass.md) - [EnumTest](docs/Model/EnumTest.md) +- [EnumWithNameAndDescription](docs/Model/EnumWithNameAndDescription.md) - [FakeBigDecimalMap200Response](docs/Model/FakeBigDecimalMap200Response.md) - [File](docs/Model/File.md) - [FileSchemaTestClass](docs/Model/FileSchemaTestClass.md) diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/DogAllOf.md b/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/EnumWithNameAndDescription.md similarity index 82% rename from samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/DogAllOf.md rename to samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/EnumWithNameAndDescription.md index 88effd4297bc..ab03446144aa 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/DogAllOf.md +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/EnumWithNameAndDescription.md @@ -1,9 +1,8 @@ -# # DogAllOf +# # EnumWithNameAndDescription ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**breed** | **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-nextgen/OpenAPIClient-php/lib/Api/AnotherFakeApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/AnotherFakeApi.php deleted file mode 100644 index 713a4944f64f..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/AnotherFakeApi.php +++ /dev/null @@ -1,425 +0,0 @@ - [ - 'application/json', - ], - ]; - -/** - * @param ClientInterface $client - * @param Configuration $config - * @param HeaderSelector $selector - * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec - */ - public function __construct( - ClientInterface $client = null, - Configuration $config = null, - HeaderSelector $selector = null, - $hostIndex = 0 - ) { - $this->client = $client ?: new Client(); - $this->config = $config ?: new Configuration(); - $this->headerSelector = $selector ?: new HeaderSelector(); - $this->hostIndex = $hostIndex; - } - - /** - * Set the host index - * - * @param int $hostIndex Host index (required) - */ - public function setHostIndex($hostIndex): void - { - $this->hostIndex = $hostIndex; - } - - /** - * Get the host index - * - * @return int Host index - */ - public function getHostIndex() - { - return $this->hostIndex; - } - - /** - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Operation call123TestSpecialTags - * - * To test special tags - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Client - */ - public function call123TestSpecialTags($client, string $contentType = self::contentTypes['call123TestSpecialTags'][0]) - { - list($response) = $this->call123TestSpecialTagsWithHttpInfo($client, $contentType); - return $response; - } - - /** - * Operation call123TestSpecialTagsWithHttpInfo - * - * To test special tags - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) - */ - public function call123TestSpecialTagsWithHttpInfo($client, string $contentType = self::contentTypes['call123TestSpecialTags'][0]) - { - $request = $this->call123TestSpecialTagsRequest($client, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Client'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Client', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation call123TestSpecialTagsAsync - * - * To test special tags - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function call123TestSpecialTagsAsync($client, string $contentType = self::contentTypes['call123TestSpecialTags'][0]) - { - return $this->call123TestSpecialTagsAsyncWithHttpInfo($client, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation call123TestSpecialTagsAsyncWithHttpInfo - * - * To test special tags - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function call123TestSpecialTagsAsyncWithHttpInfo($client, string $contentType = self::contentTypes['call123TestSpecialTags'][0]) - { - $returnType = '\OpenAPI\Client\Model\Client'; - $request = $this->call123TestSpecialTagsRequest($client, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'call123TestSpecialTags' - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function call123TestSpecialTagsRequest($client, string $contentType = self::contentTypes['call123TestSpecialTags'][0]) - { - - // verify the required parameter 'client' is set - if ($client === null || (is_array($client) && count($client) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $client when calling call123TestSpecialTags' - ); - } - - - $resourcePath = '/another-fake/dummy'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($client)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($client)); - } else { - $httpBody = $client; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PATCH', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Create http client option - * - * @throws \RuntimeException on file opening failure - * @return array of http client options - */ - protected function createHttpClientOption() - { - $options = []; - if ($this->config->getDebug()) { - $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); - if (!$options[RequestOptions::DEBUG]) { - throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); - } - } - - return $options; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/DefaultApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/DefaultApi.php deleted file mode 100644 index 834ef80ffb1c..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/DefaultApi.php +++ /dev/null @@ -1,398 +0,0 @@ - [ - 'application/json', - ], - ]; - -/** - * @param ClientInterface $client - * @param Configuration $config - * @param HeaderSelector $selector - * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec - */ - public function __construct( - ClientInterface $client = null, - Configuration $config = null, - HeaderSelector $selector = null, - $hostIndex = 0 - ) { - $this->client = $client ?: new Client(); - $this->config = $config ?: new Configuration(); - $this->headerSelector = $selector ?: new HeaderSelector(); - $this->hostIndex = $hostIndex; - } - - /** - * Set the host index - * - * @param int $hostIndex Host index (required) - */ - public function setHostIndex($hostIndex): void - { - $this->hostIndex = $hostIndex; - } - - /** - * Get the host index - * - * @return int Host index - */ - public function getHostIndex() - { - return $this->hostIndex; - } - - /** - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Operation fooGet - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\FooGetDefaultResponse - */ - public function fooGet(string $contentType = self::contentTypes['fooGet'][0]) - { - list($response) = $this->fooGetWithHttpInfo($contentType); - return $response; - } - - /** - * Operation fooGetWithHttpInfo - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\FooGetDefaultResponse, HTTP status code, HTTP response headers (array of strings) - */ - public function fooGetWithHttpInfo(string $contentType = self::contentTypes['fooGet'][0]) - { - $request = $this->fooGetRequest($contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - default: - if ('\OpenAPI\Client\Model\FooGetDefaultResponse' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\FooGetDefaultResponse' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\FooGetDefaultResponse', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\FooGetDefaultResponse'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - default: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\FooGetDefaultResponse', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation fooGetAsync - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fooGetAsync(string $contentType = self::contentTypes['fooGet'][0]) - { - return $this->fooGetAsyncWithHttpInfo($contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fooGetAsyncWithHttpInfo - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fooGetAsyncWithHttpInfo(string $contentType = self::contentTypes['fooGet'][0]) - { - $returnType = '\OpenAPI\Client\Model\FooGetDefaultResponse'; - $request = $this->fooGetRequest($contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fooGet' - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fooGetRequest(string $contentType = self::contentTypes['fooGet'][0]) - { - - - $resourcePath = '/foo'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Create http client option - * - * @throws \RuntimeException on file opening failure - * @return array of http client options - */ - protected function createHttpClientOption() - { - $options = []; - if ($this->config->getDebug()) { - $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); - if (!$options[RequestOptions::DEBUG]) { - throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); - } - } - - return $options; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/FakeApi.php deleted file mode 100644 index 6e5344684c48..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/FakeApi.php +++ /dev/null @@ -1,4908 +0,0 @@ - [ - 'application/json', - ], - 'fakeHttpSignatureTest' => [ - 'application/json', - 'application/xml', - ], - 'fakeOuterBooleanSerialize' => [ - 'application/json', - ], - 'fakeOuterCompositeSerialize' => [ - 'application/json', - ], - 'fakeOuterNumberSerialize' => [ - 'application/json', - ], - 'fakeOuterStringSerialize' => [ - 'application/json', - ], - 'fakePropertyEnumIntegerSerialize' => [ - 'application/json', - ], - 'testBodyWithBinary' => [ - 'image/png', - ], - 'testBodyWithFileSchema' => [ - 'application/json', - ], - 'testBodyWithQueryParams' => [ - 'application/json', - ], - 'testClientModel' => [ - 'application/json', - ], - 'testEndpointParameters' => [ - 'application/x-www-form-urlencoded', - ], - 'testEnumParameters' => [ - 'application/x-www-form-urlencoded', - ], - 'testGroupParameters' => [ - 'application/json', - ], - 'testInlineAdditionalProperties' => [ - 'application/json', - ], - 'testJsonFormData' => [ - 'application/x-www-form-urlencoded', - ], - 'testQueryParameterCollectionFormat' => [ - 'application/json', - ], - ]; - -/** - * @param ClientInterface $client - * @param Configuration $config - * @param HeaderSelector $selector - * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec - */ - public function __construct( - ClientInterface $client = null, - Configuration $config = null, - HeaderSelector $selector = null, - $hostIndex = 0 - ) { - $this->client = $client ?: new Client(); - $this->config = $config ?: new Configuration(); - $this->headerSelector = $selector ?: new HeaderSelector(); - $this->hostIndex = $hostIndex; - } - - /** - * Set the host index - * - * @param int $hostIndex Host index (required) - */ - public function setHostIndex($hostIndex): void - { - $this->hostIndex = $hostIndex; - } - - /** - * Get the host index - * - * @return int Host index - */ - public function getHostIndex() - { - return $this->hostIndex; - } - - /** - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Operation fakeHealthGet - * - * Health check endpoint - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\HealthCheckResult - */ - public function fakeHealthGet(string $contentType = self::contentTypes['fakeHealthGet'][0]) - { - list($response) = $this->fakeHealthGetWithHttpInfo($contentType); - return $response; - } - - /** - * Operation fakeHealthGetWithHttpInfo - * - * Health check endpoint - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\HealthCheckResult, HTTP status code, HTTP response headers (array of strings) - */ - public function fakeHealthGetWithHttpInfo(string $contentType = self::contentTypes['fakeHealthGet'][0]) - { - $request = $this->fakeHealthGetRequest($contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\HealthCheckResult' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\HealthCheckResult' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\HealthCheckResult', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\HealthCheckResult'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\HealthCheckResult', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation fakeHealthGetAsync - * - * Health check endpoint - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeHealthGetAsync(string $contentType = self::contentTypes['fakeHealthGet'][0]) - { - return $this->fakeHealthGetAsyncWithHttpInfo($contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fakeHealthGetAsyncWithHttpInfo - * - * Health check endpoint - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeHealthGetAsyncWithHttpInfo(string $contentType = self::contentTypes['fakeHealthGet'][0]) - { - $returnType = '\OpenAPI\Client\Model\HealthCheckResult'; - $request = $this->fakeHealthGetRequest($contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fakeHealthGet' - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fakeHealthGetRequest(string $contentType = self::contentTypes['fakeHealthGet'][0]) - { - - - $resourcePath = '/fake/health'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation fakeHttpSignatureTest - * - * test http signature authentication - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param string $query_1 query parameter (optional) - * @param string $header_1 header parameter (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function fakeHttpSignatureTest($pet, $query_1 = null, $header_1 = null, string $contentType = self::contentTypes['fakeHttpSignatureTest'][0]) - { - $this->fakeHttpSignatureTestWithHttpInfo($pet, $query_1, $header_1, $contentType); - } - - /** - * Operation fakeHttpSignatureTestWithHttpInfo - * - * test http signature authentication - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param string $query_1 query parameter (optional) - * @param string $header_1 header parameter (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function fakeHttpSignatureTestWithHttpInfo($pet, $query_1 = null, $header_1 = null, string $contentType = self::contentTypes['fakeHttpSignatureTest'][0]) - { - $request = $this->fakeHttpSignatureTestRequest($pet, $query_1, $header_1, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation fakeHttpSignatureTestAsync - * - * test http signature authentication - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param string $query_1 query parameter (optional) - * @param string $header_1 header parameter (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeHttpSignatureTestAsync($pet, $query_1 = null, $header_1 = null, string $contentType = self::contentTypes['fakeHttpSignatureTest'][0]) - { - return $this->fakeHttpSignatureTestAsyncWithHttpInfo($pet, $query_1, $header_1, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fakeHttpSignatureTestAsyncWithHttpInfo - * - * test http signature authentication - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param string $query_1 query parameter (optional) - * @param string $header_1 header parameter (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeHttpSignatureTestAsyncWithHttpInfo($pet, $query_1 = null, $header_1 = null, string $contentType = self::contentTypes['fakeHttpSignatureTest'][0]) - { - $returnType = ''; - $request = $this->fakeHttpSignatureTestRequest($pet, $query_1, $header_1, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fakeHttpSignatureTest' - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param string $query_1 query parameter (optional) - * @param string $header_1 header parameter (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fakeHttpSignatureTestRequest($pet, $query_1 = null, $header_1 = null, string $contentType = self::contentTypes['fakeHttpSignatureTest'][0]) - { - - // verify the required parameter 'pet' is set - if ($pet === null || (is_array($pet) && count($pet) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet when calling fakeHttpSignatureTest' - ); - } - - - - - $resourcePath = '/fake/http-signature-test'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $query_1, - 'query_1', // param base name - 'string', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - - // header params - if ($header_1 !== null) { - $headerParams['header_1'] = ObjectSerializer::toHeaderValue($header_1); - } - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($pet)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($pet)); - } else { - $httpBody = $pet; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation fakeOuterBooleanSerialize - * - * @param bool $body Input boolean as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return bool - */ - public function fakeOuterBooleanSerialize($body = null, string $contentType = self::contentTypes['fakeOuterBooleanSerialize'][0]) - { - list($response) = $this->fakeOuterBooleanSerializeWithHttpInfo($body, $contentType); - return $response; - } - - /** - * Operation fakeOuterBooleanSerializeWithHttpInfo - * - * @param bool $body Input boolean as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of bool, HTTP status code, HTTP response headers (array of strings) - */ - public function fakeOuterBooleanSerializeWithHttpInfo($body = null, string $contentType = self::contentTypes['fakeOuterBooleanSerialize'][0]) - { - $request = $this->fakeOuterBooleanSerializeRequest($body, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('bool' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('bool' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, 'bool', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = 'bool'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - 'bool', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation fakeOuterBooleanSerializeAsync - * - * @param bool $body Input boolean as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterBooleanSerializeAsync($body = null, string $contentType = self::contentTypes['fakeOuterBooleanSerialize'][0]) - { - return $this->fakeOuterBooleanSerializeAsyncWithHttpInfo($body, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fakeOuterBooleanSerializeAsyncWithHttpInfo - * - * @param bool $body Input boolean as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterBooleanSerializeAsyncWithHttpInfo($body = null, string $contentType = self::contentTypes['fakeOuterBooleanSerialize'][0]) - { - $returnType = 'bool'; - $request = $this->fakeOuterBooleanSerializeRequest($body, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fakeOuterBooleanSerialize' - * - * @param bool $body Input boolean as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fakeOuterBooleanSerializeRequest($body = null, string $contentType = self::contentTypes['fakeOuterBooleanSerialize'][0]) - { - - - - $resourcePath = '/fake/outer/boolean'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['*/*', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($body)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); - } else { - $httpBody = $body; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation fakeOuterCompositeSerialize - * - * @param \OpenAPI\Client\Model\OuterComposite $outer_composite Input composite as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\OuterComposite - */ - public function fakeOuterCompositeSerialize($outer_composite = null, string $contentType = self::contentTypes['fakeOuterCompositeSerialize'][0]) - { - list($response) = $this->fakeOuterCompositeSerializeWithHttpInfo($outer_composite, $contentType); - return $response; - } - - /** - * Operation fakeOuterCompositeSerializeWithHttpInfo - * - * @param \OpenAPI\Client\Model\OuterComposite $outer_composite Input composite as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\OuterComposite, HTTP status code, HTTP response headers (array of strings) - */ - public function fakeOuterCompositeSerializeWithHttpInfo($outer_composite = null, string $contentType = self::contentTypes['fakeOuterCompositeSerialize'][0]) - { - $request = $this->fakeOuterCompositeSerializeRequest($outer_composite, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\OuterComposite' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\OuterComposite' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\OuterComposite', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\OuterComposite'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\OuterComposite', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation fakeOuterCompositeSerializeAsync - * - * @param \OpenAPI\Client\Model\OuterComposite $outer_composite Input composite as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterCompositeSerializeAsync($outer_composite = null, string $contentType = self::contentTypes['fakeOuterCompositeSerialize'][0]) - { - return $this->fakeOuterCompositeSerializeAsyncWithHttpInfo($outer_composite, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fakeOuterCompositeSerializeAsyncWithHttpInfo - * - * @param \OpenAPI\Client\Model\OuterComposite $outer_composite Input composite as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterCompositeSerializeAsyncWithHttpInfo($outer_composite = null, string $contentType = self::contentTypes['fakeOuterCompositeSerialize'][0]) - { - $returnType = '\OpenAPI\Client\Model\OuterComposite'; - $request = $this->fakeOuterCompositeSerializeRequest($outer_composite, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fakeOuterCompositeSerialize' - * - * @param \OpenAPI\Client\Model\OuterComposite $outer_composite Input composite as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fakeOuterCompositeSerializeRequest($outer_composite = null, string $contentType = self::contentTypes['fakeOuterCompositeSerialize'][0]) - { - - - - $resourcePath = '/fake/outer/composite'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['*/*', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($outer_composite)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($outer_composite)); - } else { - $httpBody = $outer_composite; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation fakeOuterNumberSerialize - * - * @param float $body Input number as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return float - */ - public function fakeOuterNumberSerialize($body = null, string $contentType = self::contentTypes['fakeOuterNumberSerialize'][0]) - { - list($response) = $this->fakeOuterNumberSerializeWithHttpInfo($body, $contentType); - return $response; - } - - /** - * Operation fakeOuterNumberSerializeWithHttpInfo - * - * @param float $body Input number as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of float, HTTP status code, HTTP response headers (array of strings) - */ - public function fakeOuterNumberSerializeWithHttpInfo($body = null, string $contentType = self::contentTypes['fakeOuterNumberSerialize'][0]) - { - $request = $this->fakeOuterNumberSerializeRequest($body, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('float' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('float' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, 'float', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = 'float'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - 'float', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation fakeOuterNumberSerializeAsync - * - * @param float $body Input number as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterNumberSerializeAsync($body = null, string $contentType = self::contentTypes['fakeOuterNumberSerialize'][0]) - { - return $this->fakeOuterNumberSerializeAsyncWithHttpInfo($body, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fakeOuterNumberSerializeAsyncWithHttpInfo - * - * @param float $body Input number as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterNumberSerializeAsyncWithHttpInfo($body = null, string $contentType = self::contentTypes['fakeOuterNumberSerialize'][0]) - { - $returnType = 'float'; - $request = $this->fakeOuterNumberSerializeRequest($body, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fakeOuterNumberSerialize' - * - * @param float $body Input number as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fakeOuterNumberSerializeRequest($body = null, string $contentType = self::contentTypes['fakeOuterNumberSerialize'][0]) - { - - - - $resourcePath = '/fake/outer/number'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['*/*', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($body)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); - } else { - $httpBody = $body; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation fakeOuterStringSerialize - * - * @param string $body Input string as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return string - */ - public function fakeOuterStringSerialize($body = null, string $contentType = self::contentTypes['fakeOuterStringSerialize'][0]) - { - list($response) = $this->fakeOuterStringSerializeWithHttpInfo($body, $contentType); - return $response; - } - - /** - * Operation fakeOuterStringSerializeWithHttpInfo - * - * @param string $body Input string as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of string, HTTP status code, HTTP response headers (array of strings) - */ - public function fakeOuterStringSerializeWithHttpInfo($body = null, string $contentType = self::contentTypes['fakeOuterStringSerialize'][0]) - { - $request = $this->fakeOuterStringSerializeRequest($body, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('string' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('string' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, 'string', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = 'string'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - 'string', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation fakeOuterStringSerializeAsync - * - * @param string $body Input string as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterStringSerializeAsync($body = null, string $contentType = self::contentTypes['fakeOuterStringSerialize'][0]) - { - return $this->fakeOuterStringSerializeAsyncWithHttpInfo($body, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fakeOuterStringSerializeAsyncWithHttpInfo - * - * @param string $body Input string as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakeOuterStringSerializeAsyncWithHttpInfo($body = null, string $contentType = self::contentTypes['fakeOuterStringSerialize'][0]) - { - $returnType = 'string'; - $request = $this->fakeOuterStringSerializeRequest($body, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fakeOuterStringSerialize' - * - * @param string $body Input string as post body (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fakeOuterStringSerializeRequest($body = null, string $contentType = self::contentTypes['fakeOuterStringSerialize'][0]) - { - - - - $resourcePath = '/fake/outer/string'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['*/*', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($body)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); - } else { - $httpBody = $body; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation fakePropertyEnumIntegerSerialize - * - * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\OuterObjectWithEnumProperty - */ - public function fakePropertyEnumIntegerSerialize($outer_object_with_enum_property, string $contentType = self::contentTypes['fakePropertyEnumIntegerSerialize'][0]) - { - list($response) = $this->fakePropertyEnumIntegerSerializeWithHttpInfo($outer_object_with_enum_property, $contentType); - return $response; - } - - /** - * Operation fakePropertyEnumIntegerSerializeWithHttpInfo - * - * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\OuterObjectWithEnumProperty, HTTP status code, HTTP response headers (array of strings) - */ - public function fakePropertyEnumIntegerSerializeWithHttpInfo($outer_object_with_enum_property, string $contentType = self::contentTypes['fakePropertyEnumIntegerSerialize'][0]) - { - $request = $this->fakePropertyEnumIntegerSerializeRequest($outer_object_with_enum_property, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\OuterObjectWithEnumProperty' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\OuterObjectWithEnumProperty' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\OuterObjectWithEnumProperty', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\OuterObjectWithEnumProperty'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\OuterObjectWithEnumProperty', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation fakePropertyEnumIntegerSerializeAsync - * - * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakePropertyEnumIntegerSerializeAsync($outer_object_with_enum_property, string $contentType = self::contentTypes['fakePropertyEnumIntegerSerialize'][0]) - { - return $this->fakePropertyEnumIntegerSerializeAsyncWithHttpInfo($outer_object_with_enum_property, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation fakePropertyEnumIntegerSerializeAsyncWithHttpInfo - * - * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function fakePropertyEnumIntegerSerializeAsyncWithHttpInfo($outer_object_with_enum_property, string $contentType = self::contentTypes['fakePropertyEnumIntegerSerialize'][0]) - { - $returnType = '\OpenAPI\Client\Model\OuterObjectWithEnumProperty'; - $request = $this->fakePropertyEnumIntegerSerializeRequest($outer_object_with_enum_property, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'fakePropertyEnumIntegerSerialize' - * - * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function fakePropertyEnumIntegerSerializeRequest($outer_object_with_enum_property, string $contentType = self::contentTypes['fakePropertyEnumIntegerSerialize'][0]) - { - - // verify the required parameter 'outer_object_with_enum_property' is set - if ($outer_object_with_enum_property === null || (is_array($outer_object_with_enum_property) && count($outer_object_with_enum_property) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $outer_object_with_enum_property when calling fakePropertyEnumIntegerSerialize' - ); - } - - - $resourcePath = '/fake/property/enum-int'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['*/*', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($outer_object_with_enum_property)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($outer_object_with_enum_property)); - } else { - $httpBody = $outer_object_with_enum_property; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testBodyWithBinary - * - * @param \SplFileObject $body image to upload (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testBodyWithBinary($body, string $contentType = self::contentTypes['testBodyWithBinary'][0]) - { - $this->testBodyWithBinaryWithHttpInfo($body, $contentType); - } - - /** - * Operation testBodyWithBinaryWithHttpInfo - * - * @param \SplFileObject $body image to upload (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testBodyWithBinaryWithHttpInfo($body, string $contentType = self::contentTypes['testBodyWithBinary'][0]) - { - $request = $this->testBodyWithBinaryRequest($body, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testBodyWithBinaryAsync - * - * @param \SplFileObject $body image to upload (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testBodyWithBinaryAsync($body, string $contentType = self::contentTypes['testBodyWithBinary'][0]) - { - return $this->testBodyWithBinaryAsyncWithHttpInfo($body, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testBodyWithBinaryAsyncWithHttpInfo - * - * @param \SplFileObject $body image to upload (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testBodyWithBinaryAsyncWithHttpInfo($body, string $contentType = self::contentTypes['testBodyWithBinary'][0]) - { - $returnType = ''; - $request = $this->testBodyWithBinaryRequest($body, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testBodyWithBinary' - * - * @param \SplFileObject $body image to upload (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testBodyWithBinaryRequest($body, string $contentType = self::contentTypes['testBodyWithBinary'][0]) - { - - // verify the required parameter 'body' is set - if ($body === null || (is_array($body) && count($body) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $body when calling testBodyWithBinary' - ); - } - - - $resourcePath = '/fake/body-with-binary'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($body)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); - } else { - $httpBody = $body; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PUT', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testBodyWithFileSchema - * - * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class file_schema_test_class (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testBodyWithFileSchema($file_schema_test_class, string $contentType = self::contentTypes['testBodyWithFileSchema'][0]) - { - $this->testBodyWithFileSchemaWithHttpInfo($file_schema_test_class, $contentType); - } - - /** - * Operation testBodyWithFileSchemaWithHttpInfo - * - * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testBodyWithFileSchemaWithHttpInfo($file_schema_test_class, string $contentType = self::contentTypes['testBodyWithFileSchema'][0]) - { - $request = $this->testBodyWithFileSchemaRequest($file_schema_test_class, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testBodyWithFileSchemaAsync - * - * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testBodyWithFileSchemaAsync($file_schema_test_class, string $contentType = self::contentTypes['testBodyWithFileSchema'][0]) - { - return $this->testBodyWithFileSchemaAsyncWithHttpInfo($file_schema_test_class, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testBodyWithFileSchemaAsyncWithHttpInfo - * - * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testBodyWithFileSchemaAsyncWithHttpInfo($file_schema_test_class, string $contentType = self::contentTypes['testBodyWithFileSchema'][0]) - { - $returnType = ''; - $request = $this->testBodyWithFileSchemaRequest($file_schema_test_class, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testBodyWithFileSchema' - * - * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testBodyWithFileSchemaRequest($file_schema_test_class, string $contentType = self::contentTypes['testBodyWithFileSchema'][0]) - { - - // verify the required parameter 'file_schema_test_class' is set - if ($file_schema_test_class === null || (is_array($file_schema_test_class) && count($file_schema_test_class) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $file_schema_test_class when calling testBodyWithFileSchema' - ); - } - - - $resourcePath = '/fake/body-with-file-schema'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($file_schema_test_class)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($file_schema_test_class)); - } else { - $httpBody = $file_schema_test_class; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PUT', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testBodyWithQueryParams - * - * @param string $query query (required) - * @param \OpenAPI\Client\Model\User $user user (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testBodyWithQueryParams($query, $user, string $contentType = self::contentTypes['testBodyWithQueryParams'][0]) - { - $this->testBodyWithQueryParamsWithHttpInfo($query, $user, $contentType); - } - - /** - * Operation testBodyWithQueryParamsWithHttpInfo - * - * @param string $query (required) - * @param \OpenAPI\Client\Model\User $user (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testBodyWithQueryParamsWithHttpInfo($query, $user, string $contentType = self::contentTypes['testBodyWithQueryParams'][0]) - { - $request = $this->testBodyWithQueryParamsRequest($query, $user, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testBodyWithQueryParamsAsync - * - * @param string $query (required) - * @param \OpenAPI\Client\Model\User $user (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testBodyWithQueryParamsAsync($query, $user, string $contentType = self::contentTypes['testBodyWithQueryParams'][0]) - { - return $this->testBodyWithQueryParamsAsyncWithHttpInfo($query, $user, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testBodyWithQueryParamsAsyncWithHttpInfo - * - * @param string $query (required) - * @param \OpenAPI\Client\Model\User $user (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testBodyWithQueryParamsAsyncWithHttpInfo($query, $user, string $contentType = self::contentTypes['testBodyWithQueryParams'][0]) - { - $returnType = ''; - $request = $this->testBodyWithQueryParamsRequest($query, $user, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testBodyWithQueryParams' - * - * @param string $query (required) - * @param \OpenAPI\Client\Model\User $user (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testBodyWithQueryParamsRequest($query, $user, string $contentType = self::contentTypes['testBodyWithQueryParams'][0]) - { - - // verify the required parameter 'query' is set - if ($query === null || (is_array($query) && count($query) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $query when calling testBodyWithQueryParams' - ); - } - - // verify the required parameter 'user' is set - if ($user === null || (is_array($user) && count($user) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $user when calling testBodyWithQueryParams' - ); - } - - - $resourcePath = '/fake/body-with-query-params'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $query, - 'query', // param base name - 'string', // openApiType - 'form', // style - true, // explode - true // required - ) ?? []); - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($user)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($user)); - } else { - $httpBody = $user; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PUT', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testClientModel - * - * To test \"client\" model - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Client - */ - public function testClientModel($client, string $contentType = self::contentTypes['testClientModel'][0]) - { - list($response) = $this->testClientModelWithHttpInfo($client, $contentType); - return $response; - } - - /** - * Operation testClientModelWithHttpInfo - * - * To test \"client\" model - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) - */ - public function testClientModelWithHttpInfo($client, string $contentType = self::contentTypes['testClientModel'][0]) - { - $request = $this->testClientModelRequest($client, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Client'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Client', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation testClientModelAsync - * - * To test \"client\" model - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testClientModelAsync($client, string $contentType = self::contentTypes['testClientModel'][0]) - { - return $this->testClientModelAsyncWithHttpInfo($client, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testClientModelAsyncWithHttpInfo - * - * To test \"client\" model - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testClientModelAsyncWithHttpInfo($client, string $contentType = self::contentTypes['testClientModel'][0]) - { - $returnType = '\OpenAPI\Client\Model\Client'; - $request = $this->testClientModelRequest($client, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testClientModel' - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testClientModelRequest($client, string $contentType = self::contentTypes['testClientModel'][0]) - { - - // verify the required parameter 'client' is set - if ($client === null || (is_array($client) && count($client) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $client when calling testClientModel' - ); - } - - - $resourcePath = '/fake'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($client)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($client)); - } else { - $httpBody = $client; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PATCH', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testEndpointParameters - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param float $number None (required) - * @param float $double None (required) - * @param string $pattern_without_delimiter None (required) - * @param string $byte None (required) - * @param int $integer None (optional) - * @param int $int32 None (optional) - * @param int $int64 None (optional) - * @param float $float None (optional) - * @param string $string None (optional) - * @param \SplFileObject $binary None (optional) - * @param \DateTime $date None (optional) - * @param \DateTime $date_time None (optional) - * @param string $password None (optional) - * @param string $callback None (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testEndpointParameters($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null, string $contentType = self::contentTypes['testEndpointParameters'][0]) - { - $this->testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback, $contentType); - } - - /** - * Operation testEndpointParametersWithHttpInfo - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param float $number None (required) - * @param float $double None (required) - * @param string $pattern_without_delimiter None (required) - * @param string $byte None (required) - * @param int $integer None (optional) - * @param int $int32 None (optional) - * @param int $int64 None (optional) - * @param float $float None (optional) - * @param string $string None (optional) - * @param \SplFileObject $binary None (optional) - * @param \DateTime $date None (optional) - * @param \DateTime $date_time None (optional) - * @param string $password None (optional) - * @param string $callback None (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testEndpointParametersWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null, string $contentType = self::contentTypes['testEndpointParameters'][0]) - { - $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testEndpointParametersAsync - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param float $number None (required) - * @param float $double None (required) - * @param string $pattern_without_delimiter None (required) - * @param string $byte None (required) - * @param int $integer None (optional) - * @param int $int32 None (optional) - * @param int $int64 None (optional) - * @param float $float None (optional) - * @param string $string None (optional) - * @param \SplFileObject $binary None (optional) - * @param \DateTime $date None (optional) - * @param \DateTime $date_time None (optional) - * @param string $password None (optional) - * @param string $callback None (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testEndpointParametersAsync($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null, string $contentType = self::contentTypes['testEndpointParameters'][0]) - { - return $this->testEndpointParametersAsyncWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testEndpointParametersAsyncWithHttpInfo - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param float $number None (required) - * @param float $double None (required) - * @param string $pattern_without_delimiter None (required) - * @param string $byte None (required) - * @param int $integer None (optional) - * @param int $int32 None (optional) - * @param int $int64 None (optional) - * @param float $float None (optional) - * @param string $string None (optional) - * @param \SplFileObject $binary None (optional) - * @param \DateTime $date None (optional) - * @param \DateTime $date_time None (optional) - * @param string $password None (optional) - * @param string $callback None (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testEndpointParametersAsyncWithHttpInfo($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null, string $contentType = self::contentTypes['testEndpointParameters'][0]) - { - $returnType = ''; - $request = $this->testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer, $int32, $int64, $float, $string, $binary, $date, $date_time, $password, $callback, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testEndpointParameters' - * - * @param float $number None (required) - * @param float $double None (required) - * @param string $pattern_without_delimiter None (required) - * @param string $byte None (required) - * @param int $integer None (optional) - * @param int $int32 None (optional) - * @param int $int64 None (optional) - * @param float $float None (optional) - * @param string $string None (optional) - * @param \SplFileObject $binary None (optional) - * @param \DateTime $date None (optional) - * @param \DateTime $date_time None (optional) - * @param string $password None (optional) - * @param string $callback None (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testEndpointParametersRequest($number, $double, $pattern_without_delimiter, $byte, $integer = null, $int32 = null, $int64 = null, $float = null, $string = null, $binary = null, $date = null, $date_time = null, $password = null, $callback = null, string $contentType = self::contentTypes['testEndpointParameters'][0]) - { - - // verify the required parameter 'number' is set - if ($number === null || (is_array($number) && count($number) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $number when calling testEndpointParameters' - ); - } - if ($number > 543.2) { - throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 543.2.'); - } - if ($number < 32.1) { - throw new \InvalidArgumentException('invalid value for "$number" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 32.1.'); - } - - // verify the required parameter 'double' is set - if ($double === null || (is_array($double) && count($double) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $double when calling testEndpointParameters' - ); - } - if ($double > 123.4) { - throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 123.4.'); - } - if ($double < 67.8) { - throw new \InvalidArgumentException('invalid value for "$double" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 67.8.'); - } - - // verify the required parameter 'pattern_without_delimiter' is set - if ($pattern_without_delimiter === null || (is_array($pattern_without_delimiter) && count($pattern_without_delimiter) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pattern_without_delimiter when calling testEndpointParameters' - ); - } - if (!preg_match("/^[A-Z].*/", $pattern_without_delimiter)) { - throw new \InvalidArgumentException("invalid value for \"pattern_without_delimiter\" when calling FakeApi.testEndpointParameters, must conform to the pattern /^[A-Z].*/."); - } - - // verify the required parameter 'byte' is set - if ($byte === null || (is_array($byte) && count($byte) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $byte when calling testEndpointParameters' - ); - } - - if ($integer !== null && $integer > 100) { - throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 100.'); - } - if ($integer !== null && $integer < 10) { - throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); - } - - if ($int32 !== null && $int32 > 200) { - throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 200.'); - } - if ($int32 !== null && $int32 < 20) { - throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 20.'); - } - - - if ($float !== null && $float > 987.6) { - throw new \InvalidArgumentException('invalid value for "$float" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 987.6.'); - } - - if ($string !== null && !preg_match("/[a-z]/i", $string)) { - throw new \InvalidArgumentException("invalid value for \"string\" when calling FakeApi.testEndpointParameters, must conform to the pattern /[a-z]/i."); - } - - - - - if ($password !== null && strlen($password) > 64) { - throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 64.'); - } - if ($password !== null && strlen($password) < 10) { - throw new \InvalidArgumentException('invalid length for "$password" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); - } - - - - $resourcePath = '/fake'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - // form params - if ($integer !== null) { - $formParams['integer'] = ObjectSerializer::toFormValue($integer); - } - // form params - if ($int32 !== null) { - $formParams['int32'] = ObjectSerializer::toFormValue($int32); - } - // form params - if ($int64 !== null) { - $formParams['int64'] = ObjectSerializer::toFormValue($int64); - } - // form params - if ($number !== null) { - $formParams['number'] = ObjectSerializer::toFormValue($number); - } - // form params - if ($float !== null) { - $formParams['float'] = ObjectSerializer::toFormValue($float); - } - // form params - if ($double !== null) { - $formParams['double'] = ObjectSerializer::toFormValue($double); - } - // form params - if ($string !== null) { - $formParams['string'] = ObjectSerializer::toFormValue($string); - } - // form params - if ($pattern_without_delimiter !== null) { - $formParams['pattern_without_delimiter'] = ObjectSerializer::toFormValue($pattern_without_delimiter); - } - // form params - if ($byte !== null) { - $formParams['byte'] = ObjectSerializer::toFormValue($byte); - } - // form params - if ($binary !== null) { - $multipart = true; - $formParams['binary'] = []; - $paramFiles = is_array($binary) ? $binary : [$binary]; - foreach ($paramFiles as $paramFile) { - $formParams['binary'][] = \GuzzleHttp\Psr7\Utils::tryFopen( - ObjectSerializer::toFormValue($paramFile), - 'rb' - ); - } - } - // form params - if ($date !== null) { - $formParams['date'] = ObjectSerializer::toFormValue($date); - } - // form params - if ($date_time !== null) { - $formParams['dateTime'] = ObjectSerializer::toFormValue($date_time); - } - // form params - if ($password !== null) { - $formParams['password'] = ObjectSerializer::toFormValue($password); - } - // form params - if ($callback !== null) { - $formParams['callback'] = ObjectSerializer::toFormValue($callback); - } - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires HTTP basic authentication - if (!empty($this->config->getUsername()) || !(empty($this->config->getPassword()))) { - $headers['Authorization'] = 'Basic ' . base64_encode($this->config->getUsername() . ":" . $this->config->getPassword()); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testEnumParameters - * - * To test enum parameters - * - * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) - * @param string $enum_header_string Header parameter enum test (string) (optional, default to '-efg') - * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) - * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') - * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param float $enum_query_double Query parameter enum test (double) (optional) - * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array enum_query_model_array (optional) - * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') - * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testEnumParameters($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_query_model_array = null, $enum_form_string_array = '$', $enum_form_string = '-efg', string $contentType = self::contentTypes['testEnumParameters'][0]) - { - $this->testEnumParametersWithHttpInfo($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_query_model_array, $enum_form_string_array, $enum_form_string, $contentType); - } - - /** - * Operation testEnumParametersWithHttpInfo - * - * To test enum parameters - * - * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) - * @param string $enum_header_string Header parameter enum test (string) (optional, default to '-efg') - * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) - * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') - * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param float $enum_query_double Query parameter enum test (double) (optional) - * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) - * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') - * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testEnumParametersWithHttpInfo($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_query_model_array = null, $enum_form_string_array = '$', $enum_form_string = '-efg', string $contentType = self::contentTypes['testEnumParameters'][0]) - { - $request = $this->testEnumParametersRequest($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_query_model_array, $enum_form_string_array, $enum_form_string, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testEnumParametersAsync - * - * To test enum parameters - * - * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) - * @param string $enum_header_string Header parameter enum test (string) (optional, default to '-efg') - * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) - * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') - * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param float $enum_query_double Query parameter enum test (double) (optional) - * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) - * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') - * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testEnumParametersAsync($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_query_model_array = null, $enum_form_string_array = '$', $enum_form_string = '-efg', string $contentType = self::contentTypes['testEnumParameters'][0]) - { - return $this->testEnumParametersAsyncWithHttpInfo($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_query_model_array, $enum_form_string_array, $enum_form_string, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testEnumParametersAsyncWithHttpInfo - * - * To test enum parameters - * - * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) - * @param string $enum_header_string Header parameter enum test (string) (optional, default to '-efg') - * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) - * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') - * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param float $enum_query_double Query parameter enum test (double) (optional) - * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) - * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') - * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testEnumParametersAsyncWithHttpInfo($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_query_model_array = null, $enum_form_string_array = '$', $enum_form_string = '-efg', string $contentType = self::contentTypes['testEnumParameters'][0]) - { - $returnType = ''; - $request = $this->testEnumParametersRequest($enum_header_string_array, $enum_header_string, $enum_query_string_array, $enum_query_string, $enum_query_integer, $enum_query_double, $enum_query_model_array, $enum_form_string_array, $enum_form_string, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testEnumParameters' - * - * @param string[] $enum_header_string_array Header parameter enum test (string array) (optional) - * @param string $enum_header_string Header parameter enum test (string) (optional, default to '-efg') - * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) - * @param string $enum_query_string Query parameter enum test (string) (optional, default to '-efg') - * @param int $enum_query_integer Query parameter enum test (double) (optional) - * @param float $enum_query_double Query parameter enum test (double) (optional) - * @param \OpenAPI\Client\Model\EnumClass[] $enum_query_model_array (optional) - * @param string[] $enum_form_string_array Form parameter enum test (string array) (optional, default to '$') - * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testEnumParametersRequest($enum_header_string_array = null, $enum_header_string = '-efg', $enum_query_string_array = null, $enum_query_string = '-efg', $enum_query_integer = null, $enum_query_double = null, $enum_query_model_array = null, $enum_form_string_array = '$', $enum_form_string = '-efg', string $contentType = self::contentTypes['testEnumParameters'][0]) - { - - - - - - - - - - - - $resourcePath = '/fake'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $enum_query_string_array, - 'enum_query_string_array', // param base name - 'array', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $enum_query_string, - 'enum_query_string', // param base name - 'string', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $enum_query_integer, - 'enum_query_integer', // param base name - 'integer', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $enum_query_double, - 'enum_query_double', // param base name - 'number', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $enum_query_model_array, - 'enum_query_model_array', // param base name - 'array', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - - // header params - if (is_array($enum_header_string_array)) { - $enum_header_string_array = ObjectSerializer::serializeCollection($enum_header_string_array, 'csv'); - } - if ($enum_header_string_array !== null) { - $headerParams['enum_header_string_array'] = ObjectSerializer::toHeaderValue($enum_header_string_array); - } - // header params - if ($enum_header_string !== null) { - $headerParams['enum_header_string'] = ObjectSerializer::toHeaderValue($enum_header_string); - } - - - // form params - if ($enum_form_string_array !== null) { - $formParams['enum_form_string_array'] = ObjectSerializer::toFormValue($enum_form_string_array); - } - // form params - if ($enum_form_string !== null) { - $formParams['enum_form_string'] = ObjectSerializer::toFormValue($enum_form_string); - } - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testGroupParameters - * - * Fake endpoint to test group parameters (optional) - * - * Note: the input parameter is an associative array with the keys listed as the parameter name below - * - * @param int $required_string_group Required String in group parameters (required) - * @param bool $required_boolean_group Required Boolean in group parameters (required) - * @param int $required_int64_group Required Integer in group parameters (required) - * @param int $string_group String in group parameters (optional) - * @param bool $boolean_group Boolean in group parameters (optional) - * @param int $int64_group Integer in group parameters (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testGroupParameters($associative_array) - { - $this->testGroupParametersWithHttpInfo($associative_array); - } - - /** - * Operation testGroupParametersWithHttpInfo - * - * Fake endpoint to test group parameters (optional) - * - * Note: the input parameter is an associative array with the keys listed as the parameter name below - * - * @param int $required_string_group Required String in group parameters (required) - * @param bool $required_boolean_group Required Boolean in group parameters (required) - * @param int $required_int64_group Required Integer in group parameters (required) - * @param int $string_group String in group parameters (optional) - * @param bool $boolean_group Boolean in group parameters (optional) - * @param int $int64_group Integer in group parameters (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testGroupParametersWithHttpInfo($associative_array) - { - $request = $this->testGroupParametersRequest($associative_array); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testGroupParametersAsync - * - * Fake endpoint to test group parameters (optional) - * - * Note: the input parameter is an associative array with the keys listed as the parameter name below - * - * @param int $required_string_group Required String in group parameters (required) - * @param bool $required_boolean_group Required Boolean in group parameters (required) - * @param int $required_int64_group Required Integer in group parameters (required) - * @param int $string_group String in group parameters (optional) - * @param bool $boolean_group Boolean in group parameters (optional) - * @param int $int64_group Integer in group parameters (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testGroupParametersAsync($associative_array) - { - return $this->testGroupParametersAsyncWithHttpInfo($associative_array) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testGroupParametersAsyncWithHttpInfo - * - * Fake endpoint to test group parameters (optional) - * - * Note: the input parameter is an associative array with the keys listed as the parameter name below - * - * @param int $required_string_group Required String in group parameters (required) - * @param bool $required_boolean_group Required Boolean in group parameters (required) - * @param int $required_int64_group Required Integer in group parameters (required) - * @param int $string_group String in group parameters (optional) - * @param bool $boolean_group Boolean in group parameters (optional) - * @param int $int64_group Integer in group parameters (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testGroupParametersAsyncWithHttpInfo($associative_array) - { - $returnType = ''; - $request = $this->testGroupParametersRequest($associative_array); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testGroupParameters' - * - * Note: the input parameter is an associative array with the keys listed as the parameter name below - * - * @param int $required_string_group Required String in group parameters (required) - * @param bool $required_boolean_group Required Boolean in group parameters (required) - * @param int $required_int64_group Required Integer in group parameters (required) - * @param int $string_group String in group parameters (optional) - * @param bool $boolean_group Boolean in group parameters (optional) - * @param int $int64_group Integer in group parameters (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testGroupParametersRequest($associative_array) - { - // unbox the parameters from the associative array - $required_string_group = array_key_exists('required_string_group', $associative_array) ? $associative_array['required_string_group'] : null; - $required_boolean_group = array_key_exists('required_boolean_group', $associative_array) ? $associative_array['required_boolean_group'] : null; - $required_int64_group = array_key_exists('required_int64_group', $associative_array) ? $associative_array['required_int64_group'] : null; - $string_group = array_key_exists('string_group', $associative_array) ? $associative_array['string_group'] : null; - $boolean_group = array_key_exists('boolean_group', $associative_array) ? $associative_array['boolean_group'] : null; - $int64_group = array_key_exists('int64_group', $associative_array) ? $associative_array['int64_group'] : null; - $contentType = $associative_array['contentType'] ?? self::contentTypes['testGroupParameters'][0]; - - // verify the required parameter 'required_string_group' is set - if ($required_string_group === null || (is_array($required_string_group) && count($required_string_group) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $required_string_group when calling testGroupParameters' - ); - } - - // verify the required parameter 'required_boolean_group' is set - if ($required_boolean_group === null || (is_array($required_boolean_group) && count($required_boolean_group) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $required_boolean_group when calling testGroupParameters' - ); - } - - // verify the required parameter 'required_int64_group' is set - if ($required_int64_group === null || (is_array($required_int64_group) && count($required_int64_group) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $required_int64_group when calling testGroupParameters' - ); - } - - - - - - $resourcePath = '/fake'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $required_string_group, - 'required_string_group', // param base name - 'integer', // openApiType - 'form', // style - true, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $required_int64_group, - 'required_int64_group', // param base name - 'integer', // openApiType - 'form', // style - true, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $string_group, - 'string_group', // param base name - 'integer', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $int64_group, - 'int64_group', // param base name - 'integer', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - - // header params - if ($required_boolean_group !== null) { - $headerParams['required_boolean_group'] = ObjectSerializer::toHeaderValue($required_boolean_group); - } - // header params - if ($boolean_group !== null) { - $headerParams['boolean_group'] = ObjectSerializer::toHeaderValue($boolean_group); - } - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires Bearer (JWT) authentication (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'DELETE', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testInlineAdditionalProperties - * - * test inline additionalProperties - * - * @param array $request_body request body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testInlineAdditionalProperties($request_body, string $contentType = self::contentTypes['testInlineAdditionalProperties'][0]) - { - $this->testInlineAdditionalPropertiesWithHttpInfo($request_body, $contentType); - } - - /** - * Operation testInlineAdditionalPropertiesWithHttpInfo - * - * test inline additionalProperties - * - * @param array $request_body request body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testInlineAdditionalPropertiesWithHttpInfo($request_body, string $contentType = self::contentTypes['testInlineAdditionalProperties'][0]) - { - $request = $this->testInlineAdditionalPropertiesRequest($request_body, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testInlineAdditionalPropertiesAsync - * - * test inline additionalProperties - * - * @param array $request_body request body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testInlineAdditionalPropertiesAsync($request_body, string $contentType = self::contentTypes['testInlineAdditionalProperties'][0]) - { - return $this->testInlineAdditionalPropertiesAsyncWithHttpInfo($request_body, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testInlineAdditionalPropertiesAsyncWithHttpInfo - * - * test inline additionalProperties - * - * @param array $request_body request body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testInlineAdditionalPropertiesAsyncWithHttpInfo($request_body, string $contentType = self::contentTypes['testInlineAdditionalProperties'][0]) - { - $returnType = ''; - $request = $this->testInlineAdditionalPropertiesRequest($request_body, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testInlineAdditionalProperties' - * - * @param array $request_body request body (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testInlineAdditionalPropertiesRequest($request_body, string $contentType = self::contentTypes['testInlineAdditionalProperties'][0]) - { - - // verify the required parameter 'request_body' is set - if ($request_body === null || (is_array($request_body) && count($request_body) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $request_body when calling testInlineAdditionalProperties' - ); - } - - - $resourcePath = '/fake/inline-additionalProperties'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($request_body)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($request_body)); - } else { - $httpBody = $request_body; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testJsonFormData - * - * test json serialization of form data - * - * @param string $param field1 (required) - * @param string $param2 field2 (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testJsonFormData($param, $param2, string $contentType = self::contentTypes['testJsonFormData'][0]) - { - $this->testJsonFormDataWithHttpInfo($param, $param2, $contentType); - } - - /** - * Operation testJsonFormDataWithHttpInfo - * - * test json serialization of form data - * - * @param string $param field1 (required) - * @param string $param2 field2 (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testJsonFormDataWithHttpInfo($param, $param2, string $contentType = self::contentTypes['testJsonFormData'][0]) - { - $request = $this->testJsonFormDataRequest($param, $param2, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testJsonFormDataAsync - * - * test json serialization of form data - * - * @param string $param field1 (required) - * @param string $param2 field2 (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testJsonFormDataAsync($param, $param2, string $contentType = self::contentTypes['testJsonFormData'][0]) - { - return $this->testJsonFormDataAsyncWithHttpInfo($param, $param2, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testJsonFormDataAsyncWithHttpInfo - * - * test json serialization of form data - * - * @param string $param field1 (required) - * @param string $param2 field2 (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testJsonFormDataAsyncWithHttpInfo($param, $param2, string $contentType = self::contentTypes['testJsonFormData'][0]) - { - $returnType = ''; - $request = $this->testJsonFormDataRequest($param, $param2, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testJsonFormData' - * - * @param string $param field1 (required) - * @param string $param2 field2 (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testJsonFormDataRequest($param, $param2, string $contentType = self::contentTypes['testJsonFormData'][0]) - { - - // verify the required parameter 'param' is set - if ($param === null || (is_array($param) && count($param) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $param when calling testJsonFormData' - ); - } - - // verify the required parameter 'param2' is set - if ($param2 === null || (is_array($param2) && count($param2) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $param2 when calling testJsonFormData' - ); - } - - - $resourcePath = '/fake/jsonFormData'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - // form params - if ($param !== null) { - $formParams['param'] = ObjectSerializer::toFormValue($param); - } - // form params - if ($param2 !== null) { - $formParams['param2'] = ObjectSerializer::toFormValue($param2); - } - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation testQueryParameterCollectionFormat - * - * @param string[] $pipe pipe (required) - * @param string[] $ioutil ioutil (required) - * @param string[] $http http (required) - * @param string[] $url url (required) - * @param string[] $context context (required) - * @param string $allow_empty allow_empty (required) - * @param array $language language (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function testQueryParameterCollectionFormat($pipe, $ioutil, $http, $url, $context, $allow_empty, $language = null, string $contentType = self::contentTypes['testQueryParameterCollectionFormat'][0]) - { - $this->testQueryParameterCollectionFormatWithHttpInfo($pipe, $ioutil, $http, $url, $context, $allow_empty, $language, $contentType); - } - - /** - * Operation testQueryParameterCollectionFormatWithHttpInfo - * - * @param string[] $pipe (required) - * @param string[] $ioutil (required) - * @param string[] $http (required) - * @param string[] $url (required) - * @param string[] $context (required) - * @param string $allow_empty (required) - * @param array $language (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function testQueryParameterCollectionFormatWithHttpInfo($pipe, $ioutil, $http, $url, $context, $allow_empty, $language = null, string $contentType = self::contentTypes['testQueryParameterCollectionFormat'][0]) - { - $request = $this->testQueryParameterCollectionFormatRequest($pipe, $ioutil, $http, $url, $context, $allow_empty, $language, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation testQueryParameterCollectionFormatAsync - * - * @param string[] $pipe (required) - * @param string[] $ioutil (required) - * @param string[] $http (required) - * @param string[] $url (required) - * @param string[] $context (required) - * @param string $allow_empty (required) - * @param array $language (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testQueryParameterCollectionFormatAsync($pipe, $ioutil, $http, $url, $context, $allow_empty, $language = null, string $contentType = self::contentTypes['testQueryParameterCollectionFormat'][0]) - { - return $this->testQueryParameterCollectionFormatAsyncWithHttpInfo($pipe, $ioutil, $http, $url, $context, $allow_empty, $language, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testQueryParameterCollectionFormatAsyncWithHttpInfo - * - * @param string[] $pipe (required) - * @param string[] $ioutil (required) - * @param string[] $http (required) - * @param string[] $url (required) - * @param string[] $context (required) - * @param string $allow_empty (required) - * @param array $language (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testQueryParameterCollectionFormatAsyncWithHttpInfo($pipe, $ioutil, $http, $url, $context, $allow_empty, $language = null, string $contentType = self::contentTypes['testQueryParameterCollectionFormat'][0]) - { - $returnType = ''; - $request = $this->testQueryParameterCollectionFormatRequest($pipe, $ioutil, $http, $url, $context, $allow_empty, $language, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testQueryParameterCollectionFormat' - * - * @param string[] $pipe (required) - * @param string[] $ioutil (required) - * @param string[] $http (required) - * @param string[] $url (required) - * @param string[] $context (required) - * @param string $allow_empty (required) - * @param array $language (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testQueryParameterCollectionFormatRequest($pipe, $ioutil, $http, $url, $context, $allow_empty, $language = null, string $contentType = self::contentTypes['testQueryParameterCollectionFormat'][0]) - { - - // verify the required parameter 'pipe' is set - if ($pipe === null || (is_array($pipe) && count($pipe) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pipe when calling testQueryParameterCollectionFormat' - ); - } - - // verify the required parameter 'ioutil' is set - if ($ioutil === null || (is_array($ioutil) && count($ioutil) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $ioutil when calling testQueryParameterCollectionFormat' - ); - } - - // verify the required parameter 'http' is set - if ($http === null || (is_array($http) && count($http) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $http when calling testQueryParameterCollectionFormat' - ); - } - - // verify the required parameter 'url' is set - if ($url === null || (is_array($url) && count($url) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $url when calling testQueryParameterCollectionFormat' - ); - } - - // verify the required parameter 'context' is set - if ($context === null || (is_array($context) && count($context) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $context when calling testQueryParameterCollectionFormat' - ); - } - - // verify the required parameter 'allow_empty' is set - if ($allow_empty === null || (is_array($allow_empty) && count($allow_empty) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $allow_empty when calling testQueryParameterCollectionFormat' - ); - } - - - - $resourcePath = '/fake/test-query-parameters'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $pipe, - 'pipe', // param base name - 'array', // openApiType - 'pipeDelimited', // style - false, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $ioutil, - 'ioutil', // param base name - 'array', // openApiType - 'form', // style - false, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $http, - 'http', // param base name - 'array', // openApiType - 'spaceDelimited', // style - false, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $url, - 'url', // param base name - 'array', // openApiType - 'form', // style - false, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $context, - 'context', // param base name - 'array', // openApiType - 'form', // style - true, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $language, - 'language', // param base name - 'object', // openApiType - 'form', // style - true, // explode - false // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $allow_empty, - 'allowEmpty', // param base name - 'string', // openApiType - 'form', // style - true, // explode - true // required - ) ?? []); - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PUT', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Create http client option - * - * @throws \RuntimeException on file opening failure - * @return array of http client options - */ - protected function createHttpClientOption() - { - $options = []; - if ($this->config->getDebug()) { - $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); - if (!$options[RequestOptions::DEBUG]) { - throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); - } - } - - return $options; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php deleted file mode 100644 index 131ded357415..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php +++ /dev/null @@ -1,430 +0,0 @@ - [ - 'application/json', - ], - ]; - -/** - * @param ClientInterface $client - * @param Configuration $config - * @param HeaderSelector $selector - * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec - */ - public function __construct( - ClientInterface $client = null, - Configuration $config = null, - HeaderSelector $selector = null, - $hostIndex = 0 - ) { - $this->client = $client ?: new Client(); - $this->config = $config ?: new Configuration(); - $this->headerSelector = $selector ?: new HeaderSelector(); - $this->hostIndex = $hostIndex; - } - - /** - * Set the host index - * - * @param int $hostIndex Host index (required) - */ - public function setHostIndex($hostIndex): void - { - $this->hostIndex = $hostIndex; - } - - /** - * Get the host index - * - * @return int Host index - */ - public function getHostIndex() - { - return $this->hostIndex; - } - - /** - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Operation testClassname - * - * To test class name in snake case - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Client - */ - public function testClassname($client, string $contentType = self::contentTypes['testClassname'][0]) - { - list($response) = $this->testClassnameWithHttpInfo($client, $contentType); - return $response; - } - - /** - * Operation testClassnameWithHttpInfo - * - * To test class name in snake case - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) - */ - public function testClassnameWithHttpInfo($client, string $contentType = self::contentTypes['testClassname'][0]) - { - $request = $this->testClassnameRequest($client, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Client' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Client', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Client'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Client', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation testClassnameAsync - * - * To test class name in snake case - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testClassnameAsync($client, string $contentType = self::contentTypes['testClassname'][0]) - { - return $this->testClassnameAsyncWithHttpInfo($client, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation testClassnameAsyncWithHttpInfo - * - * To test class name in snake case - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function testClassnameAsyncWithHttpInfo($client, string $contentType = self::contentTypes['testClassname'][0]) - { - $returnType = '\OpenAPI\Client\Model\Client'; - $request = $this->testClassnameRequest($client, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'testClassname' - * - * @param \OpenAPI\Client\Model\Client $client client model (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function testClassnameRequest($client, string $contentType = self::contentTypes['testClassname'][0]) - { - - // verify the required parameter 'client' is set - if ($client === null || (is_array($client) && count($client) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $client when calling testClassname' - ); - } - - - $resourcePath = '/fake_classname_test'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($client)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($client)); - } else { - $httpBody = $client; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires API key authentication - $apiKey = $this->config->getApiKeyWithPrefix('api_key_query'); - if ($apiKey !== null) { - $queryParams['api_key_query'] = $apiKey; - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PATCH', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Create http client option - * - * @throws \RuntimeException on file opening failure - * @return array of http client options - */ - protected function createHttpClientOption() - { - $options = []; - if ($this->config->getDebug()) { - $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); - if (!$options[RequestOptions::DEBUG]) { - throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); - } - } - - return $options; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/PetApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/PetApi.php deleted file mode 100644 index d75d7f469bef..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/PetApi.php +++ /dev/null @@ -1,2918 +0,0 @@ - [ - 'application/json', - 'application/xml', - ], - 'deletePet' => [ - 'application/json', - ], - 'findPetsByStatus' => [ - 'application/json', - ], - 'findPetsByTags' => [ - 'application/json', - ], - 'getPetById' => [ - 'application/json', - ], - 'updatePet' => [ - 'application/json', - 'application/xml', - ], - 'updatePetWithForm' => [ - 'application/x-www-form-urlencoded', - ], - 'uploadFile' => [ - 'multipart/form-data', - ], - 'uploadFileWithRequiredFile' => [ - 'multipart/form-data', - ], - ]; - -/** - * @param ClientInterface $client - * @param Configuration $config - * @param HeaderSelector $selector - * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec - */ - public function __construct( - ClientInterface $client = null, - Configuration $config = null, - HeaderSelector $selector = null, - $hostIndex = 0 - ) { - $this->client = $client ?: new Client(); - $this->config = $config ?: new Configuration(); - $this->headerSelector = $selector ?: new HeaderSelector(); - $this->hostIndex = $hostIndex; - } - - /** - * Set the host index - * - * @param int $hostIndex Host index (required) - */ - public function setHostIndex($hostIndex): void - { - $this->hostIndex = $hostIndex; - } - - /** - * Get the host index - * - * @return int Host index - */ - public function getHostIndex() - { - return $this->hostIndex; - } - - /** - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Operation addPet - * - * Add a new pet to the store - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function addPet($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['addPet'][0]) - { - $this->addPetWithHttpInfo($pet, $hostIndex, $variables, $contentType); - } - - /** - * Operation addPetWithHttpInfo - * - * Add a new pet to the store - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function addPetWithHttpInfo($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['addPet'][0]) - { - $request = $this->addPetRequest($pet, $hostIndex, $variables, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation addPetAsync - * - * Add a new pet to the store - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function addPetAsync($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['addPet'][0]) - { - return $this->addPetAsyncWithHttpInfo($pet, $hostIndex, $variables, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation addPetAsyncWithHttpInfo - * - * Add a new pet to the store - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function addPetAsyncWithHttpInfo($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['addPet'][0]) - { - $returnType = ''; - $request = $this->addPetRequest($pet, $hostIndex, $variables, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'addPet' - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function addPetRequest($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['addPet'][0]) - { - - // verify the required parameter 'pet' is set - if ($pet === null || (is_array($pet) && count($pet) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet when calling addPet' - ); - } - - - $resourcePath = '/pet'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($pet)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($pet)); - } else { - $httpBody = $pet; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - # Preserve the original behavior of server indexing. - if ($hostIndex === null) { - $hostIndex = $this->hostIndex; - } - - $hostSettings = $this->getHostSettingsForaddPet(); - - if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { - throw new \InvalidArgumentException("Invalid index {$hostIndex} when selecting the host. Must be less than ".count($hostSettings)); - } - $operationHost = Configuration::getHostString($hostSettings, $hostIndex, $variables); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Returns an array of host settings for Operation addPet - * - * @return array an array of host settings - */ - protected function getHostSettingsForaddPet(): array - { - return [ - [ - "url" => "http://petstore.swagger.io/v2", - "description" => "No description provided", - ], - [ - "url" => "http://path-server-test.petstore.local/v2", - "description" => "No description provided", - ], - [ - "url" => "http://{server}.swagger.io:{port}/v2", - "description" => "test server with variables", - "variables" => [ - "server" => [ - "description" => "target server", - "default_value" => "petstore", - "enum_values" => [ - "petstore", - "qa-petstore", - "dev-petstore", - ] - ], - "port" => [ - "description" => "No description provided", - "default_value" => "80", - "enum_values" => [ - "80", - "8080", - ] - ] - ] - ] - ]; - } - - /** - * Operation deletePet - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key api_key (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function deletePet($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) - { - $this->deletePetWithHttpInfo($pet_id, $api_key, $contentType); - } - - /** - * Operation deletePetWithHttpInfo - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function deletePetWithHttpInfo($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) - { - $request = $this->deletePetRequest($pet_id, $api_key, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation deletePetAsync - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function deletePetAsync($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) - { - return $this->deletePetAsyncWithHttpInfo($pet_id, $api_key, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation deletePetAsyncWithHttpInfo - * - * Deletes a pet - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function deletePetAsyncWithHttpInfo($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) - { - $returnType = ''; - $request = $this->deletePetRequest($pet_id, $api_key, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'deletePet' - * - * @param int $pet_id Pet id to delete (required) - * @param string $api_key (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function deletePetRequest($pet_id, $api_key = null, string $contentType = self::contentTypes['deletePet'][0]) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet_id when calling deletePet' - ); - } - - - - $resourcePath = '/pet/{petId}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - // header params - if ($api_key !== null) { - $headerParams['api_key'] = ObjectSerializer::toHeaderValue($api_key); - } - - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - '{' . 'petId' . '}', - ObjectSerializer::toPathValue($pet_id), - $resourcePath - ); - } - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'DELETE', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation findPetsByStatus - * - * Finds Pets by status - * - * @param string[] $status Status values that need to be considered for filter (required) (deprecated) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Pet[] - */ - public function findPetsByStatus($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) - { - list($response) = $this->findPetsByStatusWithHttpInfo($status, $contentType); - return $response; - } - - /** - * Operation findPetsByStatusWithHttpInfo - * - * Finds Pets by status - * - * @param string[] $status Status values that need to be considered for filter (required) (deprecated) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) - */ - public function findPetsByStatusWithHttpInfo($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) - { - $request = $this->findPetsByStatusRequest($status, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet[]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Pet[]'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Pet[]', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation findPetsByStatusAsync - * - * Finds Pets by status - * - * @param string[] $status Status values that need to be considered for filter (required) (deprecated) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function findPetsByStatusAsync($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) - { - return $this->findPetsByStatusAsyncWithHttpInfo($status, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation findPetsByStatusAsyncWithHttpInfo - * - * Finds Pets by status - * - * @param string[] $status Status values that need to be considered for filter (required) (deprecated) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function findPetsByStatusAsyncWithHttpInfo($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) - { - $returnType = '\OpenAPI\Client\Model\Pet[]'; - $request = $this->findPetsByStatusRequest($status, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'findPetsByStatus' - * - * @param string[] $status Status values that need to be considered for filter (required) (deprecated) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function findPetsByStatusRequest($status, string $contentType = self::contentTypes['findPetsByStatus'][0]) - { - - // verify the required parameter 'status' is set - if ($status === null || (is_array($status) && count($status) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $status when calling findPetsByStatus' - ); - } - - - $resourcePath = '/pet/findByStatus'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $status, - 'status', // param base name - 'array', // openApiType - 'form', // style - false, // explode - true // required - ) ?? []); - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation findPetsByTags - * - * Finds Pets by tags - * - * @param string[] $tags Tags to filter by (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Pet[] - * @deprecated - */ - public function findPetsByTags($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) - { - list($response) = $this->findPetsByTagsWithHttpInfo($tags, $contentType); - return $response; - } - - /** - * Operation findPetsByTagsWithHttpInfo - * - * Finds Pets by tags - * - * @param string[] $tags Tags to filter by (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) - * @deprecated - */ - public function findPetsByTagsWithHttpInfo($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) - { - $request = $this->findPetsByTagsRequest($tags, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Pet[]' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet[]', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Pet[]'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Pet[]', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation findPetsByTagsAsync - * - * Finds Pets by tags - * - * @param string[] $tags Tags to filter by (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - * @deprecated - */ - public function findPetsByTagsAsync($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) - { - return $this->findPetsByTagsAsyncWithHttpInfo($tags, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation findPetsByTagsAsyncWithHttpInfo - * - * Finds Pets by tags - * - * @param string[] $tags Tags to filter by (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - * @deprecated - */ - public function findPetsByTagsAsyncWithHttpInfo($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) - { - $returnType = '\OpenAPI\Client\Model\Pet[]'; - $request = $this->findPetsByTagsRequest($tags, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'findPetsByTags' - * - * @param string[] $tags Tags to filter by (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - * @deprecated - */ - public function findPetsByTagsRequest($tags, string $contentType = self::contentTypes['findPetsByTags'][0]) - { - - // verify the required parameter 'tags' is set - if ($tags === null || (is_array($tags) && count($tags) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $tags when calling findPetsByTags' - ); - } - - - $resourcePath = '/pet/findByTags'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $tags, - 'tags', // param base name - 'array', // openApiType - 'form', // style - false, // explode - true // required - ) ?? []); - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation getPetById - * - * Find pet by ID - * - * @param int $pet_id ID of pet to return (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Pet - */ - public function getPetById($pet_id, string $contentType = self::contentTypes['getPetById'][0]) - { - list($response) = $this->getPetByIdWithHttpInfo($pet_id, $contentType); - return $response; - } - - /** - * Operation getPetByIdWithHttpInfo - * - * Find pet by ID - * - * @param int $pet_id ID of pet to return (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) - */ - public function getPetByIdWithHttpInfo($pet_id, string $contentType = self::contentTypes['getPetById'][0]) - { - $request = $this->getPetByIdRequest($pet_id, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Pet' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Pet' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Pet'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Pet', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation getPetByIdAsync - * - * Find pet by ID - * - * @param int $pet_id ID of pet to return (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getPetByIdAsync($pet_id, string $contentType = self::contentTypes['getPetById'][0]) - { - return $this->getPetByIdAsyncWithHttpInfo($pet_id, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation getPetByIdAsyncWithHttpInfo - * - * Find pet by ID - * - * @param int $pet_id ID of pet to return (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getPetByIdAsyncWithHttpInfo($pet_id, string $contentType = self::contentTypes['getPetById'][0]) - { - $returnType = '\OpenAPI\Client\Model\Pet'; - $request = $this->getPetByIdRequest($pet_id, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'getPetById' - * - * @param int $pet_id ID of pet to return (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function getPetByIdRequest($pet_id, string $contentType = self::contentTypes['getPetById'][0]) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet_id when calling getPetById' - ); - } - - - $resourcePath = '/pet/{petId}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - '{' . 'petId' . '}', - ObjectSerializer::toPathValue($pet_id), - $resourcePath - ); - } - - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires API key authentication - $apiKey = $this->config->getApiKeyWithPrefix('api_key'); - if ($apiKey !== null) { - $headers['api_key'] = $apiKey; - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation updatePet - * - * Update an existing pet - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function updatePet($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['updatePet'][0]) - { - $this->updatePetWithHttpInfo($pet, $hostIndex, $variables, $contentType); - } - - /** - * Operation updatePetWithHttpInfo - * - * Update an existing pet - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function updatePetWithHttpInfo($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['updatePet'][0]) - { - $request = $this->updatePetRequest($pet, $hostIndex, $variables, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation updatePetAsync - * - * Update an existing pet - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function updatePetAsync($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['updatePet'][0]) - { - return $this->updatePetAsyncWithHttpInfo($pet, $hostIndex, $variables, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation updatePetAsyncWithHttpInfo - * - * Update an existing pet - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function updatePetAsyncWithHttpInfo($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['updatePet'][0]) - { - $returnType = ''; - $request = $this->updatePetRequest($pet, $hostIndex, $variables, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'updatePet' - * - * This operation contains host(s) defined in the OpenAPI spec. Use 'hostIndex' to select the host. - * if needed, use the 'variables' parameter to pass variables to the host. - * URL: http://petstore.swagger.io/v2 - * URL: http://path-server-test.petstore.local/v2 - * URL: http://{server}.swagger.io:{port}/v2 - * Variables: - * - server: target server - * Allowed values: - * - petstore - * - qa-petstore - * - dev-petstore - * - port: No description provided - * Allowed values: - * - 80 - * - 8080 - * - * @param \OpenAPI\Client\Model\Pet $pet Pet object that needs to be added to the store (required) - * @param null|int $hostIndex Host index. Defaults to null. If null, then the library will use $this->hostIndex instead - * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function updatePetRequest($pet, ?int $hostIndex = null, array $variables = [], string $contentType = self::contentTypes['updatePet'][0]) - { - - // verify the required parameter 'pet' is set - if ($pet === null || (is_array($pet) && count($pet) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet when calling updatePet' - ); - } - - - $resourcePath = '/pet'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($pet)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($pet)); - } else { - $httpBody = $pet; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - # Preserve the original behavior of server indexing. - if ($hostIndex === null) { - $hostIndex = $this->hostIndex; - } - - $hostSettings = $this->getHostSettingsForupdatePet(); - - if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { - throw new \InvalidArgumentException("Invalid index {$hostIndex} when selecting the host. Must be less than ".count($hostSettings)); - } - $operationHost = Configuration::getHostString($hostSettings, $hostIndex, $variables); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PUT', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Returns an array of host settings for Operation updatePet - * - * @return array an array of host settings - */ - protected function getHostSettingsForupdatePet(): array - { - return [ - [ - "url" => "http://petstore.swagger.io/v2", - "description" => "No description provided", - ], - [ - "url" => "http://path-server-test.petstore.local/v2", - "description" => "No description provided", - ], - [ - "url" => "http://{server}.swagger.io:{port}/v2", - "description" => "test server with variables", - "variables" => [ - "server" => [ - "description" => "target server", - "default_value" => "petstore", - "enum_values" => [ - "petstore", - "qa-petstore", - "dev-petstore", - ] - ], - "port" => [ - "description" => "No description provided", - "default_value" => "80", - "enum_values" => [ - "80", - "8080", - ] - ] - ] - ] - ]; - } - - /** - * Operation updatePetWithForm - * - * Updates a pet in the store with form data - * - * @param int $pet_id ID of pet that needs to be updated (required) - * @param string $name Updated name of the pet (optional) - * @param string $status Updated status of the pet (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function updatePetWithForm($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) - { - $this->updatePetWithFormWithHttpInfo($pet_id, $name, $status, $contentType); - } - - /** - * Operation updatePetWithFormWithHttpInfo - * - * Updates a pet in the store with form data - * - * @param int $pet_id ID of pet that needs to be updated (required) - * @param string $name Updated name of the pet (optional) - * @param string $status Updated status of the pet (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function updatePetWithFormWithHttpInfo($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) - { - $request = $this->updatePetWithFormRequest($pet_id, $name, $status, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation updatePetWithFormAsync - * - * Updates a pet in the store with form data - * - * @param int $pet_id ID of pet that needs to be updated (required) - * @param string $name Updated name of the pet (optional) - * @param string $status Updated status of the pet (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function updatePetWithFormAsync($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) - { - return $this->updatePetWithFormAsyncWithHttpInfo($pet_id, $name, $status, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation updatePetWithFormAsyncWithHttpInfo - * - * Updates a pet in the store with form data - * - * @param int $pet_id ID of pet that needs to be updated (required) - * @param string $name Updated name of the pet (optional) - * @param string $status Updated status of the pet (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function updatePetWithFormAsyncWithHttpInfo($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) - { - $returnType = ''; - $request = $this->updatePetWithFormRequest($pet_id, $name, $status, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'updatePetWithForm' - * - * @param int $pet_id ID of pet that needs to be updated (required) - * @param string $name Updated name of the pet (optional) - * @param string $status Updated status of the pet (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function updatePetWithFormRequest($pet_id, $name = null, $status = null, string $contentType = self::contentTypes['updatePetWithForm'][0]) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet_id when calling updatePetWithForm' - ); - } - - - - - $resourcePath = '/pet/{petId}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - '{' . 'petId' . '}', - ObjectSerializer::toPathValue($pet_id), - $resourcePath - ); - } - - // form params - if ($name !== null) { - $formParams['name'] = ObjectSerializer::toFormValue($name); - } - // form params - if ($status !== null) { - $formParams['status'] = ObjectSerializer::toFormValue($status); - } - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation uploadFile - * - * uploads an image - * - * @param int $pet_id ID of pet to update (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param \SplFileObject $file file to upload (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\ApiResponse - */ - public function uploadFile($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) - { - list($response) = $this->uploadFileWithHttpInfo($pet_id, $additional_metadata, $file, $contentType); - return $response; - } - - /** - * Operation uploadFileWithHttpInfo - * - * uploads an image - * - * @param int $pet_id ID of pet to update (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param \SplFileObject $file file to upload (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) - */ - public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) - { - $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\ApiResponse' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\ApiResponse', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\ApiResponse'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\ApiResponse', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation uploadFileAsync - * - * uploads an image - * - * @param int $pet_id ID of pet to update (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param \SplFileObject $file file to upload (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function uploadFileAsync($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) - { - return $this->uploadFileAsyncWithHttpInfo($pet_id, $additional_metadata, $file, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation uploadFileAsyncWithHttpInfo - * - * uploads an image - * - * @param int $pet_id ID of pet to update (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param \SplFileObject $file file to upload (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function uploadFileAsyncWithHttpInfo($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) - { - $returnType = '\OpenAPI\Client\Model\ApiResponse'; - $request = $this->uploadFileRequest($pet_id, $additional_metadata, $file, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'uploadFile' - * - * @param int $pet_id ID of pet to update (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param \SplFileObject $file file to upload (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function uploadFileRequest($pet_id, $additional_metadata = null, $file = null, string $contentType = self::contentTypes['uploadFile'][0]) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet_id when calling uploadFile' - ); - } - - - - - $resourcePath = '/pet/{petId}/uploadImage'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - '{' . 'petId' . '}', - ObjectSerializer::toPathValue($pet_id), - $resourcePath - ); - } - - // form params - if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = ObjectSerializer::toFormValue($additional_metadata); - } - // form params - if ($file !== null) { - $multipart = true; - $formParams['file'] = []; - $paramFiles = is_array($file) ? $file : [$file]; - foreach ($paramFiles as $paramFile) { - $formParams['file'][] = \GuzzleHttp\Psr7\Utils::tryFopen( - ObjectSerializer::toFormValue($paramFile), - 'rb' - ); - } - } - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation uploadFileWithRequiredFile - * - * uploads an image (required) - * - * @param int $pet_id ID of pet to update (required) - * @param \SplFileObject $required_file file to upload (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\ApiResponse - */ - public function uploadFileWithRequiredFile($pet_id, $required_file, $additional_metadata = null, string $contentType = self::contentTypes['uploadFileWithRequiredFile'][0]) - { - list($response) = $this->uploadFileWithRequiredFileWithHttpInfo($pet_id, $required_file, $additional_metadata, $contentType); - return $response; - } - - /** - * Operation uploadFileWithRequiredFileWithHttpInfo - * - * uploads an image (required) - * - * @param int $pet_id ID of pet to update (required) - * @param \SplFileObject $required_file file to upload (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) - */ - public function uploadFileWithRequiredFileWithHttpInfo($pet_id, $required_file, $additional_metadata = null, string $contentType = self::contentTypes['uploadFileWithRequiredFile'][0]) - { - $request = $this->uploadFileWithRequiredFileRequest($pet_id, $required_file, $additional_metadata, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\ApiResponse' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\ApiResponse', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\ApiResponse'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\ApiResponse', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation uploadFileWithRequiredFileAsync - * - * uploads an image (required) - * - * @param int $pet_id ID of pet to update (required) - * @param \SplFileObject $required_file file to upload (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function uploadFileWithRequiredFileAsync($pet_id, $required_file, $additional_metadata = null, string $contentType = self::contentTypes['uploadFileWithRequiredFile'][0]) - { - return $this->uploadFileWithRequiredFileAsyncWithHttpInfo($pet_id, $required_file, $additional_metadata, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation uploadFileWithRequiredFileAsyncWithHttpInfo - * - * uploads an image (required) - * - * @param int $pet_id ID of pet to update (required) - * @param \SplFileObject $required_file file to upload (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function uploadFileWithRequiredFileAsyncWithHttpInfo($pet_id, $required_file, $additional_metadata = null, string $contentType = self::contentTypes['uploadFileWithRequiredFile'][0]) - { - $returnType = '\OpenAPI\Client\Model\ApiResponse'; - $request = $this->uploadFileWithRequiredFileRequest($pet_id, $required_file, $additional_metadata, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'uploadFileWithRequiredFile' - * - * @param int $pet_id ID of pet to update (required) - * @param \SplFileObject $required_file file to upload (required) - * @param string $additional_metadata Additional data to pass to server (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function uploadFileWithRequiredFileRequest($pet_id, $required_file, $additional_metadata = null, string $contentType = self::contentTypes['uploadFileWithRequiredFile'][0]) - { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null || (is_array($pet_id) && count($pet_id) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $pet_id when calling uploadFileWithRequiredFile' - ); - } - - // verify the required parameter 'required_file' is set - if ($required_file === null || (is_array($required_file) && count($required_file) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $required_file when calling uploadFileWithRequiredFile' - ); - } - - - - $resourcePath = '/fake/{petId}/uploadImageWithRequiredFile'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($pet_id !== null) { - $resourcePath = str_replace( - '{' . 'petId' . '}', - ObjectSerializer::toPathValue($pet_id), - $resourcePath - ); - } - - // form params - if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = ObjectSerializer::toFormValue($additional_metadata); - } - // form params - if ($required_file !== null) { - $multipart = true; - $formParams['requiredFile'] = []; - $paramFiles = is_array($required_file) ? $required_file : [$required_file]; - foreach ($paramFiles as $paramFile) { - $formParams['requiredFile'][] = \GuzzleHttp\Psr7\Utils::tryFopen( - ObjectSerializer::toFormValue($paramFile), - 'rb' - ); - } - } - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires OAuth (access token) - if (!empty($this->config->getAccessToken())) { - $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Create http client option - * - * @throws \RuntimeException on file opening failure - * @return array of http client options - */ - protected function createHttpClientOption() - { - $options = []; - if ($this->config->getDebug()) { - $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); - if (!$options[RequestOptions::DEBUG]) { - throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); - } - } - - return $options; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/StoreApi.php deleted file mode 100644 index 54f31f8a9219..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/StoreApi.php +++ /dev/null @@ -1,1220 +0,0 @@ - [ - 'application/json', - ], - 'getInventory' => [ - 'application/json', - ], - 'getOrderById' => [ - 'application/json', - ], - 'placeOrder' => [ - 'application/json', - ], - ]; - -/** - * @param ClientInterface $client - * @param Configuration $config - * @param HeaderSelector $selector - * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec - */ - public function __construct( - ClientInterface $client = null, - Configuration $config = null, - HeaderSelector $selector = null, - $hostIndex = 0 - ) { - $this->client = $client ?: new Client(); - $this->config = $config ?: new Configuration(); - $this->headerSelector = $selector ?: new HeaderSelector(); - $this->hostIndex = $hostIndex; - } - - /** - * Set the host index - * - * @param int $hostIndex Host index (required) - */ - public function setHostIndex($hostIndex): void - { - $this->hostIndex = $hostIndex; - } - - /** - * Get the host index - * - * @return int Host index - */ - public function getHostIndex() - { - return $this->hostIndex; - } - - /** - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Operation deleteOrder - * - * Delete purchase order by ID - * - * @param string $order_id ID of the order that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function deleteOrder($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) - { - $this->deleteOrderWithHttpInfo($order_id, $contentType); - } - - /** - * Operation deleteOrderWithHttpInfo - * - * Delete purchase order by ID - * - * @param string $order_id ID of the order that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function deleteOrderWithHttpInfo($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) - { - $request = $this->deleteOrderRequest($order_id, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation deleteOrderAsync - * - * Delete purchase order by ID - * - * @param string $order_id ID of the order that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function deleteOrderAsync($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) - { - return $this->deleteOrderAsyncWithHttpInfo($order_id, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation deleteOrderAsyncWithHttpInfo - * - * Delete purchase order by ID - * - * @param string $order_id ID of the order that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function deleteOrderAsyncWithHttpInfo($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) - { - $returnType = ''; - $request = $this->deleteOrderRequest($order_id, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'deleteOrder' - * - * @param string $order_id ID of the order that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function deleteOrderRequest($order_id, string $contentType = self::contentTypes['deleteOrder'][0]) - { - - // verify the required parameter 'order_id' is set - if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $order_id when calling deleteOrder' - ); - } - - - $resourcePath = '/store/order/{order_id}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($order_id !== null) { - $resourcePath = str_replace( - '{' . 'order_id' . '}', - ObjectSerializer::toPathValue($order_id), - $resourcePath - ); - } - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'DELETE', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation getInventory - * - * Returns pet inventories by status - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array - */ - public function getInventory(string $contentType = self::contentTypes['getInventory'][0]) - { - list($response) = $this->getInventoryWithHttpInfo($contentType); - return $response; - } - - /** - * Operation getInventoryWithHttpInfo - * - * Returns pet inventories by status - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of array, HTTP status code, HTTP response headers (array of strings) - */ - public function getInventoryWithHttpInfo(string $contentType = self::contentTypes['getInventory'][0]) - { - $request = $this->getInventoryRequest($contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('array' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('array' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, 'array', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = 'array'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - 'array', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation getInventoryAsync - * - * Returns pet inventories by status - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getInventoryAsync(string $contentType = self::contentTypes['getInventory'][0]) - { - return $this->getInventoryAsyncWithHttpInfo($contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation getInventoryAsyncWithHttpInfo - * - * Returns pet inventories by status - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getInventoryAsyncWithHttpInfo(string $contentType = self::contentTypes['getInventory'][0]) - { - $returnType = 'array'; - $request = $this->getInventoryRequest($contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'getInventory' - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function getInventoryRequest(string $contentType = self::contentTypes['getInventory'][0]) - { - - - $resourcePath = '/store/inventory'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - // this endpoint requires API key authentication - $apiKey = $this->config->getApiKeyWithPrefix('api_key'); - if ($apiKey !== null) { - $headers['api_key'] = $apiKey; - } - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation getOrderById - * - * Find purchase order by ID - * - * @param int $order_id ID of pet that needs to be fetched (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Order - */ - public function getOrderById($order_id, string $contentType = self::contentTypes['getOrderById'][0]) - { - list($response) = $this->getOrderByIdWithHttpInfo($order_id, $contentType); - return $response; - } - - /** - * Operation getOrderByIdWithHttpInfo - * - * Find purchase order by ID - * - * @param int $order_id ID of pet that needs to be fetched (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) - */ - public function getOrderByIdWithHttpInfo($order_id, string $contentType = self::contentTypes['getOrderById'][0]) - { - $request = $this->getOrderByIdRequest($order_id, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Order' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Order', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Order'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Order', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation getOrderByIdAsync - * - * Find purchase order by ID - * - * @param int $order_id ID of pet that needs to be fetched (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getOrderByIdAsync($order_id, string $contentType = self::contentTypes['getOrderById'][0]) - { - return $this->getOrderByIdAsyncWithHttpInfo($order_id, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation getOrderByIdAsyncWithHttpInfo - * - * Find purchase order by ID - * - * @param int $order_id ID of pet that needs to be fetched (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getOrderByIdAsyncWithHttpInfo($order_id, string $contentType = self::contentTypes['getOrderById'][0]) - { - $returnType = '\OpenAPI\Client\Model\Order'; - $request = $this->getOrderByIdRequest($order_id, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'getOrderById' - * - * @param int $order_id ID of pet that needs to be fetched (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function getOrderByIdRequest($order_id, string $contentType = self::contentTypes['getOrderById'][0]) - { - - // verify the required parameter 'order_id' is set - if ($order_id === null || (is_array($order_id) && count($order_id) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $order_id when calling getOrderById' - ); - } - if ($order_id > 5) { - throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be smaller than or equal to 5.'); - } - if ($order_id < 1) { - throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.'); - } - - - $resourcePath = '/store/order/{order_id}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($order_id !== null) { - $resourcePath = str_replace( - '{' . 'order_id' . '}', - ObjectSerializer::toPathValue($order_id), - $resourcePath - ); - } - - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation placeOrder - * - * Place an order for a pet - * - * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\Order - */ - public function placeOrder($order, string $contentType = self::contentTypes['placeOrder'][0]) - { - list($response) = $this->placeOrderWithHttpInfo($order, $contentType); - return $response; - } - - /** - * Operation placeOrderWithHttpInfo - * - * Place an order for a pet - * - * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) - */ - public function placeOrderWithHttpInfo($order, string $contentType = self::contentTypes['placeOrder'][0]) - { - $request = $this->placeOrderRequest($order, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\Order' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\Order' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Order', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\Order'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\Order', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation placeOrderAsync - * - * Place an order for a pet - * - * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function placeOrderAsync($order, string $contentType = self::contentTypes['placeOrder'][0]) - { - return $this->placeOrderAsyncWithHttpInfo($order, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation placeOrderAsyncWithHttpInfo - * - * Place an order for a pet - * - * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function placeOrderAsyncWithHttpInfo($order, string $contentType = self::contentTypes['placeOrder'][0]) - { - $returnType = '\OpenAPI\Client\Model\Order'; - $request = $this->placeOrderRequest($order, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'placeOrder' - * - * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function placeOrderRequest($order, string $contentType = self::contentTypes['placeOrder'][0]) - { - - // verify the required parameter 'order' is set - if ($order === null || (is_array($order) && count($order) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $order when calling placeOrder' - ); - } - - - $resourcePath = '/store/order'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($order)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($order)); - } else { - $httpBody = $order; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Create http client option - * - * @throws \RuntimeException on file opening failure - * @return array of http client options - */ - protected function createHttpClientOption() - { - $options = []; - if ($this->config->getDebug()) { - $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); - if (!$options[RequestOptions::DEBUG]) { - throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); - } - } - - return $options; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/UserApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/UserApi.php deleted file mode 100644 index 43831c86827b..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Api/UserApi.php +++ /dev/null @@ -1,2122 +0,0 @@ - [ - 'application/json', - ], - 'createUsersWithArrayInput' => [ - 'application/json', - ], - 'createUsersWithListInput' => [ - 'application/json', - ], - 'deleteUser' => [ - 'application/json', - ], - 'getUserByName' => [ - 'application/json', - ], - 'loginUser' => [ - 'application/json', - ], - 'logoutUser' => [ - 'application/json', - ], - 'updateUser' => [ - 'application/json', - ], - ]; - -/** - * @param ClientInterface $client - * @param Configuration $config - * @param HeaderSelector $selector - * @param int $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec - */ - public function __construct( - ClientInterface $client = null, - Configuration $config = null, - HeaderSelector $selector = null, - $hostIndex = 0 - ) { - $this->client = $client ?: new Client(); - $this->config = $config ?: new Configuration(); - $this->headerSelector = $selector ?: new HeaderSelector(); - $this->hostIndex = $hostIndex; - } - - /** - * Set the host index - * - * @param int $hostIndex Host index (required) - */ - public function setHostIndex($hostIndex): void - { - $this->hostIndex = $hostIndex; - } - - /** - * Get the host index - * - * @return int Host index - */ - public function getHostIndex() - { - return $this->hostIndex; - } - - /** - * @return Configuration - */ - public function getConfig() - { - return $this->config; - } - - /** - * Operation createUser - * - * Create user - * - * @param \OpenAPI\Client\Model\User $user Created user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function createUser($user, string $contentType = self::contentTypes['createUser'][0]) - { - $this->createUserWithHttpInfo($user, $contentType); - } - - /** - * Operation createUserWithHttpInfo - * - * Create user - * - * @param \OpenAPI\Client\Model\User $user Created user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function createUserWithHttpInfo($user, string $contentType = self::contentTypes['createUser'][0]) - { - $request = $this->createUserRequest($user, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation createUserAsync - * - * Create user - * - * @param \OpenAPI\Client\Model\User $user Created user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function createUserAsync($user, string $contentType = self::contentTypes['createUser'][0]) - { - return $this->createUserAsyncWithHttpInfo($user, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation createUserAsyncWithHttpInfo - * - * Create user - * - * @param \OpenAPI\Client\Model\User $user Created user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function createUserAsyncWithHttpInfo($user, string $contentType = self::contentTypes['createUser'][0]) - { - $returnType = ''; - $request = $this->createUserRequest($user, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'createUser' - * - * @param \OpenAPI\Client\Model\User $user Created user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function createUserRequest($user, string $contentType = self::contentTypes['createUser'][0]) - { - - // verify the required parameter 'user' is set - if ($user === null || (is_array($user) && count($user) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $user when calling createUser' - ); - } - - - $resourcePath = '/user'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($user)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($user)); - } else { - $httpBody = $user; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation createUsersWithArrayInput - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function createUsersWithArrayInput($user, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) - { - $this->createUsersWithArrayInputWithHttpInfo($user, $contentType); - } - - /** - * Operation createUsersWithArrayInputWithHttpInfo - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function createUsersWithArrayInputWithHttpInfo($user, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) - { - $request = $this->createUsersWithArrayInputRequest($user, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation createUsersWithArrayInputAsync - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function createUsersWithArrayInputAsync($user, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) - { - return $this->createUsersWithArrayInputAsyncWithHttpInfo($user, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation createUsersWithArrayInputAsyncWithHttpInfo - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function createUsersWithArrayInputAsyncWithHttpInfo($user, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) - { - $returnType = ''; - $request = $this->createUsersWithArrayInputRequest($user, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'createUsersWithArrayInput' - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function createUsersWithArrayInputRequest($user, string $contentType = self::contentTypes['createUsersWithArrayInput'][0]) - { - - // verify the required parameter 'user' is set - if ($user === null || (is_array($user) && count($user) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $user when calling createUsersWithArrayInput' - ); - } - - - $resourcePath = '/user/createWithArray'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($user)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($user)); - } else { - $httpBody = $user; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation createUsersWithListInput - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function createUsersWithListInput($user, string $contentType = self::contentTypes['createUsersWithListInput'][0]) - { - $this->createUsersWithListInputWithHttpInfo($user, $contentType); - } - - /** - * Operation createUsersWithListInputWithHttpInfo - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function createUsersWithListInputWithHttpInfo($user, string $contentType = self::contentTypes['createUsersWithListInput'][0]) - { - $request = $this->createUsersWithListInputRequest($user, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation createUsersWithListInputAsync - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function createUsersWithListInputAsync($user, string $contentType = self::contentTypes['createUsersWithListInput'][0]) - { - return $this->createUsersWithListInputAsyncWithHttpInfo($user, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation createUsersWithListInputAsyncWithHttpInfo - * - * Creates list of users with given input array - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function createUsersWithListInputAsyncWithHttpInfo($user, string $contentType = self::contentTypes['createUsersWithListInput'][0]) - { - $returnType = ''; - $request = $this->createUsersWithListInputRequest($user, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'createUsersWithListInput' - * - * @param \OpenAPI\Client\Model\User[] $user List of user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function createUsersWithListInputRequest($user, string $contentType = self::contentTypes['createUsersWithListInput'][0]) - { - - // verify the required parameter 'user' is set - if ($user === null || (is_array($user) && count($user) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $user when calling createUsersWithListInput' - ); - } - - - $resourcePath = '/user/createWithList'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($user)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($user)); - } else { - $httpBody = $user; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'POST', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation deleteUser - * - * Delete user - * - * @param string $username The name that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function deleteUser($username, string $contentType = self::contentTypes['deleteUser'][0]) - { - $this->deleteUserWithHttpInfo($username, $contentType); - } - - /** - * Operation deleteUserWithHttpInfo - * - * Delete user - * - * @param string $username The name that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function deleteUserWithHttpInfo($username, string $contentType = self::contentTypes['deleteUser'][0]) - { - $request = $this->deleteUserRequest($username, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation deleteUserAsync - * - * Delete user - * - * @param string $username The name that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function deleteUserAsync($username, string $contentType = self::contentTypes['deleteUser'][0]) - { - return $this->deleteUserAsyncWithHttpInfo($username, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation deleteUserAsyncWithHttpInfo - * - * Delete user - * - * @param string $username The name that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function deleteUserAsyncWithHttpInfo($username, string $contentType = self::contentTypes['deleteUser'][0]) - { - $returnType = ''; - $request = $this->deleteUserRequest($username, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'deleteUser' - * - * @param string $username The name that needs to be deleted (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function deleteUserRequest($username, string $contentType = self::contentTypes['deleteUser'][0]) - { - - // verify the required parameter 'username' is set - if ($username === null || (is_array($username) && count($username) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $username when calling deleteUser' - ); - } - - - $resourcePath = '/user/{username}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($username !== null) { - $resourcePath = str_replace( - '{' . 'username' . '}', - ObjectSerializer::toPathValue($username), - $resourcePath - ); - } - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'DELETE', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation getUserByName - * - * Get user by user name - * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return \OpenAPI\Client\Model\User - */ - public function getUserByName($username, string $contentType = self::contentTypes['getUserByName'][0]) - { - list($response) = $this->getUserByNameWithHttpInfo($username, $contentType); - return $response; - } - - /** - * Operation getUserByNameWithHttpInfo - * - * Get user by user name - * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of \OpenAPI\Client\Model\User, HTTP status code, HTTP response headers (array of strings) - */ - public function getUserByNameWithHttpInfo($username, string $contentType = self::contentTypes['getUserByName'][0]) - { - $request = $this->getUserByNameRequest($username, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('\OpenAPI\Client\Model\User' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('\OpenAPI\Client\Model\User' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\User', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = '\OpenAPI\Client\Model\User'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - '\OpenAPI\Client\Model\User', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation getUserByNameAsync - * - * Get user by user name - * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getUserByNameAsync($username, string $contentType = self::contentTypes['getUserByName'][0]) - { - return $this->getUserByNameAsyncWithHttpInfo($username, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation getUserByNameAsyncWithHttpInfo - * - * Get user by user name - * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function getUserByNameAsyncWithHttpInfo($username, string $contentType = self::contentTypes['getUserByName'][0]) - { - $returnType = '\OpenAPI\Client\Model\User'; - $request = $this->getUserByNameRequest($username, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'getUserByName' - * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function getUserByNameRequest($username, string $contentType = self::contentTypes['getUserByName'][0]) - { - - // verify the required parameter 'username' is set - if ($username === null || (is_array($username) && count($username) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $username when calling getUserByName' - ); - } - - - $resourcePath = '/user/{username}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($username !== null) { - $resourcePath = str_replace( - '{' . 'username' . '}', - ObjectSerializer::toPathValue($username), - $resourcePath - ); - } - - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation loginUser - * - * Logs user into the system - * - * @param string $username The user name for login (required) - * @param string $password The password for login in clear text (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return string - */ - public function loginUser($username, $password, string $contentType = self::contentTypes['loginUser'][0]) - { - list($response) = $this->loginUserWithHttpInfo($username, $password, $contentType); - return $response; - } - - /** - * Operation loginUserWithHttpInfo - * - * Logs user into the system - * - * @param string $username The user name for login (required) - * @param string $password The password for login in clear text (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of string, HTTP status code, HTTP response headers (array of strings) - */ - public function loginUserWithHttpInfo($username, $password, string $contentType = self::contentTypes['loginUser'][0]) - { - $request = $this->loginUserRequest($username, $password, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - switch($statusCode) { - case 200: - if ('string' === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ('string' !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, 'string', []), - $response->getStatusCode(), - $response->getHeaders() - ]; - } - - $returnType = 'string'; - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = ObjectSerializer::deserialize( - $e->getResponseBody(), - 'string', - $e->getResponseHeaders() - ); - $e->setResponseObject($data); - break; - } - throw $e; - } - } - - /** - * Operation loginUserAsync - * - * Logs user into the system - * - * @param string $username The user name for login (required) - * @param string $password The password for login in clear text (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function loginUserAsync($username, $password, string $contentType = self::contentTypes['loginUser'][0]) - { - return $this->loginUserAsyncWithHttpInfo($username, $password, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation loginUserAsyncWithHttpInfo - * - * Logs user into the system - * - * @param string $username The user name for login (required) - * @param string $password The password for login in clear text (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function loginUserAsyncWithHttpInfo($username, $password, string $contentType = self::contentTypes['loginUser'][0]) - { - $returnType = 'string'; - $request = $this->loginUserRequest($username, $password, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - if ($returnType === '\SplFileObject') { - $content = $response->getBody(); //stream goes to serializer - } else { - $content = (string) $response->getBody(); - if ($returnType !== 'string') { - $content = json_decode($content); - } - } - - return [ - ObjectSerializer::deserialize($content, $returnType, []), - $response->getStatusCode(), - $response->getHeaders() - ]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'loginUser' - * - * @param string $username The user name for login (required) - * @param string $password The password for login in clear text (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function loginUserRequest($username, $password, string $contentType = self::contentTypes['loginUser'][0]) - { - - // verify the required parameter 'username' is set - if ($username === null || (is_array($username) && count($username) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $username when calling loginUser' - ); - } - - // verify the required parameter 'password' is set - if ($password === null || (is_array($password) && count($password) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $password when calling loginUser' - ); - } - - - $resourcePath = '/user/login'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $username, - 'username', // param base name - 'string', // openApiType - 'form', // style - true, // explode - true // required - ) ?? []); - // query params - $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue( - $password, - 'password', // param base name - 'string', // openApiType - 'form', // style - true, // explode - true // required - ) ?? []); - - - - - $headers = $this->headerSelector->selectHeaders( - ['application/xml', 'application/json', ], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation logoutUser - * - * Logs out current logged in user session - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function logoutUser(string $contentType = self::contentTypes['logoutUser'][0]) - { - $this->logoutUserWithHttpInfo($contentType); - } - - /** - * Operation logoutUserWithHttpInfo - * - * Logs out current logged in user session - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function logoutUserWithHttpInfo(string $contentType = self::contentTypes['logoutUser'][0]) - { - $request = $this->logoutUserRequest($contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation logoutUserAsync - * - * Logs out current logged in user session - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function logoutUserAsync(string $contentType = self::contentTypes['logoutUser'][0]) - { - return $this->logoutUserAsyncWithHttpInfo($contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation logoutUserAsyncWithHttpInfo - * - * Logs out current logged in user session - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function logoutUserAsyncWithHttpInfo(string $contentType = self::contentTypes['logoutUser'][0]) - { - $returnType = ''; - $request = $this->logoutUserRequest($contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'logoutUser' - * - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function logoutUserRequest(string $contentType = self::contentTypes['logoutUser'][0]) - { - - - $resourcePath = '/user/logout'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'GET', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Operation updateUser - * - * Updated user - * - * @param string $username name that need to be deleted (required) - * @param \OpenAPI\Client\Model\User $user Updated user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return void - */ - public function updateUser($username, $user, string $contentType = self::contentTypes['updateUser'][0]) - { - $this->updateUserWithHttpInfo($username, $user, $contentType); - } - - /** - * Operation updateUserWithHttpInfo - * - * Updated user - * - * @param string $username name that need to be deleted (required) - * @param \OpenAPI\Client\Model\User $user Updated user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation - * - * @throws \OpenAPI\Client\ApiException on non-2xx response - * @throws \InvalidArgumentException - * @return array of null, HTTP status code, HTTP response headers (array of strings) - */ - public function updateUserWithHttpInfo($username, $user, string $contentType = self::contentTypes['updateUser'][0]) - { - $request = $this->updateUserRequest($username, $user, $contentType); - - try { - $options = $this->createHttpClientOption(); - try { - $response = $this->client->send($request, $options); - } catch (RequestException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - $e->getResponse() ? $e->getResponse()->getHeaders() : null, - $e->getResponse() ? (string) $e->getResponse()->getBody() : null - ); - } catch (ConnectException $e) { - throw new ApiException( - "[{$e->getCode()}] {$e->getMessage()}", - (int) $e->getCode(), - null, - null - ); - } - - $statusCode = $response->getStatusCode(); - - if ($statusCode < 200 || $statusCode > 299) { - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - (string) $request->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - - return [null, $statusCode, $response->getHeaders()]; - - } catch (ApiException $e) { - switch ($e->getCode()) { - } - throw $e; - } - } - - /** - * Operation updateUserAsync - * - * Updated user - * - * @param string $username name that need to be deleted (required) - * @param \OpenAPI\Client\Model\User $user Updated user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function updateUserAsync($username, $user, string $contentType = self::contentTypes['updateUser'][0]) - { - return $this->updateUserAsyncWithHttpInfo($username, $user, $contentType) - ->then( - function ($response) { - return $response[0]; - } - ); - } - - /** - * Operation updateUserAsyncWithHttpInfo - * - * Updated user - * - * @param string $username name that need to be deleted (required) - * @param \OpenAPI\Client\Model\User $user Updated user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Promise\PromiseInterface - */ - public function updateUserAsyncWithHttpInfo($username, $user, string $contentType = self::contentTypes['updateUser'][0]) - { - $returnType = ''; - $request = $this->updateUserRequest($username, $user, $contentType); - - return $this->client - ->sendAsync($request, $this->createHttpClientOption()) - ->then( - function ($response) use ($returnType) { - return [null, $response->getStatusCode(), $response->getHeaders()]; - }, - function ($exception) { - $response = $exception->getResponse(); - $statusCode = $response->getStatusCode(); - throw new ApiException( - sprintf( - '[%d] Error connecting to the API (%s)', - $statusCode, - $exception->getRequest()->getUri() - ), - $statusCode, - $response->getHeaders(), - (string) $response->getBody() - ); - } - ); - } - - /** - * Create request for operation 'updateUser' - * - * @param string $username name that need to be deleted (required) - * @param \OpenAPI\Client\Model\User $user Updated user object (required) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation - * - * @throws \InvalidArgumentException - * @return \GuzzleHttp\Psr7\Request - */ - public function updateUserRequest($username, $user, string $contentType = self::contentTypes['updateUser'][0]) - { - - // verify the required parameter 'username' is set - if ($username === null || (is_array($username) && count($username) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $username when calling updateUser' - ); - } - - // verify the required parameter 'user' is set - if ($user === null || (is_array($user) && count($user) === 0)) { - throw new \InvalidArgumentException( - 'Missing the required parameter $user when calling updateUser' - ); - } - - - $resourcePath = '/user/{username}'; - $formParams = []; - $queryParams = []; - $headerParams = []; - $httpBody = ''; - $multipart = false; - - - - // path params - if ($username !== null) { - $resourcePath = str_replace( - '{' . 'username' . '}', - ObjectSerializer::toPathValue($username), - $resourcePath - ); - } - - - $headers = $this->headerSelector->selectHeaders( - [], - $contentType, - $multipart - ); - - // for model (json/xml) - if (isset($user)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($user)); - } else { - $httpBody = $user; - } - } elseif (count($formParams) > 0) { - if ($multipart) { - $multipartContents = []; - foreach ($formParams as $formParamName => $formParamValue) { - $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; - foreach ($formParamValueItems as $formParamValueItem) { - $multipartContents[] = [ - 'name' => $formParamName, - 'contents' => $formParamValueItem - ]; - } - } - // for HTTP post (form) - $httpBody = new MultipartStream($multipartContents); - - } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the form parameters - $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); - } else { - // for HTTP post (form) - $httpBody = ObjectSerializer::buildQuery($formParams); - } - } - - - $defaultHeaders = []; - if ($this->config->getUserAgent()) { - $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); - } - - $headers = array_merge( - $defaultHeaders, - $headerParams, - $headers - ); - - $operationHost = $this->config->getHost(); - $query = ObjectSerializer::buildQuery($queryParams); - return new Request( - 'PUT', - $operationHost . $resourcePath . ($query ? "?{$query}" : ''), - $headers, - $httpBody - ); - } - - /** - * Create http client option - * - * @throws \RuntimeException on file opening failure - * @return array of http client options - */ - protected function createHttpClientOption() - { - $options = []; - if ($this->config->getDebug()) { - $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a'); - if (!$options[RequestOptions::DEBUG]) { - throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile()); - } - } - - return $options; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/ApiException.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/ApiException.php deleted file mode 100644 index bffc807b9a2f..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/ApiException.php +++ /dev/null @@ -1,119 +0,0 @@ -responseHeaders = $responseHeaders; - $this->responseBody = $responseBody; - } - - /** - * Gets the HTTP response header - * - * @return string[]|null HTTP response header - */ - public function getResponseHeaders() - { - return $this->responseHeaders; - } - - /** - * Gets the HTTP body of the server response either as Json or string - * - * @return \stdClass|string|null HTTP body of the server response either as \stdClass or string - */ - public function getResponseBody() - { - return $this->responseBody; - } - - /** - * Sets the deserialized response object (during deserialization) - * - * @param mixed $obj Deserialized response object - * - * @return void - */ - public function setResponseObject($obj) - { - $this->responseObject = $obj; - } - - /** - * Gets the deserialized response object (during deserialization) - * - * @return mixed the deserialized response object - */ - public function getResponseObject() - { - return $this->responseObject; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Configuration.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Configuration.php deleted file mode 100644 index c08e07f8cdfb..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Configuration.php +++ /dev/null @@ -1,567 +0,0 @@ -tempFolderPath = sys_get_temp_dir(); - } - - /** - * Sets API key - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $key API key or token - * - * @return $this - */ - public function setApiKey($apiKeyIdentifier, $key) - { - $this->apiKeys[$apiKeyIdentifier] = $key; - return $this; - } - - /** - * Gets API key - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return null|string API key or token - */ - public function getApiKey($apiKeyIdentifier) - { - return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; - } - - /** - * Sets the prefix for API key (e.g. Bearer) - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * @param string $prefix API key prefix, e.g. Bearer - * - * @return $this - */ - public function setApiKeyPrefix($apiKeyIdentifier, $prefix) - { - $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; - return $this; - } - - /** - * Gets API key prefix - * - * @param string $apiKeyIdentifier API key identifier (authentication scheme) - * - * @return null|string - */ - public function getApiKeyPrefix($apiKeyIdentifier) - { - return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; - } - - /** - * Sets the access token for OAuth - * - * @param string $accessToken Token for OAuth - * - * @return $this - */ - public function setAccessToken($accessToken) - { - $this->accessToken = $accessToken; - return $this; - } - - /** - * Gets the access token for OAuth - * - * @return string Access token for OAuth - */ - public function getAccessToken() - { - return $this->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 - * - * @param string $username Username for HTTP basic authentication - * - * @return $this - */ - public function setUsername($username) - { - $this->username = $username; - return $this; - } - - /** - * Gets the username for HTTP basic authentication - * - * @return string Username for HTTP basic authentication - */ - public function getUsername() - { - return $this->username; - } - - /** - * Sets the password for HTTP basic authentication - * - * @param string $password Password for HTTP basic authentication - * - * @return $this - */ - public function setPassword($password) - { - $this->password = $password; - return $this; - } - - /** - * Gets the password for HTTP basic authentication - * - * @return string Password for HTTP basic authentication - */ - public function getPassword() - { - return $this->password; - } - - /** - * Sets the host - * - * @param string $host Host - * - * @return $this - */ - public function setHost($host) - { - $this->host = $host; - return $this; - } - - /** - * Gets the host - * - * @return string Host - */ - public function getHost() - { - return $this->host; - } - - /** - * Sets the user agent of the api client - * - * @param string $userAgent the user agent of the api client - * - * @throws \InvalidArgumentException - * @return $this - */ - public function setUserAgent($userAgent) - { - if (!is_string($userAgent)) { - throw new \InvalidArgumentException('User-agent must be a string.'); - } - - $this->userAgent = $userAgent; - return $this; - } - - /** - * Gets the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() - { - return $this->userAgent; - } - - /** - * Sets debug flag - * - * @param bool $debug Debug flag - * - * @return $this - */ - public function setDebug($debug) - { - $this->debug = $debug; - return $this; - } - - /** - * Gets the debug flag - * - * @return bool - */ - public function getDebug() - { - return $this->debug; - } - - /** - * Sets the debug file - * - * @param string $debugFile Debug file - * - * @return $this - */ - public function setDebugFile($debugFile) - { - $this->debugFile = $debugFile; - return $this; - } - - /** - * Gets the debug file - * - * @return string - */ - public function getDebugFile() - { - return $this->debugFile; - } - - /** - * Sets the temp folder path - * - * @param string $tempFolderPath Temp folder path - * - * @return $this - */ - public function setTempFolderPath($tempFolderPath) - { - $this->tempFolderPath = $tempFolderPath; - return $this; - } - - /** - * Gets the temp folder path - * - * @return string Temp folder path - */ - public function getTempFolderPath() - { - return $this->tempFolderPath; - } - - /** - * Gets the default configuration instance - * - * @return Configuration - */ - public static function getDefaultConfiguration() - { - if (self::$defaultConfiguration === null) { - self::$defaultConfiguration = new Configuration(); - } - - return self::$defaultConfiguration; - } - - /** - * Sets the default configuration instance - * - * @param Configuration $config An instance of the Configuration Object - * - * @return void - */ - public static function setDefaultConfiguration(Configuration $config) - { - self::$defaultConfiguration = $config; - } - - /** - * Gets the essential information for debugging - * - * @return string The report for debugging - */ - public static function toDebugReport() - { - $report = 'PHP SDK (OpenAPI\Client) Debug Report:' . PHP_EOL; - $report .= ' OS: ' . php_uname() . PHP_EOL; - $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; - $report .= ' The version of the OpenAPI document: 1.0.0' . PHP_EOL; - $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; - - return $report; - } - - /** - * Get API key (with prefix if set) - * - * @param string $apiKeyIdentifier name of apikey - * - * @return null|string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKeyIdentifier) - { - $prefix = $this->getApiKeyPrefix($apiKeyIdentifier); - $apiKey = $this->getApiKey($apiKeyIdentifier); - - if ($apiKey === null) { - return null; - } - - if ($prefix === null) { - $keyWithPrefix = $apiKey; - } else { - $keyWithPrefix = $prefix . ' ' . $apiKey; - } - - return $keyWithPrefix; - } - - /** - * Returns an array of host settings - * - * @return array an array of host settings - */ - public function getHostSettings() - { - return [ - [ - "url" => "http://{server}.swagger.io:{port}/v2", - "description" => "petstore server", - "variables" => [ - "server" => [ - "description" => "No description provided", - "default_value" => "petstore", - "enum_values" => [ - "petstore", - "qa-petstore", - "dev-petstore" - ] - ], - "port" => [ - "description" => "No description provided", - "default_value" => "80", - "enum_values" => [ - "80", - "8080" - ] - ] - ] - ], - [ - "url" => "https://localhost:8080/{version}", - "description" => "The local server", - "variables" => [ - "version" => [ - "description" => "No description provided", - "default_value" => "v2", - "enum_values" => [ - "v1", - "v2" - ] - ] - ] - ], - [ - "url" => "https://127.0.0.1/no_varaible", - "description" => "The local server without variables", - ] - ]; - } - - /** - * Returns URL based on host settings, index and variables - * - * @param array $hostSettings array of host settings, generated from getHostSettings() or equivalent from the API clients - * @param int $hostIndex index of the host settings - * @param array|null $variables hash of variable and the corresponding value (optional) - * @return string URL based on host settings - */ - public static function getHostString(array $hostsSettings, $hostIndex, array $variables = null) - { - if (null === $variables) { - $variables = []; - } - - // check array index out of bound - if ($hostIndex < 0 || $hostIndex >= count($hostsSettings)) { - throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostsSettings)); - } - - $host = $hostsSettings[$hostIndex]; - $url = $host["url"]; - - // go through variable and assign a value - foreach ($host["variables"] ?? [] as $name => $variable) { - if (array_key_exists($name, $variables)) { // check to see if it's in the variables provided by the user - if (!isset($variable['enum_values']) || in_array($variables[$name], $variable["enum_values"], true)) { // check to see if the value is in the enum - $url = str_replace("{".$name."}", $variables[$name], $url); - } else { - throw new \InvalidArgumentException("The variable `$name` in the host URL has invalid value ".$variables[$name].". Must be ".join(',', $variable["enum_values"])."."); - } - } else { - // use default value - $url = str_replace("{".$name."}", $variable["default_value"], $url); - } - } - - return $url; - } - - /** - * Returns URL based on the index and variables - * - * @param int $index index of the host settings - * @param array|null $variables hash of variable and the corresponding value (optional) - * @return string URL based on host settings - */ - public function getHostFromSettings($index, $variables = null) - { - return self::getHostString($this->getHostSettings(), $index, $variables); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/HeaderSelector.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/HeaderSelector.php deleted file mode 100644 index 611975603c86..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/HeaderSelector.php +++ /dev/null @@ -1,245 +0,0 @@ -selectAcceptHeader($accept); - if ($accept !== null) { - $headers['Accept'] = $accept; - } - - if (!$isMultipart) { - if($contentType === '') { - $contentType = 'application/json'; - } - - $headers['Content-Type'] = $contentType; - } - - return $headers; - } - - /** - * Return the header 'Accept' based on an array of Accept provided. - * - * @param string[] $accept Array of header - * - * @return null|string Accept (e.g. application/json) - */ - private function selectAcceptHeader(array $accept): ?string - { - # filter out empty entries - $accept = array_filter($accept); - - if (count($accept) === 0) { - return null; - } - - # If there's only one Accept header, just use it - if (count($accept) === 1) { - return reset($accept); - } - - # If none of the available Accept headers is of type "json", then just use all them - $headersWithJson = preg_grep('~(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$~', $accept); - if (count($headersWithJson) === 0) { - return implode(',', $accept); - } - - # If we got here, then we need add quality values (weight), as described in IETF RFC 9110, Items 12.4.2/12.5.1, - # to give the highest priority to json-like headers - recalculating the existing ones, if needed - return $this->getAcceptHeaderWithAdjustedWeight($accept, $headersWithJson); - } - - /** - * Create an Accept header string from the given "Accept" headers array, recalculating all weights - * - * @param string[] $accept Array of Accept Headers - * @param string[] $headersWithJson Array of Accept Headers of type "json" - * - * @return string "Accept" Header (e.g. "application/json, text/html; q=0.9") - */ - private function getAcceptHeaderWithAdjustedWeight(array $accept, array $headersWithJson): string - { - $processedHeaders = [ - 'withApplicationJson' => [], - 'withJson' => [], - 'withoutJson' => [], - ]; - - foreach ($accept as $header) { - - $headerData = $this->getHeaderAndWeight($header); - - if (stripos($headerData['header'], 'application/json') === 0) { - $processedHeaders['withApplicationJson'][] = $headerData; - } elseif (in_array($header, $headersWithJson, true)) { - $processedHeaders['withJson'][] = $headerData; - } else { - $processedHeaders['withoutJson'][] = $headerData; - } - } - - $acceptHeaders = []; - $currentWeight = 1000; - - $hasMoreThan28Headers = count($accept) > 28; - - foreach($processedHeaders as $headers) { - if (count($headers) > 0) { - $acceptHeaders[] = $this->adjustWeight($headers, $currentWeight, $hasMoreThan28Headers); - } - } - - $acceptHeaders = array_merge(...$acceptHeaders); - - return implode(',', $acceptHeaders); - } - - /** - * Given an Accept header, returns an associative array splitting the header and its weight - * - * @param string $header "Accept" Header - * - * @return array with the header and its weight - */ - private function getHeaderAndWeight(string $header): array - { - # matches headers with weight, splitting the header and the weight in $outputArray - if (preg_match('/(.*);\s*q=(1(?:\.0+)?|0\.\d+)$/', $header, $outputArray) === 1) { - $headerData = [ - 'header' => $outputArray[1], - 'weight' => (int)($outputArray[2] * 1000), - ]; - } else { - $headerData = [ - 'header' => trim($header), - 'weight' => 1000, - ]; - } - - return $headerData; - } - - /** - * @param array[] $headers - * @param float $currentWeight - * @param bool $hasMoreThan28Headers - * @return string[] array of adjusted "Accept" headers - */ - private function adjustWeight(array $headers, float &$currentWeight, bool $hasMoreThan28Headers): array - { - usort($headers, function (array $a, array $b) { - return $b['weight'] - $a['weight']; - }); - - $acceptHeaders = []; - foreach ($headers as $index => $header) { - if($index > 0 && $headers[$index - 1]['weight'] > $header['weight']) - { - $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); - } - - $weight = $currentWeight; - - $acceptHeaders[] = $this->buildAcceptHeader($header['header'], $weight); - } - - $currentWeight = $this->getNextWeight($currentWeight, $hasMoreThan28Headers); - - return $acceptHeaders; - } - - /** - * @param string $header - * @param int $weight - * @return string - */ - private function buildAcceptHeader(string $header, int $weight): string - { - if($weight === 1000) { - return $header; - } - - return trim($header, '; ') . ';q=' . rtrim(sprintf('%0.3f', $weight / 1000), '0'); - } - - /** - * Calculate the next weight, based on the current one. - * - * If there are less than 28 "Accept" headers, the weights will be decreased by 1 on its highest significant digit, using the - * following formula: - * - * next weight = current weight - 10 ^ (floor(log(current weight - 1))) - * - * ( current weight minus ( 10 raised to the power of ( floor of (log to the base 10 of ( current weight minus 1 ) ) ) ) ) - * - * Starting from 1000, this generates the following series: - * - * 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 - * - * The resulting quality codes are closer to the average "normal" usage of them (like "q=0.9", "q=0.8" and so on), but it only works - * if there is a maximum of 28 "Accept" headers. If we have more than that (which is extremely unlikely), then we fall back to a 1-by-1 - * decrement rule, which will result in quality codes like "q=0.999", "q=0.998" etc. - * - * @param int $currentWeight varying from 1 to 1000 (will be divided by 1000 to build the quality value) - * @param bool $hasMoreThan28Headers - * @return int - */ - public function getNextWeight(int $currentWeight, bool $hasMoreThan28Headers): int - { - if ($currentWeight <= 1) { - return 1; - } - - if ($hasMoreThan28Headers) { - return $currentWeight - 1; - } - - return $currentWeight - 10 ** floor( log10($currentWeight - 1) ); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php deleted file mode 100644 index 5a211d7e1752..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php +++ /dev/null @@ -1,443 +0,0 @@ - - */ -class AdditionalPropertiesClass implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'AdditionalPropertiesClass'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'map_property' => 'array', - 'map_of_map_property' => 'array>' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'map_property' => null, - 'map_of_map_property' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'map_property' => false, - 'map_of_map_property' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'map_property' => 'map_property', - 'map_of_map_property' => 'map_of_map_property' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'map_property' => 'setMapProperty', - 'map_of_map_property' => 'setMapOfMapProperty' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'map_property' => 'getMapProperty', - 'map_of_map_property' => 'getMapOfMapProperty' - ]; - - /** - * 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->setIfExists('map_property', $data ?? [], null); - $this->setIfExists('map_of_map_property', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 map_property - * - * @return array|null - */ - public function getMapProperty() - { - return $this->container['map_property']; - } - - /** - * Sets map_property - * - * @param array|null $map_property map_property - * - * @return self - */ - public function setMapProperty($map_property) - { - if (is_null($map_property)) { - throw new \InvalidArgumentException('non-nullable map_property cannot be null'); - } - $this->container['map_property'] = $map_property; - - return $this; - } - - /** - * Gets map_of_map_property - * - * @return array>|null - */ - public function getMapOfMapProperty() - { - return $this->container['map_of_map_property']; - } - - /** - * Sets map_of_map_property - * - * @param array>|null $map_of_map_property map_of_map_property - * - * @return self - */ - public function setMapOfMapProperty($map_of_map_property) - { - if (is_null($map_of_map_property)) { - throw new \InvalidArgumentException('non-nullable map_of_map_property cannot be null'); - } - $this->container['map_of_map_property'] = $map_of_map_property; - - 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-nextgen/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php deleted file mode 100644 index 9091da224f34..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php +++ /dev/null @@ -1,443 +0,0 @@ - - */ -class AllOfWithSingleRef implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'AllOfWithSingleRef'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'username' => 'string', - 'single_ref_type' => 'SingleRefType' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'username' => null, - 'single_ref_type' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'username' => false, - 'single_ref_type' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'username' => 'username', - 'single_ref_type' => 'SingleRefType' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'username' => 'setUsername', - 'single_ref_type' => 'setSingleRefType' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'username' => 'getUsername', - 'single_ref_type' => 'getSingleRefType' - ]; - - /** - * 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->setIfExists('username', $data ?? [], null); - $this->setIfExists('single_ref_type', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 username - * - * @return string|null - */ - public function getUsername() - { - return $this->container['username']; - } - - /** - * Sets username - * - * @param string|null $username username - * - * @return self - */ - public function setUsername($username) - { - if (is_null($username)) { - throw new \InvalidArgumentException('non-nullable username cannot be null'); - } - $this->container['username'] = $username; - - return $this; - } - - /** - * Gets single_ref_type - * - * @return SingleRefType|null - */ - public function getSingleRefType() - { - return $this->container['single_ref_type']; - } - - /** - * Sets single_ref_type - * - * @param SingleRefType|null $single_ref_type single_ref_type - * - * @return self - */ - public function setSingleRefType($single_ref_type) - { - if (is_null($single_ref_type)) { - throw new \InvalidArgumentException('non-nullable single_ref_type cannot be null'); - } - $this->container['single_ref_type'] = $single_ref_type; - - 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-nextgen/OpenAPIClient-php/lib/Model/Animal.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Animal.php deleted file mode 100644 index 415a65286146..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Animal.php +++ /dev/null @@ -1,449 +0,0 @@ - - */ -class Animal implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = 'class_name'; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Animal'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'class_name' => 'string', - 'color' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'class_name' => null, - 'color' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'class_name' => false, - 'color' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'class_name' => 'className', - 'color' => 'color' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'class_name' => 'setClassName', - 'color' => 'setColor' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'class_name' => 'getClassName', - 'color' => 'getColor' - ]; - - /** - * 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->setIfExists('class_name', $data ?? [], null); - $this->setIfExists('color', $data ?? [], 'red'); - - // Initialize discriminator property with the model name. - $this->container['class_name'] = static::$openAPIModelName; - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - if ($this->container['class_name'] === null) { - $invalidProperties[] = "'class_name' can't be null"; - } - 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 class_name - * - * @return string - */ - public function getClassName() - { - return $this->container['class_name']; - } - - /** - * Sets class_name - * - * @param string $class_name class_name - * - * @return self - */ - public function setClassName($class_name) - { - if (is_null($class_name)) { - throw new \InvalidArgumentException('non-nullable class_name cannot be null'); - } - $this->container['class_name'] = $class_name; - - return $this; - } - - /** - * Gets color - * - * @return string|null - */ - public function getColor() - { - return $this->container['color']; - } - - /** - * Sets color - * - * @param string|null $color color - * - * @return self - */ - public function setColor($color) - { - if (is_null($color)) { - throw new \InvalidArgumentException('non-nullable color cannot be null'); - } - $this->container['color'] = $color; - - 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-nextgen/OpenAPIClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ApiResponse.php deleted file mode 100644 index f624e8182af8..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ApiResponse.php +++ /dev/null @@ -1,477 +0,0 @@ - - */ -class ApiResponse implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'ApiResponse'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'code' => 'int', - 'type' => 'string', - 'message' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'code' => 'int32', - 'type' => null, - 'message' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'code' => false, - 'type' => false, - 'message' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'code' => 'code', - 'type' => 'type', - 'message' => 'message' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'code' => 'setCode', - 'type' => 'setType', - 'message' => 'setMessage' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'code' => 'getCode', - 'type' => 'getType', - 'message' => 'getMessage' - ]; - - /** - * 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->setIfExists('code', $data ?? [], null); - $this->setIfExists('type', $data ?? [], null); - $this->setIfExists('message', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 code - * - * @return int|null - */ - public function getCode() - { - return $this->container['code']; - } - - /** - * Sets code - * - * @param int|null $code code - * - * @return self - */ - public function setCode($code) - { - if (is_null($code)) { - throw new \InvalidArgumentException('non-nullable code cannot be null'); - } - $this->container['code'] = $code; - - return $this; - } - - /** - * Gets type - * - * @return string|null - */ - public function getType() - { - return $this->container['type']; - } - - /** - * Sets type - * - * @param string|null $type type - * - * @return self - */ - public function setType($type) - { - if (is_null($type)) { - throw new \InvalidArgumentException('non-nullable type cannot be null'); - } - $this->container['type'] = $type; - - return $this; - } - - /** - * Gets message - * - * @return string|null - */ - public function getMessage() - { - return $this->container['message']; - } - - /** - * Sets message - * - * @param string|null $message message - * - * @return self - */ - public function setMessage($message) - { - if (is_null($message)) { - throw new \InvalidArgumentException('non-nullable message cannot be null'); - } - $this->container['message'] = $message; - - 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-nextgen/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php deleted file mode 100644 index b09e0c111bcb..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class ArrayOfArrayOfNumberOnly implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'ArrayOfArrayOfNumberOnly'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'array_array_number' => 'float[][]' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'array_array_number' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'array_array_number' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'array_array_number' => 'ArrayArrayNumber' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'array_array_number' => 'setArrayArrayNumber' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'array_array_number' => 'getArrayArrayNumber' - ]; - - /** - * 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->setIfExists('array_array_number', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 array_array_number - * - * @return float[][]|null - */ - public function getArrayArrayNumber() - { - return $this->container['array_array_number']; - } - - /** - * Sets array_array_number - * - * @param float[][]|null $array_array_number array_array_number - * - * @return self - */ - public function setArrayArrayNumber($array_array_number) - { - if (is_null($array_array_number)) { - throw new \InvalidArgumentException('non-nullable array_array_number cannot be null'); - } - $this->container['array_array_number'] = $array_array_number; - - 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-nextgen/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php deleted file mode 100644 index 27606ad1816c..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class ArrayOfNumberOnly implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'ArrayOfNumberOnly'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'array_number' => 'float[]' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'array_number' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'array_number' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'array_number' => 'ArrayNumber' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'array_number' => 'setArrayNumber' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'array_number' => 'getArrayNumber' - ]; - - /** - * 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->setIfExists('array_number', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 array_number - * - * @return float[]|null - */ - public function getArrayNumber() - { - return $this->container['array_number']; - } - - /** - * Sets array_number - * - * @param float[]|null $array_number array_number - * - * @return self - */ - public function setArrayNumber($array_number) - { - if (is_null($array_number)) { - throw new \InvalidArgumentException('non-nullable array_number cannot be null'); - } - $this->container['array_number'] = $array_number; - - 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-nextgen/OpenAPIClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ArrayTest.php deleted file mode 100644 index f8da0740ca5e..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ArrayTest.php +++ /dev/null @@ -1,492 +0,0 @@ - - */ -class ArrayTest implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'ArrayTest'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'array_of_string' => 'string[]', - 'array_array_of_integer' => 'int[][]', - 'array_array_of_model' => '\OpenAPI\Client\Model\ReadOnlyFirst[][]' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'array_of_string' => null, - 'array_array_of_integer' => 'int64', - 'array_array_of_model' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'array_of_string' => false, - 'array_array_of_integer' => false, - 'array_array_of_model' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'array_of_string' => 'array_of_string', - 'array_array_of_integer' => 'array_array_of_integer', - 'array_array_of_model' => 'array_array_of_model' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'array_of_string' => 'setArrayOfString', - 'array_array_of_integer' => 'setArrayArrayOfInteger', - 'array_array_of_model' => 'setArrayArrayOfModel' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'array_of_string' => 'getArrayOfString', - 'array_array_of_integer' => 'getArrayArrayOfInteger', - 'array_array_of_model' => 'getArrayArrayOfModel' - ]; - - /** - * 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->setIfExists('array_of_string', $data ?? [], null); - $this->setIfExists('array_array_of_integer', $data ?? [], null); - $this->setIfExists('array_array_of_model', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - if (!is_null($this->container['array_of_string']) && (count($this->container['array_of_string']) > 3)) { - $invalidProperties[] = "invalid value for 'array_of_string', number of items must be less than or equal to 3."; - } - - if (!is_null($this->container['array_of_string']) && (count($this->container['array_of_string']) < 0)) { - $invalidProperties[] = "invalid value for 'array_of_string', number of items must be greater than or equal to 0."; - } - - 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 array_of_string - * - * @return string[]|null - */ - public function getArrayOfString() - { - return $this->container['array_of_string']; - } - - /** - * Sets array_of_string - * - * @param string[]|null $array_of_string array_of_string - * - * @return self - */ - public function setArrayOfString($array_of_string) - { - if (is_null($array_of_string)) { - throw new \InvalidArgumentException('non-nullable array_of_string cannot be null'); - } - - if ((count($array_of_string) > 3)) { - throw new \InvalidArgumentException('invalid value for $array_of_string when calling ArrayTest., number of items must be less than or equal to 3.'); - } - if ((count($array_of_string) < 0)) { - throw new \InvalidArgumentException('invalid length for $array_of_string when calling ArrayTest., number of items must be greater than or equal to 0.'); - } - $this->container['array_of_string'] = $array_of_string; - - return $this; - } - - /** - * Gets array_array_of_integer - * - * @return int[][]|null - */ - public function getArrayArrayOfInteger() - { - return $this->container['array_array_of_integer']; - } - - /** - * Sets array_array_of_integer - * - * @param int[][]|null $array_array_of_integer array_array_of_integer - * - * @return self - */ - public function setArrayArrayOfInteger($array_array_of_integer) - { - if (is_null($array_array_of_integer)) { - throw new \InvalidArgumentException('non-nullable array_array_of_integer cannot be null'); - } - $this->container['array_array_of_integer'] = $array_array_of_integer; - - return $this; - } - - /** - * Gets array_array_of_model - * - * @return \OpenAPI\Client\Model\ReadOnlyFirst[][]|null - */ - public function getArrayArrayOfModel() - { - return $this->container['array_array_of_model']; - } - - /** - * Sets array_array_of_model - * - * @param \OpenAPI\Client\Model\ReadOnlyFirst[][]|null $array_array_of_model array_array_of_model - * - * @return self - */ - public function setArrayArrayOfModel($array_array_of_model) - { - if (is_null($array_array_of_model)) { - throw new \InvalidArgumentException('non-nullable array_array_of_model cannot be null'); - } - $this->container['array_array_of_model'] = $array_array_of_model; - - 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-nextgen/OpenAPIClient-php/lib/Model/Capitalization.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Capitalization.php deleted file mode 100644 index 1bbb0ff5dcd9..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Capitalization.php +++ /dev/null @@ -1,579 +0,0 @@ - - */ -class Capitalization implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Capitalization'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'small_camel' => 'string', - 'capital_camel' => 'string', - 'small_snake' => 'string', - 'capital_snake' => 'string', - 'sca_eth_flow_points' => 'string', - 'att_name' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'small_camel' => null, - 'capital_camel' => null, - 'small_snake' => null, - 'capital_snake' => null, - 'sca_eth_flow_points' => null, - 'att_name' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'small_camel' => false, - 'capital_camel' => false, - 'small_snake' => false, - 'capital_snake' => false, - 'sca_eth_flow_points' => false, - 'att_name' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'small_camel' => 'smallCamel', - 'capital_camel' => 'CapitalCamel', - 'small_snake' => 'small_Snake', - 'capital_snake' => 'Capital_Snake', - 'sca_eth_flow_points' => 'SCA_ETH_Flow_Points', - 'att_name' => 'ATT_NAME' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'small_camel' => 'setSmallCamel', - 'capital_camel' => 'setCapitalCamel', - 'small_snake' => 'setSmallSnake', - 'capital_snake' => 'setCapitalSnake', - 'sca_eth_flow_points' => 'setScaEthFlowPoints', - 'att_name' => 'setAttName' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'small_camel' => 'getSmallCamel', - 'capital_camel' => 'getCapitalCamel', - 'small_snake' => 'getSmallSnake', - 'capital_snake' => 'getCapitalSnake', - 'sca_eth_flow_points' => 'getScaEthFlowPoints', - 'att_name' => 'getAttName' - ]; - - /** - * 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->setIfExists('small_camel', $data ?? [], null); - $this->setIfExists('capital_camel', $data ?? [], null); - $this->setIfExists('small_snake', $data ?? [], null); - $this->setIfExists('capital_snake', $data ?? [], null); - $this->setIfExists('sca_eth_flow_points', $data ?? [], null); - $this->setIfExists('att_name', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 small_camel - * - * @return string|null - */ - public function getSmallCamel() - { - return $this->container['small_camel']; - } - - /** - * Sets small_camel - * - * @param string|null $small_camel small_camel - * - * @return self - */ - public function setSmallCamel($small_camel) - { - if (is_null($small_camel)) { - throw new \InvalidArgumentException('non-nullable small_camel cannot be null'); - } - $this->container['small_camel'] = $small_camel; - - return $this; - } - - /** - * Gets capital_camel - * - * @return string|null - */ - public function getCapitalCamel() - { - return $this->container['capital_camel']; - } - - /** - * Sets capital_camel - * - * @param string|null $capital_camel capital_camel - * - * @return self - */ - public function setCapitalCamel($capital_camel) - { - if (is_null($capital_camel)) { - throw new \InvalidArgumentException('non-nullable capital_camel cannot be null'); - } - $this->container['capital_camel'] = $capital_camel; - - return $this; - } - - /** - * Gets small_snake - * - * @return string|null - */ - public function getSmallSnake() - { - return $this->container['small_snake']; - } - - /** - * Sets small_snake - * - * @param string|null $small_snake small_snake - * - * @return self - */ - public function setSmallSnake($small_snake) - { - if (is_null($small_snake)) { - throw new \InvalidArgumentException('non-nullable small_snake cannot be null'); - } - $this->container['small_snake'] = $small_snake; - - return $this; - } - - /** - * Gets capital_snake - * - * @return string|null - */ - public function getCapitalSnake() - { - return $this->container['capital_snake']; - } - - /** - * Sets capital_snake - * - * @param string|null $capital_snake capital_snake - * - * @return self - */ - public function setCapitalSnake($capital_snake) - { - if (is_null($capital_snake)) { - throw new \InvalidArgumentException('non-nullable capital_snake cannot be null'); - } - $this->container['capital_snake'] = $capital_snake; - - return $this; - } - - /** - * Gets sca_eth_flow_points - * - * @return string|null - */ - public function getScaEthFlowPoints() - { - return $this->container['sca_eth_flow_points']; - } - - /** - * Sets sca_eth_flow_points - * - * @param string|null $sca_eth_flow_points sca_eth_flow_points - * - * @return self - */ - public function setScaEthFlowPoints($sca_eth_flow_points) - { - if (is_null($sca_eth_flow_points)) { - throw new \InvalidArgumentException('non-nullable sca_eth_flow_points cannot be null'); - } - $this->container['sca_eth_flow_points'] = $sca_eth_flow_points; - - return $this; - } - - /** - * Gets att_name - * - * @return string|null - */ - public function getAttName() - { - return $this->container['att_name']; - } - - /** - * Sets att_name - * - * @param string|null $att_name Name of the pet - * - * @return self - */ - public function setAttName($att_name) - { - if (is_null($att_name)) { - throw new \InvalidArgumentException('non-nullable att_name cannot be null'); - } - $this->container['att_name'] = $att_name; - - 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-nextgen/OpenAPIClient-php/lib/Model/Cat.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Cat.php deleted file mode 100644 index 08f6ce145766..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Cat.php +++ /dev/null @@ -1,403 +0,0 @@ - - */ -class Cat extends Animal -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Cat'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'declawed' => 'bool' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'declawed' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'declawed' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPITypes() - { - return self::$openAPITypes + parent::openAPITypes(); - } - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPIFormats() - { - return self::$openAPIFormats + parent::openAPIFormats(); - } - - /** - * Array of nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables + parent::openAPINullables(); - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'declawed' => 'declawed' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'declawed' => 'setDeclawed' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'declawed' => 'getDeclawed' - ]; - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @return array - */ - public static function attributeMap() - { - return parent::attributeMap() + self::$attributeMap; - } - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @return array - */ - public static function setters() - { - return parent::setters() + self::$setters; - } - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @return array - */ - public static function getters() - { - return parent::getters() + self::$getters; - } - - /** - * The original name of the model. - * - * @return string - */ - public function getModelName() - { - return self::$openAPIModelName; - } - - - - /** - * Constructor - * - * @param mixed[] $data Associated array of property values - * initializing the model - */ - public function __construct(array $data = null) - { - parent::__construct($data); - - $this->setIfExists('declawed', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = parent::listInvalidProperties(); - - 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 declawed - * - * @return bool|null - */ - public function getDeclawed() - { - return $this->container['declawed']; - } - - /** - * Sets declawed - * - * @param bool|null $declawed declawed - * - * @return self - */ - public function setDeclawed($declawed) - { - if (is_null($declawed)) { - throw new \InvalidArgumentException('non-nullable declawed cannot be null'); - } - $this->container['declawed'] = $declawed; - - 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-nextgen/OpenAPIClient-php/lib/Model/CatAllOf.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/CatAllOf.php deleted file mode 100644 index 823c4a7bb3bb..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/CatAllOf.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class CatAllOf implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Cat_allOf'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'declawed' => 'bool' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'declawed' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'declawed' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'declawed' => 'declawed' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'declawed' => 'setDeclawed' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'declawed' => 'getDeclawed' - ]; - - /** - * 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->setIfExists('declawed', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 declawed - * - * @return bool|null - */ - public function getDeclawed() - { - return $this->container['declawed']; - } - - /** - * Sets declawed - * - * @param bool|null $declawed declawed - * - * @return self - */ - public function setDeclawed($declawed) - { - if (is_null($declawed)) { - throw new \InvalidArgumentException('non-nullable declawed cannot be null'); - } - $this->container['declawed'] = $declawed; - - 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-nextgen/OpenAPIClient-php/lib/Model/Category.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Category.php deleted file mode 100644 index 1b3778ef9bf8..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Category.php +++ /dev/null @@ -1,446 +0,0 @@ - - */ -class Category implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Category'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'id' => 'int', - 'name' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'id' => 'int64', - 'name' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'id' => false, - 'name' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'id' => 'id', - 'name' => 'name' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'id' => 'setId', - 'name' => 'setName' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'id' => 'getId', - 'name' => 'getName' - ]; - - /** - * 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->setIfExists('id', $data ?? [], null); - $this->setIfExists('name', $data ?? [], 'default-name'); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - if ($this->container['name'] === null) { - $invalidProperties[] = "'name' can't be null"; - } - 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 id - * - * @return int|null - */ - public function getId() - { - return $this->container['id']; - } - - /** - * Sets id - * - * @param int|null $id id - * - * @return self - */ - public function setId($id) - { - if (is_null($id)) { - throw new \InvalidArgumentException('non-nullable id cannot be null'); - } - $this->container['id'] = $id; - - return $this; - } - - /** - * Gets name - * - * @return string - */ - public function getName() - { - return $this->container['name']; - } - - /** - * Sets name - * - * @param string $name name - * - * @return self - */ - public function setName($name) - { - if (is_null($name)) { - throw new \InvalidArgumentException('non-nullable name cannot be null'); - } - $this->container['name'] = $name; - - 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-nextgen/OpenAPIClient-php/lib/Model/ClassModel.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ClassModel.php deleted file mode 100644 index 37689b34d464..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ClassModel.php +++ /dev/null @@ -1,410 +0,0 @@ - - */ -class ClassModel implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'ClassModel'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - '_class' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - '_class' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - '_class' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - '_class' => '_class' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - '_class' => 'setClass' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - '_class' => 'getClass' - ]; - - /** - * 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->setIfExists('_class', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 _class - * - * @return string|null - */ - public function getClass() - { - return $this->container['_class']; - } - - /** - * Sets _class - * - * @param string|null $_class _class - * - * @return self - */ - public function setClass($_class) - { - if (is_null($_class)) { - throw new \InvalidArgumentException('non-nullable _class cannot be null'); - } - $this->container['_class'] = $_class; - - 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-nextgen/OpenAPIClient-php/lib/Model/Client.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Client.php deleted file mode 100644 index 8e1156b2af89..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Client.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class Client implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Client'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'client' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'client' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'client' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'client' => 'client' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'client' => 'setClient' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'client' => 'getClient' - ]; - - /** - * 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->setIfExists('client', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 client - * - * @return string|null - */ - public function getClient() - { - return $this->container['client']; - } - - /** - * Sets client - * - * @param string|null $client client - * - * @return self - */ - public function setClient($client) - { - if (is_null($client)) { - throw new \InvalidArgumentException('non-nullable client cannot be null'); - } - $this->container['client'] = $client; - - 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-nextgen/OpenAPIClient-php/lib/Model/DeprecatedObject.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/DeprecatedObject.php deleted file mode 100644 index 29d7f7370405..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/DeprecatedObject.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class DeprecatedObject implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'DeprecatedObject'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'name' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'name' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'name' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'name' => 'name' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'name' => 'setName' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'name' => 'getName' - ]; - - /** - * 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->setIfExists('name', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 name - * - * @return string|null - */ - public function getName() - { - return $this->container['name']; - } - - /** - * Sets name - * - * @param string|null $name name - * - * @return self - */ - public function setName($name) - { - if (is_null($name)) { - throw new \InvalidArgumentException('non-nullable name cannot be null'); - } - $this->container['name'] = $name; - - 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-nextgen/OpenAPIClient-php/lib/Model/Dog.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Dog.php deleted file mode 100644 index f07e9a454d80..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Dog.php +++ /dev/null @@ -1,403 +0,0 @@ - - */ -class Dog extends Animal -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Dog'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'breed' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'breed' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'breed' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPITypes() - { - return self::$openAPITypes + parent::openAPITypes(); - } - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @return array - */ - public static function openAPIFormats() - { - return self::$openAPIFormats + parent::openAPIFormats(); - } - - /** - * Array of nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables + parent::openAPINullables(); - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'breed' => 'breed' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'breed' => 'setBreed' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'breed' => 'getBreed' - ]; - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @return array - */ - public static function attributeMap() - { - return parent::attributeMap() + self::$attributeMap; - } - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @return array - */ - public static function setters() - { - return parent::setters() + self::$setters; - } - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @return array - */ - public static function getters() - { - return parent::getters() + self::$getters; - } - - /** - * The original name of the model. - * - * @return string - */ - public function getModelName() - { - return self::$openAPIModelName; - } - - - - /** - * Constructor - * - * @param mixed[] $data Associated array of property values - * initializing the model - */ - public function __construct(array $data = null) - { - parent::__construct($data); - - $this->setIfExists('breed', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = parent::listInvalidProperties(); - - 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 breed - * - * @return string|null - */ - public function getBreed() - { - return $this->container['breed']; - } - - /** - * Sets breed - * - * @param string|null $breed breed - * - * @return self - */ - public function setBreed($breed) - { - if (is_null($breed)) { - throw new \InvalidArgumentException('non-nullable breed cannot be null'); - } - $this->container['breed'] = $breed; - - 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-nextgen/OpenAPIClient-php/lib/Model/DogAllOf.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/DogAllOf.php deleted file mode 100644 index f35440ead3b0..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/DogAllOf.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class DogAllOf implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Dog_allOf'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'breed' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'breed' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'breed' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'breed' => 'breed' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'breed' => 'setBreed' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'breed' => 'getBreed' - ]; - - /** - * 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->setIfExists('breed', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 breed - * - * @return string|null - */ - public function getBreed() - { - return $this->container['breed']; - } - - /** - * Sets breed - * - * @param string|null $breed breed - * - * @return self - */ - public function setBreed($breed) - { - if (is_null($breed)) { - throw new \InvalidArgumentException('non-nullable breed cannot be null'); - } - $this->container['breed'] = $breed; - - 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-nextgen/OpenAPIClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/EnumArrays.php deleted file mode 100644 index eeb2b7c00ee4..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/EnumArrays.php +++ /dev/null @@ -1,501 +0,0 @@ - - */ -class EnumArrays implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'EnumArrays'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'just_symbol' => 'string', - 'array_enum' => 'string[]' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'just_symbol' => null, - 'array_enum' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'just_symbol' => false, - 'array_enum' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'just_symbol' => 'just_symbol', - 'array_enum' => 'array_enum' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'just_symbol' => 'setJustSymbol', - 'array_enum' => 'setArrayEnum' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'just_symbol' => 'getJustSymbol', - 'array_enum' => 'getArrayEnum' - ]; - - /** - * 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; - } - - public const JUST_SYMBOL_GREATER_THAN_OR_EQUAL_TO = '>='; - public const JUST_SYMBOL_DOLLAR = '$'; - public const ARRAY_ENUM_FISH = 'fish'; - public const ARRAY_ENUM_CRAB = 'crab'; - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getJustSymbolAllowableValues() - { - return [ - self::JUST_SYMBOL_GREATER_THAN_OR_EQUAL_TO, - self::JUST_SYMBOL_DOLLAR, - ]; - } - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getArrayEnumAllowableValues() - { - return [ - self::ARRAY_ENUM_FISH, - self::ARRAY_ENUM_CRAB, - ]; - } - - /** - * 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->setIfExists('just_symbol', $data ?? [], null); - $this->setIfExists('array_enum', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - $allowedValues = $this->getJustSymbolAllowableValues(); - if (!is_null($this->container['just_symbol']) && !in_array($this->container['just_symbol'], $allowedValues, true)) { - $invalidProperties[] = sprintf( - "invalid value '%s' for 'just_symbol', must be one of '%s'", - $this->container['just_symbol'], - implode("', '", $allowedValues) - ); - } - - 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 just_symbol - * - * @return string|null - */ - public function getJustSymbol() - { - return $this->container['just_symbol']; - } - - /** - * Sets just_symbol - * - * @param string|null $just_symbol just_symbol - * - * @return self - */ - public function setJustSymbol($just_symbol) - { - if (is_null($just_symbol)) { - throw new \InvalidArgumentException('non-nullable just_symbol cannot be null'); - } - $allowedValues = $this->getJustSymbolAllowableValues(); - if (!in_array($just_symbol, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value '%s' for 'just_symbol', must be one of '%s'", - $just_symbol, - implode("', '", $allowedValues) - ) - ); - } - $this->container['just_symbol'] = $just_symbol; - - return $this; - } - - /** - * Gets array_enum - * - * @return string[]|null - */ - public function getArrayEnum() - { - return $this->container['array_enum']; - } - - /** - * Sets array_enum - * - * @param string[]|null $array_enum array_enum - * - * @return self - */ - public function setArrayEnum($array_enum) - { - if (is_null($array_enum)) { - throw new \InvalidArgumentException('non-nullable array_enum cannot be null'); - } - $allowedValues = $this->getArrayEnumAllowableValues(); - if (array_diff($array_enum, $allowedValues)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value for 'array_enum', must be one of '%s'", - implode("', '", $allowedValues) - ) - ); - } - $this->container['array_enum'] = $array_enum; - - 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-nextgen/OpenAPIClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/EnumClass.php deleted file mode 100644 index ace27356ba5b..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/EnumClass.php +++ /dev/null @@ -1,65 +0,0 @@ - - */ -class EnumTest implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Enum_Test'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'enum_string' => 'string', - 'enum_string_required' => 'string', - 'enum_integer' => 'int', - 'enum_number' => 'float', - 'outer_enum' => '\OpenAPI\Client\Model\OuterEnum', - 'outer_enum_integer' => '\OpenAPI\Client\Model\OuterEnumInteger', - 'outer_enum_default_value' => '\OpenAPI\Client\Model\OuterEnumDefaultValue', - 'outer_enum_integer_default_value' => '\OpenAPI\Client\Model\OuterEnumIntegerDefaultValue' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'enum_string' => null, - 'enum_string_required' => null, - 'enum_integer' => 'int32', - 'enum_number' => 'double', - 'outer_enum' => null, - 'outer_enum_integer' => null, - 'outer_enum_default_value' => null, - 'outer_enum_integer_default_value' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'enum_string' => false, - 'enum_string_required' => false, - 'enum_integer' => false, - 'enum_number' => false, - 'outer_enum' => true, - 'outer_enum_integer' => false, - 'outer_enum_default_value' => false, - 'outer_enum_integer_default_value' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'enum_string' => 'enum_string', - 'enum_string_required' => 'enum_string_required', - 'enum_integer' => 'enum_integer', - 'enum_number' => 'enum_number', - 'outer_enum' => 'outerEnum', - 'outer_enum_integer' => 'outerEnumInteger', - 'outer_enum_default_value' => 'outerEnumDefaultValue', - 'outer_enum_integer_default_value' => 'outerEnumIntegerDefaultValue' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'enum_string' => 'setEnumString', - 'enum_string_required' => 'setEnumStringRequired', - 'enum_integer' => 'setEnumInteger', - 'enum_number' => 'setEnumNumber', - 'outer_enum' => 'setOuterEnum', - 'outer_enum_integer' => 'setOuterEnumInteger', - 'outer_enum_default_value' => 'setOuterEnumDefaultValue', - 'outer_enum_integer_default_value' => 'setOuterEnumIntegerDefaultValue' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'enum_string' => 'getEnumString', - 'enum_string_required' => 'getEnumStringRequired', - 'enum_integer' => 'getEnumInteger', - 'enum_number' => 'getEnumNumber', - 'outer_enum' => 'getOuterEnum', - 'outer_enum_integer' => 'getOuterEnumInteger', - 'outer_enum_default_value' => 'getOuterEnumDefaultValue', - 'outer_enum_integer_default_value' => 'getOuterEnumIntegerDefaultValue' - ]; - - /** - * 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; - } - - public const ENUM_STRING_UPPER = 'UPPER'; - public const ENUM_STRING_LOWER = 'lower'; - public const ENUM_STRING_EMPTY = ''; - public const ENUM_STRING_REQUIRED_UPPER = 'UPPER'; - public const ENUM_STRING_REQUIRED_LOWER = 'lower'; - public const ENUM_STRING_REQUIRED_EMPTY = ''; - public const ENUM_INTEGER_1 = 1; - public const ENUM_INTEGER_MINUS_1 = -1; - public const ENUM_NUMBER_1_DOT_1 = 1.1; - public const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getEnumStringAllowableValues() - { - return [ - self::ENUM_STRING_UPPER, - self::ENUM_STRING_LOWER, - self::ENUM_STRING_EMPTY, - ]; - } - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getEnumStringRequiredAllowableValues() - { - return [ - self::ENUM_STRING_REQUIRED_UPPER, - self::ENUM_STRING_REQUIRED_LOWER, - self::ENUM_STRING_REQUIRED_EMPTY, - ]; - } - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getEnumIntegerAllowableValues() - { - return [ - self::ENUM_INTEGER_1, - self::ENUM_INTEGER_MINUS_1, - ]; - } - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getEnumNumberAllowableValues() - { - return [ - self::ENUM_NUMBER_1_DOT_1, - self::ENUM_NUMBER_MINUS_1_DOT_2, - ]; - } - - /** - * 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->setIfExists('enum_string', $data ?? [], null); - $this->setIfExists('enum_string_required', $data ?? [], null); - $this->setIfExists('enum_integer', $data ?? [], null); - $this->setIfExists('enum_number', $data ?? [], null); - $this->setIfExists('outer_enum', $data ?? [], null); - $this->setIfExists('outer_enum_integer', $data ?? [], null); - $this->setIfExists('outer_enum_default_value', $data ?? [], null); - $this->setIfExists('outer_enum_integer_default_value', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - $allowedValues = $this->getEnumStringAllowableValues(); - if (!is_null($this->container['enum_string']) && !in_array($this->container['enum_string'], $allowedValues, true)) { - $invalidProperties[] = sprintf( - "invalid value '%s' for 'enum_string', must be one of '%s'", - $this->container['enum_string'], - implode("', '", $allowedValues) - ); - } - - if ($this->container['enum_string_required'] === null) { - $invalidProperties[] = "'enum_string_required' can't be null"; - } - $allowedValues = $this->getEnumStringRequiredAllowableValues(); - if (!is_null($this->container['enum_string_required']) && !in_array($this->container['enum_string_required'], $allowedValues, true)) { - $invalidProperties[] = sprintf( - "invalid value '%s' for 'enum_string_required', must be one of '%s'", - $this->container['enum_string_required'], - implode("', '", $allowedValues) - ); - } - - $allowedValues = $this->getEnumIntegerAllowableValues(); - if (!is_null($this->container['enum_integer']) && !in_array($this->container['enum_integer'], $allowedValues, true)) { - $invalidProperties[] = sprintf( - "invalid value '%s' for 'enum_integer', must be one of '%s'", - $this->container['enum_integer'], - implode("', '", $allowedValues) - ); - } - - $allowedValues = $this->getEnumNumberAllowableValues(); - if (!is_null($this->container['enum_number']) && !in_array($this->container['enum_number'], $allowedValues, true)) { - $invalidProperties[] = sprintf( - "invalid value '%s' for 'enum_number', must be one of '%s'", - $this->container['enum_number'], - implode("', '", $allowedValues) - ); - } - - 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 enum_string - * - * @return string|null - */ - public function getEnumString() - { - return $this->container['enum_string']; - } - - /** - * Sets enum_string - * - * @param string|null $enum_string enum_string - * - * @return self - */ - public function setEnumString($enum_string) - { - if (is_null($enum_string)) { - throw new \InvalidArgumentException('non-nullable enum_string cannot be null'); - } - $allowedValues = $this->getEnumStringAllowableValues(); - if (!in_array($enum_string, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value '%s' for 'enum_string', must be one of '%s'", - $enum_string, - implode("', '", $allowedValues) - ) - ); - } - $this->container['enum_string'] = $enum_string; - - return $this; - } - - /** - * Gets enum_string_required - * - * @return string - */ - public function getEnumStringRequired() - { - return $this->container['enum_string_required']; - } - - /** - * Sets enum_string_required - * - * @param string $enum_string_required enum_string_required - * - * @return self - */ - public function setEnumStringRequired($enum_string_required) - { - if (is_null($enum_string_required)) { - throw new \InvalidArgumentException('non-nullable enum_string_required cannot be null'); - } - $allowedValues = $this->getEnumStringRequiredAllowableValues(); - if (!in_array($enum_string_required, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value '%s' for 'enum_string_required', must be one of '%s'", - $enum_string_required, - implode("', '", $allowedValues) - ) - ); - } - $this->container['enum_string_required'] = $enum_string_required; - - return $this; - } - - /** - * Gets enum_integer - * - * @return int|null - */ - public function getEnumInteger() - { - return $this->container['enum_integer']; - } - - /** - * Sets enum_integer - * - * @param int|null $enum_integer enum_integer - * - * @return self - */ - public function setEnumInteger($enum_integer) - { - if (is_null($enum_integer)) { - throw new \InvalidArgumentException('non-nullable enum_integer cannot be null'); - } - $allowedValues = $this->getEnumIntegerAllowableValues(); - if (!in_array($enum_integer, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value '%s' for 'enum_integer', must be one of '%s'", - $enum_integer, - implode("', '", $allowedValues) - ) - ); - } - $this->container['enum_integer'] = $enum_integer; - - return $this; - } - - /** - * Gets enum_number - * - * @return float|null - */ - public function getEnumNumber() - { - return $this->container['enum_number']; - } - - /** - * Sets enum_number - * - * @param float|null $enum_number enum_number - * - * @return self - */ - public function setEnumNumber($enum_number) - { - if (is_null($enum_number)) { - throw new \InvalidArgumentException('non-nullable enum_number cannot be null'); - } - $allowedValues = $this->getEnumNumberAllowableValues(); - if (!in_array($enum_number, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value '%s' for 'enum_number', must be one of '%s'", - $enum_number, - implode("', '", $allowedValues) - ) - ); - } - $this->container['enum_number'] = $enum_number; - - return $this; - } - - /** - * Gets outer_enum - * - * @return \OpenAPI\Client\Model\OuterEnum|null - */ - public function getOuterEnum() - { - return $this->container['outer_enum']; - } - - /** - * Sets outer_enum - * - * @param \OpenAPI\Client\Model\OuterEnum|null $outer_enum outer_enum - * - * @return self - */ - public function setOuterEnum($outer_enum) - { - if (is_null($outer_enum)) { - array_push($this->openAPINullablesSetToNull, 'outer_enum'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('outer_enum', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['outer_enum'] = $outer_enum; - - return $this; - } - - /** - * Gets outer_enum_integer - * - * @return \OpenAPI\Client\Model\OuterEnumInteger|null - */ - public function getOuterEnumInteger() - { - return $this->container['outer_enum_integer']; - } - - /** - * Sets outer_enum_integer - * - * @param \OpenAPI\Client\Model\OuterEnumInteger|null $outer_enum_integer outer_enum_integer - * - * @return self - */ - public function setOuterEnumInteger($outer_enum_integer) - { - if (is_null($outer_enum_integer)) { - throw new \InvalidArgumentException('non-nullable outer_enum_integer cannot be null'); - } - $this->container['outer_enum_integer'] = $outer_enum_integer; - - return $this; - } - - /** - * Gets outer_enum_default_value - * - * @return \OpenAPI\Client\Model\OuterEnumDefaultValue|null - */ - public function getOuterEnumDefaultValue() - { - return $this->container['outer_enum_default_value']; - } - - /** - * Sets outer_enum_default_value - * - * @param \OpenAPI\Client\Model\OuterEnumDefaultValue|null $outer_enum_default_value outer_enum_default_value - * - * @return self - */ - public function setOuterEnumDefaultValue($outer_enum_default_value) - { - if (is_null($outer_enum_default_value)) { - throw new \InvalidArgumentException('non-nullable outer_enum_default_value cannot be null'); - } - $this->container['outer_enum_default_value'] = $outer_enum_default_value; - - return $this; - } - - /** - * Gets outer_enum_integer_default_value - * - * @return \OpenAPI\Client\Model\OuterEnumIntegerDefaultValue|null - */ - public function getOuterEnumIntegerDefaultValue() - { - return $this->container['outer_enum_integer_default_value']; - } - - /** - * Sets outer_enum_integer_default_value - * - * @param \OpenAPI\Client\Model\OuterEnumIntegerDefaultValue|null $outer_enum_integer_default_value outer_enum_integer_default_value - * - * @return self - */ - public function setOuterEnumIntegerDefaultValue($outer_enum_integer_default_value) - { - if (is_null($outer_enum_integer_default_value)) { - throw new \InvalidArgumentException('non-nullable outer_enum_integer_default_value cannot be null'); - } - $this->container['outer_enum_integer_default_value'] = $outer_enum_integer_default_value; - - 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-nextgen/OpenAPIClient-php/lib/Model/File.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/File.php deleted file mode 100644 index 5227ccccf762..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/File.php +++ /dev/null @@ -1,410 +0,0 @@ - - */ -class File implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'File'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'source_uri' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'source_uri' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'source_uri' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'source_uri' => 'sourceURI' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'source_uri' => 'setSourceUri' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'source_uri' => 'getSourceUri' - ]; - - /** - * 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->setIfExists('source_uri', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 source_uri - * - * @return string|null - */ - public function getSourceUri() - { - return $this->container['source_uri']; - } - - /** - * Sets source_uri - * - * @param string|null $source_uri Test capitalization - * - * @return self - */ - public function setSourceUri($source_uri) - { - if (is_null($source_uri)) { - throw new \InvalidArgumentException('non-nullable source_uri cannot be null'); - } - $this->container['source_uri'] = $source_uri; - - 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-nextgen/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php deleted file mode 100644 index 40477eccf03c..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php +++ /dev/null @@ -1,443 +0,0 @@ - - */ -class FileSchemaTestClass implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'FileSchemaTestClass'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'file' => '\OpenAPI\Client\Model\File', - 'files' => '\OpenAPI\Client\Model\File[]' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'file' => null, - 'files' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'file' => false, - 'files' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'file' => 'file', - 'files' => 'files' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'file' => 'setFile', - 'files' => 'setFiles' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'file' => 'getFile', - 'files' => 'getFiles' - ]; - - /** - * 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->setIfExists('file', $data ?? [], null); - $this->setIfExists('files', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 file - * - * @return \OpenAPI\Client\Model\File|null - */ - public function getFile() - { - return $this->container['file']; - } - - /** - * Sets file - * - * @param \OpenAPI\Client\Model\File|null $file file - * - * @return self - */ - public function setFile($file) - { - if (is_null($file)) { - throw new \InvalidArgumentException('non-nullable file cannot be null'); - } - $this->container['file'] = $file; - - return $this; - } - - /** - * Gets files - * - * @return \OpenAPI\Client\Model\File[]|null - */ - public function getFiles() - { - return $this->container['files']; - } - - /** - * Sets files - * - * @param \OpenAPI\Client\Model\File[]|null $files files - * - * @return self - */ - public function setFiles($files) - { - if (is_null($files)) { - throw new \InvalidArgumentException('non-nullable files cannot be null'); - } - $this->container['files'] = $files; - - 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-nextgen/OpenAPIClient-php/lib/Model/Foo.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Foo.php deleted file mode 100644 index 3f2bd008dee7..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Foo.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class Foo implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Foo'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'bar' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'bar' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'bar' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'bar' => 'bar' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'bar' => 'setBar' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - '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->setIfExists('bar', $data ?? [], 'bar'); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 bar - * - * @return string|null - */ - public function getBar() - { - return $this->container['bar']; - } - - /** - * Sets bar - * - * @param string|null $bar bar - * - * @return self - */ - public function setBar($bar) - { - if (is_null($bar)) { - throw new \InvalidArgumentException('non-nullable bar cannot be null'); - } - $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-nextgen/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php deleted file mode 100644 index f532f9e2e55b..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class FooGetDefaultResponse implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = '_foo_get_default_response'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'string' => '\OpenAPI\Client\Model\Foo' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'string' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'string' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'string' => 'string' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'string' => 'setString' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'string' => 'getString' - ]; - - /** - * 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->setIfExists('string', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 string - * - * @return \OpenAPI\Client\Model\Foo|null - */ - public function getString() - { - return $this->container['string']; - } - - /** - * Sets string - * - * @param \OpenAPI\Client\Model\Foo|null $string string - * - * @return self - */ - public function setString($string) - { - if (is_null($string)) { - throw new \InvalidArgumentException('non-nullable string cannot be null'); - } - $this->container['string'] = $string; - - 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-nextgen/OpenAPIClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/FormatTest.php deleted file mode 100644 index 4149df86c5cf..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/FormatTest.php +++ /dev/null @@ -1,1053 +0,0 @@ - - */ -class FormatTest implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'format_test'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'integer' => 'int', - 'int32' => 'int', - 'int64' => 'int', - 'number' => 'float', - 'float' => 'float', - 'double' => 'float', - 'decimal' => 'float', - 'string' => 'string', - 'byte' => 'string', - 'binary' => '\SplFileObject', - 'date' => '\DateTime', - 'date_time' => '\DateTime', - 'uuid' => 'string', - 'password' => 'string', - 'pattern_with_digits' => 'string', - 'pattern_with_digits_and_delimiter' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'integer' => null, - 'int32' => 'int32', - 'int64' => 'int64', - 'number' => null, - 'float' => 'float', - 'double' => 'double', - 'decimal' => 'number', - 'string' => null, - 'byte' => 'byte', - 'binary' => 'binary', - 'date' => 'date', - 'date_time' => 'date-time', - 'uuid' => 'uuid', - 'password' => 'password', - 'pattern_with_digits' => null, - 'pattern_with_digits_and_delimiter' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'integer' => false, - 'int32' => false, - 'int64' => false, - 'number' => false, - 'float' => false, - 'double' => false, - 'decimal' => false, - 'string' => false, - 'byte' => false, - 'binary' => false, - 'date' => false, - 'date_time' => false, - 'uuid' => false, - 'password' => false, - 'pattern_with_digits' => false, - 'pattern_with_digits_and_delimiter' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'integer' => 'integer', - 'int32' => 'int32', - 'int64' => 'int64', - 'number' => 'number', - 'float' => 'float', - 'double' => 'double', - 'decimal' => 'decimal', - 'string' => 'string', - 'byte' => 'byte', - 'binary' => 'binary', - 'date' => 'date', - 'date_time' => 'dateTime', - 'uuid' => 'uuid', - 'password' => 'password', - 'pattern_with_digits' => 'pattern_with_digits', - 'pattern_with_digits_and_delimiter' => 'pattern_with_digits_and_delimiter' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'integer' => 'setInteger', - 'int32' => 'setInt32', - 'int64' => 'setInt64', - 'number' => 'setNumber', - 'float' => 'setFloat', - 'double' => 'setDouble', - 'decimal' => 'setDecimal', - 'string' => 'setString', - 'byte' => 'setByte', - 'binary' => 'setBinary', - 'date' => 'setDate', - 'date_time' => 'setDateTime', - 'uuid' => 'setUuid', - 'password' => 'setPassword', - 'pattern_with_digits' => 'setPatternWithDigits', - 'pattern_with_digits_and_delimiter' => 'setPatternWithDigitsAndDelimiter' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'integer' => 'getInteger', - 'int32' => 'getInt32', - 'int64' => 'getInt64', - 'number' => 'getNumber', - 'float' => 'getFloat', - 'double' => 'getDouble', - 'decimal' => 'getDecimal', - 'string' => 'getString', - 'byte' => 'getByte', - 'binary' => 'getBinary', - 'date' => 'getDate', - 'date_time' => 'getDateTime', - 'uuid' => 'getUuid', - 'password' => 'getPassword', - 'pattern_with_digits' => 'getPatternWithDigits', - 'pattern_with_digits_and_delimiter' => 'getPatternWithDigitsAndDelimiter' - ]; - - /** - * 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->setIfExists('integer', $data ?? [], null); - $this->setIfExists('int32', $data ?? [], null); - $this->setIfExists('int64', $data ?? [], null); - $this->setIfExists('number', $data ?? [], null); - $this->setIfExists('float', $data ?? [], null); - $this->setIfExists('double', $data ?? [], null); - $this->setIfExists('decimal', $data ?? [], null); - $this->setIfExists('string', $data ?? [], null); - $this->setIfExists('byte', $data ?? [], null); - $this->setIfExists('binary', $data ?? [], null); - $this->setIfExists('date', $data ?? [], null); - $this->setIfExists('date_time', $data ?? [], null); - $this->setIfExists('uuid', $data ?? [], null); - $this->setIfExists('password', $data ?? [], null); - $this->setIfExists('pattern_with_digits', $data ?? [], null); - $this->setIfExists('pattern_with_digits_and_delimiter', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - if (!is_null($this->container['integer']) && ($this->container['integer'] > 100)) { - $invalidProperties[] = "invalid value for 'integer', must be smaller than or equal to 100."; - } - - if (!is_null($this->container['integer']) && ($this->container['integer'] < 10)) { - $invalidProperties[] = "invalid value for 'integer', must be bigger than or equal to 10."; - } - - if (!is_null($this->container['int32']) && ($this->container['int32'] > 200)) { - $invalidProperties[] = "invalid value for 'int32', must be smaller than or equal to 200."; - } - - if (!is_null($this->container['int32']) && ($this->container['int32'] < 20)) { - $invalidProperties[] = "invalid value for 'int32', must be bigger than or equal to 20."; - } - - if ($this->container['number'] === null) { - $invalidProperties[] = "'number' can't be null"; - } - if (($this->container['number'] > 543.2)) { - $invalidProperties[] = "invalid value for 'number', must be smaller than or equal to 543.2."; - } - - if (($this->container['number'] < 32.1)) { - $invalidProperties[] = "invalid value for 'number', must be bigger than or equal to 32.1."; - } - - if (!is_null($this->container['float']) && ($this->container['float'] > 987.6)) { - $invalidProperties[] = "invalid value for 'float', must be smaller than or equal to 987.6."; - } - - if (!is_null($this->container['float']) && ($this->container['float'] < 54.3)) { - $invalidProperties[] = "invalid value for 'float', must be bigger than or equal to 54.3."; - } - - if (!is_null($this->container['double']) && ($this->container['double'] > 123.4)) { - $invalidProperties[] = "invalid value for 'double', must be smaller than or equal to 123.4."; - } - - if (!is_null($this->container['double']) && ($this->container['double'] < 67.8)) { - $invalidProperties[] = "invalid value for 'double', must be bigger than or equal to 67.8."; - } - - if (!is_null($this->container['string']) && !preg_match("/[a-z]/i", $this->container['string'])) { - $invalidProperties[] = "invalid value for 'string', must be conform to the pattern /[a-z]/i."; - } - - if ($this->container['byte'] === null) { - $invalidProperties[] = "'byte' can't be null"; - } - if ($this->container['date'] === null) { - $invalidProperties[] = "'date' can't be null"; - } - if ($this->container['password'] === null) { - $invalidProperties[] = "'password' can't be null"; - } - if ((mb_strlen($this->container['password']) > 64)) { - $invalidProperties[] = "invalid value for 'password', the character length must be smaller than or equal to 64."; - } - - if ((mb_strlen($this->container['password']) < 10)) { - $invalidProperties[] = "invalid value for 'password', the character length must be bigger than or equal to 10."; - } - - if (!is_null($this->container['pattern_with_digits']) && !preg_match("/^\\d{10}$/", $this->container['pattern_with_digits'])) { - $invalidProperties[] = "invalid value for 'pattern_with_digits', must be conform to the pattern /^\\d{10}$/."; - } - - if (!is_null($this->container['pattern_with_digits_and_delimiter']) && !preg_match("/^image_\\d{1,3}$/i", $this->container['pattern_with_digits_and_delimiter'])) { - $invalidProperties[] = "invalid value for 'pattern_with_digits_and_delimiter', must be conform to the pattern /^image_\\d{1,3}$/i."; - } - - 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 integer - * - * @return int|null - */ - public function getInteger() - { - return $this->container['integer']; - } - - /** - * Sets integer - * - * @param int|null $integer integer - * - * @return self - */ - public function setInteger($integer) - { - if (is_null($integer)) { - throw new \InvalidArgumentException('non-nullable integer cannot be null'); - } - - if (($integer > 100)) { - throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be smaller than or equal to 100.'); - } - if (($integer < 10)) { - throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be bigger than or equal to 10.'); - } - - $this->container['integer'] = $integer; - - return $this; - } - - /** - * Gets int32 - * - * @return int|null - */ - public function getInt32() - { - return $this->container['int32']; - } - - /** - * Sets int32 - * - * @param int|null $int32 int32 - * - * @return self - */ - public function setInt32($int32) - { - if (is_null($int32)) { - throw new \InvalidArgumentException('non-nullable int32 cannot be null'); - } - - if (($int32 > 200)) { - throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be smaller than or equal to 200.'); - } - if (($int32 < 20)) { - throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be bigger than or equal to 20.'); - } - - $this->container['int32'] = $int32; - - return $this; - } - - /** - * Gets int64 - * - * @return int|null - */ - public function getInt64() - { - return $this->container['int64']; - } - - /** - * Sets int64 - * - * @param int|null $int64 int64 - * - * @return self - */ - public function setInt64($int64) - { - if (is_null($int64)) { - throw new \InvalidArgumentException('non-nullable int64 cannot be null'); - } - $this->container['int64'] = $int64; - - return $this; - } - - /** - * Gets number - * - * @return float - */ - public function getNumber() - { - return $this->container['number']; - } - - /** - * Sets number - * - * @param float $number number - * - * @return self - */ - public function setNumber($number) - { - if (is_null($number)) { - throw new \InvalidArgumentException('non-nullable number cannot be null'); - } - - if (($number > 543.2)) { - throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be smaller than or equal to 543.2.'); - } - if (($number < 32.1)) { - throw new \InvalidArgumentException('invalid value for $number when calling FormatTest., must be bigger than or equal to 32.1.'); - } - - $this->container['number'] = $number; - - return $this; - } - - /** - * Gets float - * - * @return float|null - */ - public function getFloat() - { - return $this->container['float']; - } - - /** - * Sets float - * - * @param float|null $float float - * - * @return self - */ - public function setFloat($float) - { - if (is_null($float)) { - throw new \InvalidArgumentException('non-nullable float cannot be null'); - } - - if (($float > 987.6)) { - throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be smaller than or equal to 987.6.'); - } - if (($float < 54.3)) { - throw new \InvalidArgumentException('invalid value for $float when calling FormatTest., must be bigger than or equal to 54.3.'); - } - - $this->container['float'] = $float; - - return $this; - } - - /** - * Gets double - * - * @return float|null - */ - public function getDouble() - { - return $this->container['double']; - } - - /** - * Sets double - * - * @param float|null $double double - * - * @return self - */ - public function setDouble($double) - { - if (is_null($double)) { - throw new \InvalidArgumentException('non-nullable double cannot be null'); - } - - if (($double > 123.4)) { - throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be smaller than or equal to 123.4.'); - } - if (($double < 67.8)) { - throw new \InvalidArgumentException('invalid value for $double when calling FormatTest., must be bigger than or equal to 67.8.'); - } - - $this->container['double'] = $double; - - return $this; - } - - /** - * Gets decimal - * - * @return float|null - */ - public function getDecimal() - { - return $this->container['decimal']; - } - - /** - * Sets decimal - * - * @param float|null $decimal decimal - * - * @return self - */ - public function setDecimal($decimal) - { - if (is_null($decimal)) { - throw new \InvalidArgumentException('non-nullable decimal cannot be null'); - } - $this->container['decimal'] = $decimal; - - return $this; - } - - /** - * Gets string - * - * @return string|null - */ - public function getString() - { - return $this->container['string']; - } - - /** - * Sets string - * - * @param string|null $string string - * - * @return self - */ - public function setString($string) - { - if (is_null($string)) { - throw new \InvalidArgumentException('non-nullable string cannot be null'); - } - - if ((!preg_match("/[a-z]/i", $string))) { - throw new \InvalidArgumentException("invalid value for \$string when calling FormatTest., must conform to the pattern /[a-z]/i."); - } - - $this->container['string'] = $string; - - return $this; - } - - /** - * Gets byte - * - * @return string - */ - public function getByte() - { - return $this->container['byte']; - } - - /** - * Sets byte - * - * @param string $byte byte - * - * @return self - */ - public function setByte($byte) - { - if (is_null($byte)) { - throw new \InvalidArgumentException('non-nullable byte cannot be null'); - } - $this->container['byte'] = $byte; - - return $this; - } - - /** - * Gets binary - * - * @return \SplFileObject|null - */ - public function getBinary() - { - return $this->container['binary']; - } - - /** - * Sets binary - * - * @param \SplFileObject|null $binary binary - * - * @return self - */ - public function setBinary($binary) - { - if (is_null($binary)) { - throw new \InvalidArgumentException('non-nullable binary cannot be null'); - } - $this->container['binary'] = $binary; - - return $this; - } - - /** - * Gets date - * - * @return \DateTime - */ - public function getDate() - { - return $this->container['date']; - } - - /** - * Sets date - * - * @param \DateTime $date date - * - * @return self - */ - public function setDate($date) - { - if (is_null($date)) { - throw new \InvalidArgumentException('non-nullable date cannot be null'); - } - $this->container['date'] = $date; - - return $this; - } - - /** - * Gets date_time - * - * @return \DateTime|null - */ - public function getDateTime() - { - return $this->container['date_time']; - } - - /** - * Sets date_time - * - * @param \DateTime|null $date_time date_time - * - * @return self - */ - public function setDateTime($date_time) - { - if (is_null($date_time)) { - throw new \InvalidArgumentException('non-nullable date_time cannot be null'); - } - $this->container['date_time'] = $date_time; - - return $this; - } - - /** - * Gets uuid - * - * @return string|null - */ - public function getUuid() - { - return $this->container['uuid']; - } - - /** - * Sets uuid - * - * @param string|null $uuid uuid - * - * @return self - */ - public function setUuid($uuid) - { - if (is_null($uuid)) { - throw new \InvalidArgumentException('non-nullable uuid cannot be null'); - } - $this->container['uuid'] = $uuid; - - return $this; - } - - /** - * Gets password - * - * @return string - */ - public function getPassword() - { - return $this->container['password']; - } - - /** - * Sets password - * - * @param string $password password - * - * @return self - */ - public function setPassword($password) - { - if (is_null($password)) { - throw new \InvalidArgumentException('non-nullable password cannot be null'); - } - if ((mb_strlen($password) > 64)) { - throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be smaller than or equal to 64.'); - } - if ((mb_strlen($password) < 10)) { - throw new \InvalidArgumentException('invalid length for $password when calling FormatTest., must be bigger than or equal to 10.'); - } - - $this->container['password'] = $password; - - return $this; - } - - /** - * Gets pattern_with_digits - * - * @return string|null - */ - public function getPatternWithDigits() - { - return $this->container['pattern_with_digits']; - } - - /** - * Sets pattern_with_digits - * - * @param string|null $pattern_with_digits A string that is a 10 digit number. Can have leading zeros. - * - * @return self - */ - public function setPatternWithDigits($pattern_with_digits) - { - if (is_null($pattern_with_digits)) { - throw new \InvalidArgumentException('non-nullable pattern_with_digits cannot be null'); - } - - if ((!preg_match("/^\\d{10}$/", $pattern_with_digits))) { - throw new \InvalidArgumentException("invalid value for \$pattern_with_digits when calling FormatTest., must conform to the pattern /^\\d{10}$/."); - } - - $this->container['pattern_with_digits'] = $pattern_with_digits; - - return $this; - } - - /** - * Gets pattern_with_digits_and_delimiter - * - * @return string|null - */ - public function getPatternWithDigitsAndDelimiter() - { - return $this->container['pattern_with_digits_and_delimiter']; - } - - /** - * Sets pattern_with_digits_and_delimiter - * - * @param string|null $pattern_with_digits_and_delimiter A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. - * - * @return self - */ - public function setPatternWithDigitsAndDelimiter($pattern_with_digits_and_delimiter) - { - if (is_null($pattern_with_digits_and_delimiter)) { - throw new \InvalidArgumentException('non-nullable pattern_with_digits_and_delimiter cannot be null'); - } - - if ((!preg_match("/^image_\\d{1,3}$/i", $pattern_with_digits_and_delimiter))) { - throw new \InvalidArgumentException("invalid value for \$pattern_with_digits_and_delimiter when calling FormatTest., must conform to the pattern /^image_\\d{1,3}$/i."); - } - - $this->container['pattern_with_digits_and_delimiter'] = $pattern_with_digits_and_delimiter; - - 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-nextgen/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php deleted file mode 100644 index baa160cc19b1..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php +++ /dev/null @@ -1,443 +0,0 @@ - - */ -class HasOnlyReadOnly implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'hasOnlyReadOnly'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'bar' => 'string', - 'foo' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'bar' => null, - 'foo' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'bar' => false, - 'foo' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'bar' => 'bar', - 'foo' => 'foo' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'bar' => 'setBar', - 'foo' => 'setFoo' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'bar' => 'getBar', - '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->setIfExists('bar', $data ?? [], null); - $this->setIfExists('foo', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 bar - * - * @return string|null - */ - public function getBar() - { - return $this->container['bar']; - } - - /** - * Sets bar - * - * @param string|null $bar bar - * - * @return self - */ - public function setBar($bar) - { - if (is_null($bar)) { - throw new \InvalidArgumentException('non-nullable bar cannot be null'); - } - $this->container['bar'] = $bar; - - return $this; - } - - /** - * 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) - { - if (is_null($foo)) { - throw new \InvalidArgumentException('non-nullable foo cannot be null'); - } - $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-nextgen/OpenAPIClient-php/lib/Model/HealthCheckResult.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/HealthCheckResult.php deleted file mode 100644 index 07ec049c0965..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/HealthCheckResult.php +++ /dev/null @@ -1,417 +0,0 @@ - - */ -class HealthCheckResult implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'HealthCheckResult'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'nullable_message' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'nullable_message' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'nullable_message' => true - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'nullable_message' => 'NullableMessage' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'nullable_message' => 'setNullableMessage' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'nullable_message' => 'getNullableMessage' - ]; - - /** - * 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->setIfExists('nullable_message', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 nullable_message - * - * @return string|null - */ - public function getNullableMessage() - { - return $this->container['nullable_message']; - } - - /** - * Sets nullable_message - * - * @param string|null $nullable_message nullable_message - * - * @return self - */ - public function setNullableMessage($nullable_message) - { - if (is_null($nullable_message)) { - array_push($this->openAPINullablesSetToNull, 'nullable_message'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('nullable_message', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['nullable_message'] = $nullable_message; - - 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-nextgen/OpenAPIClient-php/lib/Model/MapTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/MapTest.php deleted file mode 100644 index 0bd72a04198c..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/MapTest.php +++ /dev/null @@ -1,535 +0,0 @@ - - */ -class MapTest implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'MapTest'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'map_map_of_string' => 'array>', - 'map_of_enum_string' => 'array', - 'direct_map' => 'array', - 'indirect_map' => 'array' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'map_map_of_string' => null, - 'map_of_enum_string' => null, - 'direct_map' => null, - 'indirect_map' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'map_map_of_string' => false, - 'map_of_enum_string' => false, - 'direct_map' => false, - 'indirect_map' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'map_map_of_string' => 'map_map_of_string', - 'map_of_enum_string' => 'map_of_enum_string', - 'direct_map' => 'direct_map', - 'indirect_map' => 'indirect_map' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'map_map_of_string' => 'setMapMapOfString', - 'map_of_enum_string' => 'setMapOfEnumString', - 'direct_map' => 'setDirectMap', - 'indirect_map' => 'setIndirectMap' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'map_map_of_string' => 'getMapMapOfString', - 'map_of_enum_string' => 'getMapOfEnumString', - 'direct_map' => 'getDirectMap', - 'indirect_map' => 'getIndirectMap' - ]; - - /** - * 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; - } - - public const MAP_OF_ENUM_STRING_UPPER = 'UPPER'; - public const MAP_OF_ENUM_STRING_LOWER = 'lower'; - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getMapOfEnumStringAllowableValues() - { - return [ - self::MAP_OF_ENUM_STRING_UPPER, - self::MAP_OF_ENUM_STRING_LOWER, - ]; - } - - /** - * 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->setIfExists('map_map_of_string', $data ?? [], null); - $this->setIfExists('map_of_enum_string', $data ?? [], null); - $this->setIfExists('direct_map', $data ?? [], null); - $this->setIfExists('indirect_map', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 map_map_of_string - * - * @return array>|null - */ - public function getMapMapOfString() - { - return $this->container['map_map_of_string']; - } - - /** - * Sets map_map_of_string - * - * @param array>|null $map_map_of_string map_map_of_string - * - * @return self - */ - public function setMapMapOfString($map_map_of_string) - { - if (is_null($map_map_of_string)) { - throw new \InvalidArgumentException('non-nullable map_map_of_string cannot be null'); - } - $this->container['map_map_of_string'] = $map_map_of_string; - - return $this; - } - - /** - * Gets map_of_enum_string - * - * @return array|null - */ - public function getMapOfEnumString() - { - return $this->container['map_of_enum_string']; - } - - /** - * Sets map_of_enum_string - * - * @param array|null $map_of_enum_string map_of_enum_string - * - * @return self - */ - public function setMapOfEnumString($map_of_enum_string) - { - if (is_null($map_of_enum_string)) { - throw new \InvalidArgumentException('non-nullable map_of_enum_string cannot be null'); - } - $allowedValues = $this->getMapOfEnumStringAllowableValues(); - if (array_diff($map_of_enum_string, $allowedValues)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value for 'map_of_enum_string', must be one of '%s'", - implode("', '", $allowedValues) - ) - ); - } - $this->container['map_of_enum_string'] = $map_of_enum_string; - - return $this; - } - - /** - * Gets direct_map - * - * @return array|null - */ - public function getDirectMap() - { - return $this->container['direct_map']; - } - - /** - * Sets direct_map - * - * @param array|null $direct_map direct_map - * - * @return self - */ - public function setDirectMap($direct_map) - { - if (is_null($direct_map)) { - throw new \InvalidArgumentException('non-nullable direct_map cannot be null'); - } - $this->container['direct_map'] = $direct_map; - - return $this; - } - - /** - * Gets indirect_map - * - * @return array|null - */ - public function getIndirectMap() - { - return $this->container['indirect_map']; - } - - /** - * Sets indirect_map - * - * @param array|null $indirect_map indirect_map - * - * @return self - */ - public function setIndirectMap($indirect_map) - { - if (is_null($indirect_map)) { - throw new \InvalidArgumentException('non-nullable indirect_map cannot be null'); - } - $this->container['indirect_map'] = $indirect_map; - - 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-nextgen/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php deleted file mode 100644 index e1b4aac29286..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ /dev/null @@ -1,477 +0,0 @@ - - */ -class MixedPropertiesAndAdditionalPropertiesClass implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'MixedPropertiesAndAdditionalPropertiesClass'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'uuid' => 'string', - 'date_time' => '\DateTime', - 'map' => 'array' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'uuid' => 'uuid', - 'date_time' => 'date-time', - 'map' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'uuid' => false, - 'date_time' => false, - 'map' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'uuid' => 'uuid', - 'date_time' => 'dateTime', - 'map' => 'map' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'uuid' => 'setUuid', - 'date_time' => 'setDateTime', - 'map' => 'setMap' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'uuid' => 'getUuid', - 'date_time' => 'getDateTime', - 'map' => 'getMap' - ]; - - /** - * 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->setIfExists('uuid', $data ?? [], null); - $this->setIfExists('date_time', $data ?? [], null); - $this->setIfExists('map', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 uuid - * - * @return string|null - */ - public function getUuid() - { - return $this->container['uuid']; - } - - /** - * Sets uuid - * - * @param string|null $uuid uuid - * - * @return self - */ - public function setUuid($uuid) - { - if (is_null($uuid)) { - throw new \InvalidArgumentException('non-nullable uuid cannot be null'); - } - $this->container['uuid'] = $uuid; - - return $this; - } - - /** - * Gets date_time - * - * @return \DateTime|null - */ - public function getDateTime() - { - return $this->container['date_time']; - } - - /** - * Sets date_time - * - * @param \DateTime|null $date_time date_time - * - * @return self - */ - public function setDateTime($date_time) - { - if (is_null($date_time)) { - throw new \InvalidArgumentException('non-nullable date_time cannot be null'); - } - $this->container['date_time'] = $date_time; - - return $this; - } - - /** - * Gets map - * - * @return array|null - */ - public function getMap() - { - return $this->container['map']; - } - - /** - * Sets map - * - * @param array|null $map map - * - * @return self - */ - public function setMap($map) - { - if (is_null($map)) { - throw new \InvalidArgumentException('non-nullable map cannot be null'); - } - $this->container['map'] = $map; - - 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-nextgen/OpenAPIClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Model200Response.php deleted file mode 100644 index f0a8a4398044..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Model200Response.php +++ /dev/null @@ -1,444 +0,0 @@ - - */ -class Model200Response implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = '200_response'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'name' => 'int', - 'class' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'name' => 'int32', - 'class' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'name' => false, - 'class' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'name' => 'name', - 'class' => 'class' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'name' => 'setName', - 'class' => 'setClass' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'name' => 'getName', - 'class' => 'getClass' - ]; - - /** - * 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->setIfExists('name', $data ?? [], null); - $this->setIfExists('class', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 name - * - * @return int|null - */ - public function getName() - { - return $this->container['name']; - } - - /** - * Sets name - * - * @param int|null $name name - * - * @return self - */ - public function setName($name) - { - if (is_null($name)) { - throw new \InvalidArgumentException('non-nullable name cannot be null'); - } - $this->container['name'] = $name; - - return $this; - } - - /** - * Gets class - * - * @return string|null - */ - public function getClass() - { - return $this->container['class']; - } - - /** - * Sets class - * - * @param string|null $class class - * - * @return self - */ - public function setClass($class) - { - if (is_null($class)) { - throw new \InvalidArgumentException('non-nullable class cannot be null'); - } - $this->container['class'] = $class; - - 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-nextgen/OpenAPIClient-php/lib/Model/ModelInterface.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ModelInterface.php deleted file mode 100644 index 822ef9d3c83f..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ModelInterface.php +++ /dev/null @@ -1,111 +0,0 @@ - - */ -class ModelList implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'List'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - '_123_list' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - '_123_list' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - '_123_list' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - '_123_list' => '123-list' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - '_123_list' => 'set123List' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - '_123_list' => 'get123List' - ]; - - /** - * 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->setIfExists('_123_list', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 _123_list - * - * @return string|null - */ - public function get123List() - { - return $this->container['_123_list']; - } - - /** - * Sets _123_list - * - * @param string|null $_123_list _123_list - * - * @return self - */ - public function set123List($_123_list) - { - if (is_null($_123_list)) { - throw new \InvalidArgumentException('non-nullable _123_list cannot be null'); - } - $this->container['_123_list'] = $_123_list; - - 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-nextgen/OpenAPIClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ModelReturn.php deleted file mode 100644 index 1ec62370f37a..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ModelReturn.php +++ /dev/null @@ -1,410 +0,0 @@ - - */ -class ModelReturn implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Return'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'return' => 'int' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'return' => 'int32' - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'return' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'return' => 'return' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'return' => 'setReturn' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'return' => 'getReturn' - ]; - - /** - * 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->setIfExists('return', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 return - * - * @return int|null - */ - public function getReturn() - { - return $this->container['return']; - } - - /** - * Sets return - * - * @param int|null $return return - * - * @return self - */ - public function setReturn($return) - { - if (is_null($return)) { - throw new \InvalidArgumentException('non-nullable return cannot be null'); - } - $this->container['return'] = $return; - - 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-nextgen/OpenAPIClient-php/lib/Model/Name.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Name.php deleted file mode 100644 index 6718ae206f60..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Name.php +++ /dev/null @@ -1,515 +0,0 @@ - - */ -class Name implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Name'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'name' => 'int', - 'snake_case' => 'int', - 'property' => 'string', - '_123_number' => 'int' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'name' => 'int32', - 'snake_case' => 'int32', - 'property' => null, - '_123_number' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'name' => false, - 'snake_case' => false, - 'property' => false, - '_123_number' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'name' => 'name', - 'snake_case' => 'snake_case', - 'property' => 'property', - '_123_number' => '123Number' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'name' => 'setName', - 'snake_case' => 'setSnakeCase', - 'property' => 'setProperty', - '_123_number' => 'set123Number' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'name' => 'getName', - 'snake_case' => 'getSnakeCase', - 'property' => 'getProperty', - '_123_number' => 'get123Number' - ]; - - /** - * 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->setIfExists('name', $data ?? [], null); - $this->setIfExists('snake_case', $data ?? [], null); - $this->setIfExists('property', $data ?? [], null); - $this->setIfExists('_123_number', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - if ($this->container['name'] === null) { - $invalidProperties[] = "'name' can't be null"; - } - 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 name - * - * @return int - */ - public function getName() - { - return $this->container['name']; - } - - /** - * Sets name - * - * @param int $name name - * - * @return self - */ - public function setName($name) - { - if (is_null($name)) { - throw new \InvalidArgumentException('non-nullable name cannot be null'); - } - $this->container['name'] = $name; - - return $this; - } - - /** - * Gets snake_case - * - * @return int|null - */ - public function getSnakeCase() - { - return $this->container['snake_case']; - } - - /** - * Sets snake_case - * - * @param int|null $snake_case snake_case - * - * @return self - */ - public function setSnakeCase($snake_case) - { - if (is_null($snake_case)) { - throw new \InvalidArgumentException('non-nullable snake_case cannot be null'); - } - $this->container['snake_case'] = $snake_case; - - return $this; - } - - /** - * Gets property - * - * @return string|null - */ - public function getProperty() - { - return $this->container['property']; - } - - /** - * Sets property - * - * @param string|null $property property - * - * @return self - */ - public function setProperty($property) - { - if (is_null($property)) { - throw new \InvalidArgumentException('non-nullable property cannot be null'); - } - $this->container['property'] = $property; - - return $this; - } - - /** - * Gets _123_number - * - * @return int|null - */ - public function get123Number() - { - return $this->container['_123_number']; - } - - /** - * Sets _123_number - * - * @param int|null $_123_number _123_number - * - * @return self - */ - public function set123Number($_123_number) - { - if (is_null($_123_number)) { - throw new \InvalidArgumentException('non-nullable _123_number cannot be null'); - } - $this->container['_123_number'] = $_123_number; - - 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-nextgen/OpenAPIClient-php/lib/Model/NullableClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/NullableClass.php deleted file mode 100644 index cecfc7a333d1..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/NullableClass.php +++ /dev/null @@ -1,853 +0,0 @@ - - */ -class NullableClass implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'NullableClass'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'integer_prop' => 'int', - 'number_prop' => 'float', - 'boolean_prop' => 'bool', - 'string_prop' => 'string', - 'date_prop' => '\DateTime', - 'datetime_prop' => '\DateTime', - 'array_nullable_prop' => 'object[]', - 'array_and_items_nullable_prop' => 'object[]', - 'array_items_nullable' => 'object[]', - 'object_nullable_prop' => 'array', - 'object_and_items_nullable_prop' => 'array', - 'object_items_nullable' => 'array' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'integer_prop' => null, - 'number_prop' => null, - 'boolean_prop' => null, - 'string_prop' => null, - 'date_prop' => 'date', - 'datetime_prop' => 'date-time', - 'array_nullable_prop' => null, - 'array_and_items_nullable_prop' => null, - 'array_items_nullable' => null, - 'object_nullable_prop' => null, - 'object_and_items_nullable_prop' => null, - 'object_items_nullable' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'integer_prop' => true, - 'number_prop' => true, - 'boolean_prop' => true, - 'string_prop' => true, - 'date_prop' => true, - 'datetime_prop' => true, - 'array_nullable_prop' => true, - 'array_and_items_nullable_prop' => true, - 'array_items_nullable' => false, - 'object_nullable_prop' => true, - 'object_and_items_nullable_prop' => true, - 'object_items_nullable' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'integer_prop' => 'integer_prop', - 'number_prop' => 'number_prop', - 'boolean_prop' => 'boolean_prop', - 'string_prop' => 'string_prop', - 'date_prop' => 'date_prop', - 'datetime_prop' => 'datetime_prop', - 'array_nullable_prop' => 'array_nullable_prop', - 'array_and_items_nullable_prop' => 'array_and_items_nullable_prop', - 'array_items_nullable' => 'array_items_nullable', - 'object_nullable_prop' => 'object_nullable_prop', - 'object_and_items_nullable_prop' => 'object_and_items_nullable_prop', - 'object_items_nullable' => 'object_items_nullable' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'integer_prop' => 'setIntegerProp', - 'number_prop' => 'setNumberProp', - 'boolean_prop' => 'setBooleanProp', - 'string_prop' => 'setStringProp', - 'date_prop' => 'setDateProp', - 'datetime_prop' => 'setDatetimeProp', - 'array_nullable_prop' => 'setArrayNullableProp', - 'array_and_items_nullable_prop' => 'setArrayAndItemsNullableProp', - 'array_items_nullable' => 'setArrayItemsNullable', - 'object_nullable_prop' => 'setObjectNullableProp', - 'object_and_items_nullable_prop' => 'setObjectAndItemsNullableProp', - 'object_items_nullable' => 'setObjectItemsNullable' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'integer_prop' => 'getIntegerProp', - 'number_prop' => 'getNumberProp', - 'boolean_prop' => 'getBooleanProp', - 'string_prop' => 'getStringProp', - 'date_prop' => 'getDateProp', - 'datetime_prop' => 'getDatetimeProp', - 'array_nullable_prop' => 'getArrayNullableProp', - 'array_and_items_nullable_prop' => 'getArrayAndItemsNullableProp', - 'array_items_nullable' => 'getArrayItemsNullable', - 'object_nullable_prop' => 'getObjectNullableProp', - 'object_and_items_nullable_prop' => 'getObjectAndItemsNullableProp', - 'object_items_nullable' => 'getObjectItemsNullable' - ]; - - /** - * 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->setIfExists('integer_prop', $data ?? [], null); - $this->setIfExists('number_prop', $data ?? [], null); - $this->setIfExists('boolean_prop', $data ?? [], null); - $this->setIfExists('string_prop', $data ?? [], null); - $this->setIfExists('date_prop', $data ?? [], null); - $this->setIfExists('datetime_prop', $data ?? [], null); - $this->setIfExists('array_nullable_prop', $data ?? [], null); - $this->setIfExists('array_and_items_nullable_prop', $data ?? [], null); - $this->setIfExists('array_items_nullable', $data ?? [], null); - $this->setIfExists('object_nullable_prop', $data ?? [], null); - $this->setIfExists('object_and_items_nullable_prop', $data ?? [], null); - $this->setIfExists('object_items_nullable', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 integer_prop - * - * @return int|null - */ - public function getIntegerProp() - { - return $this->container['integer_prop']; - } - - /** - * Sets integer_prop - * - * @param int|null $integer_prop integer_prop - * - * @return self - */ - public function setIntegerProp($integer_prop) - { - if (is_null($integer_prop)) { - array_push($this->openAPINullablesSetToNull, 'integer_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('integer_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['integer_prop'] = $integer_prop; - - return $this; - } - - /** - * Gets number_prop - * - * @return float|null - */ - public function getNumberProp() - { - return $this->container['number_prop']; - } - - /** - * Sets number_prop - * - * @param float|null $number_prop number_prop - * - * @return self - */ - public function setNumberProp($number_prop) - { - if (is_null($number_prop)) { - array_push($this->openAPINullablesSetToNull, 'number_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('number_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['number_prop'] = $number_prop; - - return $this; - } - - /** - * Gets boolean_prop - * - * @return bool|null - */ - public function getBooleanProp() - { - return $this->container['boolean_prop']; - } - - /** - * Sets boolean_prop - * - * @param bool|null $boolean_prop boolean_prop - * - * @return self - */ - public function setBooleanProp($boolean_prop) - { - if (is_null($boolean_prop)) { - array_push($this->openAPINullablesSetToNull, 'boolean_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('boolean_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['boolean_prop'] = $boolean_prop; - - return $this; - } - - /** - * Gets string_prop - * - * @return string|null - */ - public function getStringProp() - { - return $this->container['string_prop']; - } - - /** - * Sets string_prop - * - * @param string|null $string_prop string_prop - * - * @return self - */ - public function setStringProp($string_prop) - { - if (is_null($string_prop)) { - array_push($this->openAPINullablesSetToNull, 'string_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('string_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['string_prop'] = $string_prop; - - return $this; - } - - /** - * Gets date_prop - * - * @return \DateTime|null - */ - public function getDateProp() - { - return $this->container['date_prop']; - } - - /** - * Sets date_prop - * - * @param \DateTime|null $date_prop date_prop - * - * @return self - */ - public function setDateProp($date_prop) - { - if (is_null($date_prop)) { - array_push($this->openAPINullablesSetToNull, 'date_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('date_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['date_prop'] = $date_prop; - - return $this; - } - - /** - * Gets datetime_prop - * - * @return \DateTime|null - */ - public function getDatetimeProp() - { - return $this->container['datetime_prop']; - } - - /** - * Sets datetime_prop - * - * @param \DateTime|null $datetime_prop datetime_prop - * - * @return self - */ - public function setDatetimeProp($datetime_prop) - { - if (is_null($datetime_prop)) { - array_push($this->openAPINullablesSetToNull, 'datetime_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('datetime_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['datetime_prop'] = $datetime_prop; - - return $this; - } - - /** - * Gets array_nullable_prop - * - * @return object[]|null - */ - public function getArrayNullableProp() - { - return $this->container['array_nullable_prop']; - } - - /** - * Sets array_nullable_prop - * - * @param object[]|null $array_nullable_prop array_nullable_prop - * - * @return self - */ - public function setArrayNullableProp($array_nullable_prop) - { - if (is_null($array_nullable_prop)) { - array_push($this->openAPINullablesSetToNull, 'array_nullable_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('array_nullable_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['array_nullable_prop'] = $array_nullable_prop; - - return $this; - } - - /** - * Gets array_and_items_nullable_prop - * - * @return object[]|null - */ - public function getArrayAndItemsNullableProp() - { - return $this->container['array_and_items_nullable_prop']; - } - - /** - * Sets array_and_items_nullable_prop - * - * @param object[]|null $array_and_items_nullable_prop array_and_items_nullable_prop - * - * @return self - */ - public function setArrayAndItemsNullableProp($array_and_items_nullable_prop) - { - if (is_null($array_and_items_nullable_prop)) { - array_push($this->openAPINullablesSetToNull, 'array_and_items_nullable_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('array_and_items_nullable_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['array_and_items_nullable_prop'] = $array_and_items_nullable_prop; - - return $this; - } - - /** - * Gets array_items_nullable - * - * @return object[]|null - */ - public function getArrayItemsNullable() - { - return $this->container['array_items_nullable']; - } - - /** - * Sets array_items_nullable - * - * @param object[]|null $array_items_nullable array_items_nullable - * - * @return self - */ - public function setArrayItemsNullable($array_items_nullable) - { - if (is_null($array_items_nullable)) { - throw new \InvalidArgumentException('non-nullable array_items_nullable cannot be null'); - } - $this->container['array_items_nullable'] = $array_items_nullable; - - return $this; - } - - /** - * Gets object_nullable_prop - * - * @return array|null - */ - public function getObjectNullableProp() - { - return $this->container['object_nullable_prop']; - } - - /** - * Sets object_nullable_prop - * - * @param array|null $object_nullable_prop object_nullable_prop - * - * @return self - */ - public function setObjectNullableProp($object_nullable_prop) - { - if (is_null($object_nullable_prop)) { - array_push($this->openAPINullablesSetToNull, 'object_nullable_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('object_nullable_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['object_nullable_prop'] = $object_nullable_prop; - - return $this; - } - - /** - * Gets object_and_items_nullable_prop - * - * @return array|null - */ - public function getObjectAndItemsNullableProp() - { - return $this->container['object_and_items_nullable_prop']; - } - - /** - * Sets object_and_items_nullable_prop - * - * @param array|null $object_and_items_nullable_prop object_and_items_nullable_prop - * - * @return self - */ - public function setObjectAndItemsNullableProp($object_and_items_nullable_prop) - { - if (is_null($object_and_items_nullable_prop)) { - array_push($this->openAPINullablesSetToNull, 'object_and_items_nullable_prop'); - } else { - $nullablesSetToNull = $this->getOpenAPINullablesSetToNull(); - $index = array_search('object_and_items_nullable_prop', $nullablesSetToNull); - if ($index !== FALSE) { - unset($nullablesSetToNull[$index]); - $this->setOpenAPINullablesSetToNull($nullablesSetToNull); - } - } - $this->container['object_and_items_nullable_prop'] = $object_and_items_nullable_prop; - - return $this; - } - - /** - * Gets object_items_nullable - * - * @return array|null - */ - public function getObjectItemsNullable() - { - return $this->container['object_items_nullable']; - } - - /** - * Sets object_items_nullable - * - * @param array|null $object_items_nullable object_items_nullable - * - * @return self - */ - public function setObjectItemsNullable($object_items_nullable) - { - if (is_null($object_items_nullable)) { - throw new \InvalidArgumentException('non-nullable object_items_nullable cannot be null'); - } - $this->container['object_items_nullable'] = $object_items_nullable; - - 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-nextgen/OpenAPIClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/NumberOnly.php deleted file mode 100644 index 73a78118a4f9..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/NumberOnly.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class NumberOnly implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'NumberOnly'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'just_number' => 'float' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'just_number' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'just_number' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'just_number' => 'JustNumber' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'just_number' => 'setJustNumber' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'just_number' => 'getJustNumber' - ]; - - /** - * 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->setIfExists('just_number', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 just_number - * - * @return float|null - */ - public function getJustNumber() - { - return $this->container['just_number']; - } - - /** - * Sets just_number - * - * @param float|null $just_number just_number - * - * @return self - */ - public function setJustNumber($just_number) - { - if (is_null($just_number)) { - throw new \InvalidArgumentException('non-nullable just_number cannot be null'); - } - $this->container['just_number'] = $just_number; - - 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-nextgen/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php deleted file mode 100644 index 1bec3db84a33..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php +++ /dev/null @@ -1,517 +0,0 @@ - - */ -class ObjectWithDeprecatedFields implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'ObjectWithDeprecatedFields'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'uuid' => 'string', - 'id' => 'float', - 'deprecated_ref' => '\OpenAPI\Client\Model\DeprecatedObject', - 'bars' => 'string[]' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'uuid' => null, - 'id' => null, - 'deprecated_ref' => null, - 'bars' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'uuid' => false, - 'id' => false, - 'deprecated_ref' => false, - 'bars' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'uuid' => 'uuid', - 'id' => 'id', - 'deprecated_ref' => 'deprecatedRef', - 'bars' => 'bars' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'uuid' => 'setUuid', - 'id' => 'setId', - 'deprecated_ref' => 'setDeprecatedRef', - 'bars' => 'setBars' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'uuid' => 'getUuid', - 'id' => 'getId', - 'deprecated_ref' => 'getDeprecatedRef', - 'bars' => 'getBars' - ]; - - /** - * 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->setIfExists('uuid', $data ?? [], null); - $this->setIfExists('id', $data ?? [], null); - $this->setIfExists('deprecated_ref', $data ?? [], null); - $this->setIfExists('bars', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 uuid - * - * @return string|null - */ - public function getUuid() - { - return $this->container['uuid']; - } - - /** - * Sets uuid - * - * @param string|null $uuid uuid - * - * @return self - */ - public function setUuid($uuid) - { - if (is_null($uuid)) { - throw new \InvalidArgumentException('non-nullable uuid cannot be null'); - } - $this->container['uuid'] = $uuid; - - return $this; - } - - /** - * Gets id - * - * @return float|null - * @deprecated - */ - public function getId() - { - return $this->container['id']; - } - - /** - * Sets id - * - * @param float|null $id id - * - * @return self - * @deprecated - */ - public function setId($id) - { - if (is_null($id)) { - throw new \InvalidArgumentException('non-nullable id cannot be null'); - } - $this->container['id'] = $id; - - return $this; - } - - /** - * Gets deprecated_ref - * - * @return \OpenAPI\Client\Model\DeprecatedObject|null - * @deprecated - */ - public function getDeprecatedRef() - { - return $this->container['deprecated_ref']; - } - - /** - * Sets deprecated_ref - * - * @param \OpenAPI\Client\Model\DeprecatedObject|null $deprecated_ref deprecated_ref - * - * @return self - * @deprecated - */ - public function setDeprecatedRef($deprecated_ref) - { - if (is_null($deprecated_ref)) { - throw new \InvalidArgumentException('non-nullable deprecated_ref cannot be null'); - } - $this->container['deprecated_ref'] = $deprecated_ref; - - return $this; - } - - /** - * Gets bars - * - * @return string[]|null - * @deprecated - */ - public function getBars() - { - return $this->container['bars']; - } - - /** - * Sets bars - * - * @param string[]|null $bars bars - * - * @return self - * @deprecated - */ - public function setBars($bars) - { - if (is_null($bars)) { - throw new \InvalidArgumentException('non-nullable bars cannot be null'); - } - $this->container['bars'] = $bars; - - 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-nextgen/OpenAPIClient-php/lib/Model/Order.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Order.php deleted file mode 100644 index ebc4eae027e9..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Order.php +++ /dev/null @@ -1,615 +0,0 @@ - - */ -class Order implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Order'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'id' => 'int', - 'pet_id' => 'int', - 'quantity' => 'int', - 'ship_date' => '\DateTime', - 'status' => 'string', - 'complete' => 'bool' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'id' => 'int64', - 'pet_id' => 'int64', - 'quantity' => 'int32', - 'ship_date' => 'date-time', - 'status' => null, - 'complete' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'id' => false, - 'pet_id' => false, - 'quantity' => false, - 'ship_date' => false, - 'status' => false, - 'complete' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'id' => 'id', - 'pet_id' => 'petId', - 'quantity' => 'quantity', - 'ship_date' => 'shipDate', - 'status' => 'status', - 'complete' => 'complete' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'id' => 'setId', - 'pet_id' => 'setPetId', - 'quantity' => 'setQuantity', - 'ship_date' => 'setShipDate', - 'status' => 'setStatus', - 'complete' => 'setComplete' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'id' => 'getId', - 'pet_id' => 'getPetId', - 'quantity' => 'getQuantity', - 'ship_date' => 'getShipDate', - 'status' => 'getStatus', - 'complete' => 'getComplete' - ]; - - /** - * 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; - } - - public const STATUS_PLACED = 'placed'; - public const STATUS_APPROVED = 'approved'; - public const STATUS_DELIVERED = 'delivered'; - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getStatusAllowableValues() - { - return [ - self::STATUS_PLACED, - self::STATUS_APPROVED, - self::STATUS_DELIVERED, - ]; - } - - /** - * 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->setIfExists('id', $data ?? [], null); - $this->setIfExists('pet_id', $data ?? [], null); - $this->setIfExists('quantity', $data ?? [], null); - $this->setIfExists('ship_date', $data ?? [], null); - $this->setIfExists('status', $data ?? [], null); - $this->setIfExists('complete', $data ?? [], false); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { - $invalidProperties[] = sprintf( - "invalid value '%s' for 'status', must be one of '%s'", - $this->container['status'], - implode("', '", $allowedValues) - ); - } - - 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 id - * - * @return int|null - */ - public function getId() - { - return $this->container['id']; - } - - /** - * Sets id - * - * @param int|null $id id - * - * @return self - */ - public function setId($id) - { - if (is_null($id)) { - throw new \InvalidArgumentException('non-nullable id cannot be null'); - } - $this->container['id'] = $id; - - return $this; - } - - /** - * Gets pet_id - * - * @return int|null - */ - public function getPetId() - { - return $this->container['pet_id']; - } - - /** - * Sets pet_id - * - * @param int|null $pet_id pet_id - * - * @return self - */ - public function setPetId($pet_id) - { - if (is_null($pet_id)) { - throw new \InvalidArgumentException('non-nullable pet_id cannot be null'); - } - $this->container['pet_id'] = $pet_id; - - return $this; - } - - /** - * Gets quantity - * - * @return int|null - */ - public function getQuantity() - { - return $this->container['quantity']; - } - - /** - * Sets quantity - * - * @param int|null $quantity quantity - * - * @return self - */ - public function setQuantity($quantity) - { - if (is_null($quantity)) { - throw new \InvalidArgumentException('non-nullable quantity cannot be null'); - } - $this->container['quantity'] = $quantity; - - return $this; - } - - /** - * Gets ship_date - * - * @return \DateTime|null - */ - public function getShipDate() - { - return $this->container['ship_date']; - } - - /** - * Sets ship_date - * - * @param \DateTime|null $ship_date ship_date - * - * @return self - */ - public function setShipDate($ship_date) - { - if (is_null($ship_date)) { - throw new \InvalidArgumentException('non-nullable ship_date cannot be null'); - } - $this->container['ship_date'] = $ship_date; - - return $this; - } - - /** - * Gets status - * - * @return string|null - */ - public function getStatus() - { - return $this->container['status']; - } - - /** - * Sets status - * - * @param string|null $status Order Status - * - * @return self - */ - public function setStatus($status) - { - if (is_null($status)) { - throw new \InvalidArgumentException('non-nullable status cannot be null'); - } - $allowedValues = $this->getStatusAllowableValues(); - if (!in_array($status, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value '%s' for 'status', must be one of '%s'", - $status, - implode("', '", $allowedValues) - ) - ); - } - $this->container['status'] = $status; - - return $this; - } - - /** - * Gets complete - * - * @return bool|null - */ - public function getComplete() - { - return $this->container['complete']; - } - - /** - * Sets complete - * - * @param bool|null $complete complete - * - * @return self - */ - public function setComplete($complete) - { - if (is_null($complete)) { - throw new \InvalidArgumentException('non-nullable complete cannot be null'); - } - $this->container['complete'] = $complete; - - 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-nextgen/OpenAPIClient-php/lib/Model/OuterComposite.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/OuterComposite.php deleted file mode 100644 index 1ad98982b70a..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/OuterComposite.php +++ /dev/null @@ -1,477 +0,0 @@ - - */ -class OuterComposite implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'OuterComposite'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'my_number' => 'float', - 'my_string' => 'string', - 'my_boolean' => 'bool' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'my_number' => null, - 'my_string' => null, - 'my_boolean' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'my_number' => false, - 'my_string' => false, - 'my_boolean' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'my_number' => 'my_number', - 'my_string' => 'my_string', - 'my_boolean' => 'my_boolean' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'my_number' => 'setMyNumber', - 'my_string' => 'setMyString', - 'my_boolean' => 'setMyBoolean' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'my_number' => 'getMyNumber', - 'my_string' => 'getMyString', - 'my_boolean' => 'getMyBoolean' - ]; - - /** - * 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->setIfExists('my_number', $data ?? [], null); - $this->setIfExists('my_string', $data ?? [], null); - $this->setIfExists('my_boolean', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 my_number - * - * @return float|null - */ - public function getMyNumber() - { - return $this->container['my_number']; - } - - /** - * Sets my_number - * - * @param float|null $my_number my_number - * - * @return self - */ - public function setMyNumber($my_number) - { - if (is_null($my_number)) { - throw new \InvalidArgumentException('non-nullable my_number cannot be null'); - } - $this->container['my_number'] = $my_number; - - return $this; - } - - /** - * Gets my_string - * - * @return string|null - */ - public function getMyString() - { - return $this->container['my_string']; - } - - /** - * Sets my_string - * - * @param string|null $my_string my_string - * - * @return self - */ - public function setMyString($my_string) - { - if (is_null($my_string)) { - throw new \InvalidArgumentException('non-nullable my_string cannot be null'); - } - $this->container['my_string'] = $my_string; - - return $this; - } - - /** - * Gets my_boolean - * - * @return bool|null - */ - public function getMyBoolean() - { - return $this->container['my_boolean']; - } - - /** - * Sets my_boolean - * - * @param bool|null $my_boolean my_boolean - * - * @return self - */ - public function setMyBoolean($my_boolean) - { - if (is_null($my_boolean)) { - throw new \InvalidArgumentException('non-nullable my_boolean cannot be null'); - } - $this->container['my_boolean'] = $my_boolean; - - 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-nextgen/OpenAPIClient-php/lib/Model/OuterEnum.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/OuterEnum.php deleted file mode 100644 index f4d09cf1f207..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/OuterEnum.php +++ /dev/null @@ -1,65 +0,0 @@ - - */ -class OuterObjectWithEnumProperty implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'OuterObjectWithEnumProperty'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'value' => '\OpenAPI\Client\Model\OuterEnumInteger' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'value' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'value' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'value' => 'value' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'value' => 'setValue' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'value' => 'getValue' - ]; - - /** - * 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->setIfExists('value', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - if ($this->container['value'] === null) { - $invalidProperties[] = "'value' can't be null"; - } - 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 value - * - * @return \OpenAPI\Client\Model\OuterEnumInteger - */ - public function getValue() - { - return $this->container['value']; - } - - /** - * Sets value - * - * @param \OpenAPI\Client\Model\OuterEnumInteger $value value - * - * @return self - */ - public function setValue($value) - { - if (is_null($value)) { - throw new \InvalidArgumentException('non-nullable value cannot be null'); - } - $this->container['value'] = $value; - - 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-nextgen/OpenAPIClient-php/lib/Model/Pet.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Pet.php deleted file mode 100644 index 6795d19e6aab..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Pet.php +++ /dev/null @@ -1,623 +0,0 @@ - - */ -class Pet implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Pet'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'id' => 'int', - 'category' => '\OpenAPI\Client\Model\Category', - 'name' => 'string', - 'photo_urls' => 'string[]', - 'tags' => '\OpenAPI\Client\Model\Tag[]', - 'status' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'id' => 'int64', - 'category' => null, - 'name' => null, - 'photo_urls' => null, - 'tags' => null, - 'status' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'id' => false, - 'category' => false, - 'name' => false, - 'photo_urls' => false, - 'tags' => false, - 'status' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'id' => 'id', - 'category' => 'category', - 'name' => 'name', - 'photo_urls' => 'photoUrls', - 'tags' => 'tags', - 'status' => 'status' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'id' => 'setId', - 'category' => 'setCategory', - 'name' => 'setName', - 'photo_urls' => 'setPhotoUrls', - 'tags' => 'setTags', - 'status' => 'setStatus' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'id' => 'getId', - 'category' => 'getCategory', - 'name' => 'getName', - 'photo_urls' => 'getPhotoUrls', - 'tags' => 'getTags', - 'status' => 'getStatus' - ]; - - /** - * 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; - } - - public const STATUS_AVAILABLE = 'available'; - public const STATUS_PENDING = 'pending'; - public const STATUS_SOLD = 'sold'; - - /** - * Gets allowable values of the enum - * - * @return string[] - */ - public function getStatusAllowableValues() - { - return [ - self::STATUS_AVAILABLE, - self::STATUS_PENDING, - self::STATUS_SOLD, - ]; - } - - /** - * 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->setIfExists('id', $data ?? [], null); - $this->setIfExists('category', $data ?? [], null); - $this->setIfExists('name', $data ?? [], null); - $this->setIfExists('photo_urls', $data ?? [], null); - $this->setIfExists('tags', $data ?? [], null); - $this->setIfExists('status', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * Show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalidProperties = []; - - if ($this->container['name'] === null) { - $invalidProperties[] = "'name' can't be null"; - } - if ($this->container['photo_urls'] === null) { - $invalidProperties[] = "'photo_urls' can't be null"; - } - $allowedValues = $this->getStatusAllowableValues(); - if (!is_null($this->container['status']) && !in_array($this->container['status'], $allowedValues, true)) { - $invalidProperties[] = sprintf( - "invalid value '%s' for 'status', must be one of '%s'", - $this->container['status'], - implode("', '", $allowedValues) - ); - } - - 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 id - * - * @return int|null - */ - public function getId() - { - return $this->container['id']; - } - - /** - * Sets id - * - * @param int|null $id id - * - * @return self - */ - public function setId($id) - { - if (is_null($id)) { - throw new \InvalidArgumentException('non-nullable id cannot be null'); - } - $this->container['id'] = $id; - - return $this; - } - - /** - * Gets category - * - * @return \OpenAPI\Client\Model\Category|null - */ - public function getCategory() - { - return $this->container['category']; - } - - /** - * Sets category - * - * @param \OpenAPI\Client\Model\Category|null $category category - * - * @return self - */ - public function setCategory($category) - { - if (is_null($category)) { - throw new \InvalidArgumentException('non-nullable category cannot be null'); - } - $this->container['category'] = $category; - - return $this; - } - - /** - * Gets name - * - * @return string - */ - public function getName() - { - return $this->container['name']; - } - - /** - * Sets name - * - * @param string $name name - * - * @return self - */ - public function setName($name) - { - if (is_null($name)) { - throw new \InvalidArgumentException('non-nullable name cannot be null'); - } - $this->container['name'] = $name; - - return $this; - } - - /** - * Gets photo_urls - * - * @return string[] - */ - public function getPhotoUrls() - { - return $this->container['photo_urls']; - } - - /** - * Sets photo_urls - * - * @param string[] $photo_urls photo_urls - * - * @return self - */ - public function setPhotoUrls($photo_urls) - { - if (is_null($photo_urls)) { - throw new \InvalidArgumentException('non-nullable photo_urls cannot be null'); - } - - - $this->container['photo_urls'] = $photo_urls; - - return $this; - } - - /** - * Gets tags - * - * @return \OpenAPI\Client\Model\Tag[]|null - */ - public function getTags() - { - return $this->container['tags']; - } - - /** - * Sets tags - * - * @param \OpenAPI\Client\Model\Tag[]|null $tags tags - * - * @return self - */ - public function setTags($tags) - { - if (is_null($tags)) { - throw new \InvalidArgumentException('non-nullable tags cannot be null'); - } - $this->container['tags'] = $tags; - - return $this; - } - - /** - * Gets status - * - * @return string|null - */ - public function getStatus() - { - return $this->container['status']; - } - - /** - * Sets status - * - * @param string|null $status pet status in the store - * - * @return self - */ - public function setStatus($status) - { - if (is_null($status)) { - throw new \InvalidArgumentException('non-nullable status cannot be null'); - } - $allowedValues = $this->getStatusAllowableValues(); - if (!in_array($status, $allowedValues, true)) { - throw new \InvalidArgumentException( - sprintf( - "Invalid value '%s' for 'status', must be one of '%s'", - $status, - implode("', '", $allowedValues) - ) - ); - } - $this->container['status'] = $status; - - 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-nextgen/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php deleted file mode 100644 index 88a7bbaed1a3..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php +++ /dev/null @@ -1,443 +0,0 @@ - - */ -class ReadOnlyFirst implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'ReadOnlyFirst'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'bar' => 'string', - 'baz' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'bar' => null, - 'baz' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'bar' => false, - 'baz' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'bar' => 'bar', - 'baz' => 'baz' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'bar' => 'setBar', - 'baz' => 'setBaz' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'bar' => 'getBar', - 'baz' => 'getBaz' - ]; - - /** - * 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->setIfExists('bar', $data ?? [], null); - $this->setIfExists('baz', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 bar - * - * @return string|null - */ - public function getBar() - { - return $this->container['bar']; - } - - /** - * Sets bar - * - * @param string|null $bar bar - * - * @return self - */ - public function setBar($bar) - { - if (is_null($bar)) { - throw new \InvalidArgumentException('non-nullable bar cannot be null'); - } - $this->container['bar'] = $bar; - - return $this; - } - - /** - * Gets baz - * - * @return string|null - */ - public function getBaz() - { - return $this->container['baz']; - } - - /** - * Sets baz - * - * @param string|null $baz baz - * - * @return self - */ - public function setBaz($baz) - { - if (is_null($baz)) { - throw new \InvalidArgumentException('non-nullable baz cannot be null'); - } - $this->container['baz'] = $baz; - - 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-nextgen/OpenAPIClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/SpecialModelName.php deleted file mode 100644 index dcf7599371e6..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/SpecialModelName.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class SpecialModelName implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = '_special_model.name_'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'special_property_name' => 'int' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'special_property_name' => 'int64' - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'special_property_name' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'special_property_name' => '$special[property.name]' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'special_property_name' => 'setSpecialPropertyName' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'special_property_name' => 'getSpecialPropertyName' - ]; - - /** - * 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->setIfExists('special_property_name', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 special_property_name - * - * @return int|null - */ - public function getSpecialPropertyName() - { - return $this->container['special_property_name']; - } - - /** - * Sets special_property_name - * - * @param int|null $special_property_name special_property_name - * - * @return self - */ - public function setSpecialPropertyName($special_property_name) - { - if (is_null($special_property_name)) { - throw new \InvalidArgumentException('non-nullable special_property_name cannot be null'); - } - $this->container['special_property_name'] = $special_property_name; - - 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-nextgen/OpenAPIClient-php/lib/Model/Tag.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Tag.php deleted file mode 100644 index 03742ae42152..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/Tag.php +++ /dev/null @@ -1,443 +0,0 @@ - - */ -class Tag implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Tag'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'id' => 'int', - 'name' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'id' => 'int64', - 'name' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'id' => false, - 'name' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'id' => 'id', - 'name' => 'name' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'id' => 'setId', - 'name' => 'setName' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'id' => 'getId', - 'name' => 'getName' - ]; - - /** - * 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->setIfExists('id', $data ?? [], null); - $this->setIfExists('name', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 id - * - * @return int|null - */ - public function getId() - { - return $this->container['id']; - } - - /** - * Sets id - * - * @param int|null $id id - * - * @return self - */ - public function setId($id) - { - if (is_null($id)) { - throw new \InvalidArgumentException('non-nullable id cannot be null'); - } - $this->container['id'] = $id; - - return $this; - } - - /** - * Gets name - * - * @return string|null - */ - public function getName() - { - return $this->container['name']; - } - - /** - * Sets name - * - * @param string|null $name name - * - * @return self - */ - public function setName($name) - { - if (is_null($name)) { - throw new \InvalidArgumentException('non-nullable name cannot be null'); - } - $this->container['name'] = $name; - - 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-nextgen/OpenAPIClient-php/lib/Model/User.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/User.php deleted file mode 100644 index d745bfc65ff1..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/User.php +++ /dev/null @@ -1,647 +0,0 @@ - - */ -class User implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'User'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'id' => 'int', - 'username' => 'string', - 'first_name' => 'string', - 'last_name' => 'string', - 'email' => 'string', - 'password' => 'string', - 'phone' => 'string', - 'user_status' => 'int' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'id' => 'int64', - 'username' => null, - 'first_name' => null, - 'last_name' => null, - 'email' => null, - 'password' => null, - 'phone' => null, - 'user_status' => 'int32' - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'id' => false, - 'username' => false, - 'first_name' => false, - 'last_name' => false, - 'email' => false, - 'password' => false, - 'phone' => false, - 'user_status' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'id' => 'id', - 'username' => 'username', - 'first_name' => 'firstName', - 'last_name' => 'lastName', - 'email' => 'email', - 'password' => 'password', - 'phone' => 'phone', - 'user_status' => 'userStatus' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'id' => 'setId', - 'username' => 'setUsername', - 'first_name' => 'setFirstName', - 'last_name' => 'setLastName', - 'email' => 'setEmail', - 'password' => 'setPassword', - 'phone' => 'setPhone', - 'user_status' => 'setUserStatus' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'id' => 'getId', - 'username' => 'getUsername', - 'first_name' => 'getFirstName', - 'last_name' => 'getLastName', - 'email' => 'getEmail', - 'password' => 'getPassword', - 'phone' => 'getPhone', - 'user_status' => 'getUserStatus' - ]; - - /** - * 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->setIfExists('id', $data ?? [], null); - $this->setIfExists('username', $data ?? [], null); - $this->setIfExists('first_name', $data ?? [], null); - $this->setIfExists('last_name', $data ?? [], null); - $this->setIfExists('email', $data ?? [], null); - $this->setIfExists('password', $data ?? [], null); - $this->setIfExists('phone', $data ?? [], null); - $this->setIfExists('user_status', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 id - * - * @return int|null - */ - public function getId() - { - return $this->container['id']; - } - - /** - * Sets id - * - * @param int|null $id id - * - * @return self - */ - public function setId($id) - { - if (is_null($id)) { - throw new \InvalidArgumentException('non-nullable id cannot be null'); - } - $this->container['id'] = $id; - - return $this; - } - - /** - * Gets username - * - * @return string|null - */ - public function getUsername() - { - return $this->container['username']; - } - - /** - * Sets username - * - * @param string|null $username username - * - * @return self - */ - public function setUsername($username) - { - if (is_null($username)) { - throw new \InvalidArgumentException('non-nullable username cannot be null'); - } - $this->container['username'] = $username; - - return $this; - } - - /** - * Gets first_name - * - * @return string|null - */ - public function getFirstName() - { - return $this->container['first_name']; - } - - /** - * Sets first_name - * - * @param string|null $first_name first_name - * - * @return self - */ - public function setFirstName($first_name) - { - if (is_null($first_name)) { - throw new \InvalidArgumentException('non-nullable first_name cannot be null'); - } - $this->container['first_name'] = $first_name; - - return $this; - } - - /** - * Gets last_name - * - * @return string|null - */ - public function getLastName() - { - return $this->container['last_name']; - } - - /** - * Sets last_name - * - * @param string|null $last_name last_name - * - * @return self - */ - public function setLastName($last_name) - { - if (is_null($last_name)) { - throw new \InvalidArgumentException('non-nullable last_name cannot be null'); - } - $this->container['last_name'] = $last_name; - - return $this; - } - - /** - * Gets email - * - * @return string|null - */ - public function getEmail() - { - return $this->container['email']; - } - - /** - * Sets email - * - * @param string|null $email email - * - * @return self - */ - public function setEmail($email) - { - if (is_null($email)) { - throw new \InvalidArgumentException('non-nullable email cannot be null'); - } - $this->container['email'] = $email; - - return $this; - } - - /** - * Gets password - * - * @return string|null - */ - public function getPassword() - { - return $this->container['password']; - } - - /** - * Sets password - * - * @param string|null $password password - * - * @return self - */ - public function setPassword($password) - { - if (is_null($password)) { - throw new \InvalidArgumentException('non-nullable password cannot be null'); - } - $this->container['password'] = $password; - - return $this; - } - - /** - * Gets phone - * - * @return string|null - */ - public function getPhone() - { - return $this->container['phone']; - } - - /** - * Sets phone - * - * @param string|null $phone phone - * - * @return self - */ - public function setPhone($phone) - { - if (is_null($phone)) { - throw new \InvalidArgumentException('non-nullable phone cannot be null'); - } - $this->container['phone'] = $phone; - - return $this; - } - - /** - * Gets user_status - * - * @return int|null - */ - public function getUserStatus() - { - return $this->container['user_status']; - } - - /** - * Sets user_status - * - * @param int|null $user_status User Status - * - * @return self - */ - public function setUserStatus($user_status) - { - if (is_null($user_status)) { - throw new \InvalidArgumentException('non-nullable user_status cannot be null'); - } - $this->container['user_status'] = $user_status; - - 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-nextgen/OpenAPIClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/ObjectSerializer.php deleted file mode 100644 index 510540985d33..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/ObjectSerializer.php +++ /dev/null @@ -1,616 +0,0 @@ -format('Y-m-d') : $data->format(self::$dateTimeFormat); - } - - if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = self::sanitizeForSerialization($value); - } - return $data; - } - - if (is_object($data)) { - $values = []; - if ($data instanceof ModelInterface) { - $formats = $data::openAPIFormats(); - foreach ($data::openAPITypes() as $property => $openAPIType) { - $getter = $data::getters()[$property]; - $value = $data->$getter(); - if ($value !== null && !in_array($openAPIType, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { - $callable = [$openAPIType, 'getAllowableEnumValues']; - if (is_callable($callable)) { - /** array $callable */ - $allowedEnumTypes = $callable(); - if (!in_array($value, $allowedEnumTypes, true)) { - $imploded = implode("', '", $allowedEnumTypes); - throw new \InvalidArgumentException("Invalid value for enum '$openAPIType', must be one of: '$imploded'"); - } - } - } - if (($data::isNullable($property) && $data->isNullableSetToNull($property)) || $value !== null) { - $values[$data::attributeMap()[$property]] = self::sanitizeForSerialization($value, $openAPIType, $formats[$property]); - } - } - } else { - foreach($data as $property => $value) { - $values[$property] = self::sanitizeForSerialization($value); - } - } - return (object)$values; - } else { - return (string)$data; - } - } - - /** - * Sanitize filename by removing path. - * e.g. ../../sun.gif becomes sun.gif - * - * @param string $filename filename to be sanitized - * - * @return string the sanitized filename - */ - public static function sanitizeFilename($filename) - { - if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { - return $match[1]; - } else { - return $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. - * - * @param string $value a string which will be part of the path - * - * @return string the serialized object - */ - public static function toPathValue($value) - { - return rawurlencode(self::toString($value)); - } - - /** - * Checks if a value is empty, based on its OpenAPI type. - * - * @param mixed $value - * @param string $openApiType - * - * @return bool true if $value is empty - */ - private static function isEmptyValue($value, string $openApiType): bool - { - # If empty() returns false, it is not empty regardless of its type. - if (!empty($value)) { - return false; - } - - # Null is always empty, as we cannot send a real "null" value in a query parameter. - if ($value === null) { - return true; - } - - switch ($openApiType) { - # For numeric values, false and '' are considered empty. - # This comparison is safe for floating point values, since the previous call to empty() will - # filter out values that don't match 0. - case 'int': - case 'integer': - return $value !== 0; - - case 'number': - case 'float': - return $value !== 0 && $value !== 0.0; - - # For boolean values, '' is considered empty - case 'bool': - case 'boolean': - return !in_array($value, [false, 0], true); - - # For all the other types, any value at this point can be considered empty. - default: - return true; - } - } - - /** - * Take query parameter properties and turn it into an array suitable for - * native http_build_query or GuzzleHttp\Psr7\Query::build. - * - * @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 array - */ - public static function toQueryValue( - $value, - string $paramName, - string $openApiType = 'string', - string $style = 'form', - bool $explode = true, - bool $required = true - ): array { - - # Check if we should omit this parameter from the query. This should only happen when: - # - Parameter is NOT required; AND - # - its value is set to a value that is equivalent to "empty", depending on its OpenAPI type. For - # example, 0 as "int" or "boolean" is NOT an empty value. - if (self::isEmptyValue($value, $openApiType)) { - if ($required) { - return ["{$paramName}" => '']; - } else { - return []; - } - } - - # Handle DateTime objects in query - if($openApiType === "\\DateTime" && $value instanceof \DateTime) { - return ["{$paramName}" => $value->format(self::$dateTimeFormat)]; - } - - $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 (Configuration::BOOLEAN_FORMAT_STRING == Configuration::getDefaultConfiguration()->getBooleanFormatForQueryString()) { - return $value ? 'true' : 'false'; - } - - return (int) $value; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the header. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * - * @param string $value a string which will be part of the header - * - * @return string the header string - */ - public static function toHeaderValue($value) - { - $callable = [$value, 'toHeaderValue']; - if (is_callable($callable)) { - return $callable(); - } - - return self::toString($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the http body (form parameter). If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * - * @param string|\SplFileObject $value the value of the form parameter - * - * @return string the form string - */ - public static function toFormValue($value) - { - if ($value instanceof \SplFileObject) { - return $value->getRealPath(); - } else { - return self::toString($value); - } - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the parameter. If it's a string, pass through unchanged - * If it's a datetime object, format it in ISO8601 - * If it's a boolean, convert it to "true" or "false". - * - * @param string|bool|\DateTime $value the value of the parameter - * - * @return string the header string - */ - public static function toString($value) - { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(self::$dateTimeFormat); - } elseif (is_bool($value)) { - return $value ? 'true' : 'false'; - } else { - return (string) $value; - } - } - - /** - * Serialize an array to a string. - * - * @param array $collection collection to serialize to a string - * @param string $style the format use for serialization (csv, - * ssv, tsv, pipes, multi) - * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array - * - * @return string - */ - public static function serializeCollection(array $collection, $style, $allowCollectionFormatMulti = false) - { - if ($allowCollectionFormatMulti && ('multi' === $style)) { - // http_build_query() almost does the job for us. We just - // need to fix the result of multidimensional arrays. - return preg_replace('/%5B[0-9]+%5D=/', '=', http_build_query($collection, '', '&')); - } - switch ($style) { - case 'pipeDelimited': - case 'pipes': - return implode('|', $collection); - - case 'tsv': - return implode("\t", $collection); - - case 'spaceDelimited': - case 'ssv': - return implode(' ', $collection); - - case 'simple': - case 'csv': - // Deliberate fall through. CSV is default format. - default: - return implode(',', $collection); - } - } - - /** - * Deserialize a JSON string into an object - * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string - * @param string[] $httpHeaders HTTP headers - * - * @return object|array|null a single or an array of $class instances - */ - public static function deserialize($data, $class, $httpHeaders = null) - { - if (null === $data) { - return null; - } - - if (strcasecmp(substr($class, -2), '[]') === 0) { - $data = is_string($data) ? json_decode($data) : $data; - - if (!is_array($data)) { - throw new \InvalidArgumentException("Invalid array '$class'"); - } - - $subClass = substr($class, 0, -2); - $values = []; - foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass, null); - } - return $values; - } - - if (preg_match('/^(array<|map\[)/', $class)) { // for associative array e.g. array - $data = is_string($data) ? json_decode($data) : $data; - settype($data, 'array'); - $inner = substr($class, 4, -1); - $deserialized = []; - if (strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass, null); - } - } - return $deserialized; - } - - if ($class === 'object') { - settype($data, 'array'); - return $data; - } elseif ($class === 'mixed') { - settype($data, gettype($data)); - return $data; - } - - if ($class === '\DateTime') { - // Some APIs return an invalid, empty string as a - // date-time property. DateTime::__construct() will return - // the current time for empty input which is probably not - // what is meant. The invalid empty string is probably to - // be interpreted as a missing field/value. Let's handle - // this graceful. - if (!empty($data)) { - try { - return new \DateTime($data); - } catch (\Exception $exception) { - // Some APIs return a date-time with too high nanosecond - // precision for php's DateTime to handle. - // With provided regexp 6 digits of microseconds saved - return new \DateTime(self::sanitizeTimestamp($data)); - } - } else { - return null; - } - } - - if ($class === '\SplFileObject') { - $data = Utils::streamFor($data); - - /** @var \Psr\Http\Message\StreamInterface $data */ - - // determine file name - 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(), ''); - } - - $file = fopen($filename, 'w'); - while ($chunk = $data->read(200)) { - fwrite($file, $chunk); - } - fclose($file); - - return new \SplFileObject($filename, 'r'); - } - - /** @psalm-suppress ParadoxicalCondition */ - if (in_array($class, ['\DateTime', '\SplFileObject', 'array', 'bool', 'boolean', 'byte', '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'"); - } - return $data; - } else { - $data = is_string($data) ? json_decode($data) : $data; - - if (is_array($data)) { - $data = (object)$data; - } - - // If a discriminator is defined and points to a valid subclass, use it. - $discriminator = $class::DISCRIMINATOR; - if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { - $subclass = '\OpenAPI\Client\Model\\' . $data->{$discriminator}; - if (is_subclass_of($subclass, $class)) { - $class = $subclass; - } - } - - /** @var ModelInterface $instance */ - $instance = new $class(); - foreach ($instance::openAPITypes() as $property => $type) { - $propertySetter = $instance::setters()[$property]; - - if (!isset($propertySetter)) { - continue; - } - - if (!isset($data->{$instance::attributeMap()[$property]})) { - if ($instance::isNullable($property)) { - $instance->$propertySetter(null); - } - - continue; - } - - if (isset($data->{$instance::attributeMap()[$property]})) { - $propertyValue = $data->{$instance::attributeMap()[$property]}; - $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); - } - } - return $instance; - } - } - - /** - * Build a query string from an array of key value pairs. - * - * This function can use the return value of `parse()` to build a query - * string. This function does not modify the provided keys when an array is - * encountered (like `http_build_query()` would). - * - * The function is copied from https://github.com/guzzle/psr7/blob/a243f80a1ca7fe8ceed4deee17f12c1930efe662/src/Query.php#L59-L112 - * with a modification which is described in https://github.com/guzzle/psr7/pull/603 - * - * @param array $params Query string parameters. - * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 - * to encode using RFC3986, or PHP_QUERY_RFC1738 - * to encode using RFC1738. - * @param bool $treatBooleansAsInts When `true` values are cast to int (e.g. ['foo' => false] gives `foo=0`). - * When `false` values are cast to strings (e.g. ['foo' => false] gives `foo=false`). - */ - public static function buildQuery(array $params, $encoding = PHP_QUERY_RFC3986, bool $treatBooleansAsInts = true): string - { - if (!$params) { - return ''; - } - - if ($encoding === false) { - $encoder = function (string $str): string { - return $str; - }; - } elseif ($encoding === PHP_QUERY_RFC3986) { - $encoder = 'rawurlencode'; - } elseif ($encoding === PHP_QUERY_RFC1738) { - $encoder = 'urlencode'; - } else { - throw new \InvalidArgumentException('Invalid type'); - } - - $castBool = $treatBooleansAsInts - ? function ($v) { return (int) $v; } - : function ($v) { return $v ? 'true' : 'false'; }; - - $qs = ''; - foreach ($params as $k => $v) { - $k = $encoder((string) $k); - if (!is_array($v)) { - $qs .= $k; - $v = is_bool($v) ? $castBool($v) : $v; - if ($v !== null) { - $qs .= '='.$encoder((string) $v); - } - $qs .= '&'; - } else { - foreach ($v as $vv) { - $qs .= $k; - $vv = is_bool($vv) ? $castBool($vv) : $vv; - if ($vv !== null) { - $qs .= '='.$encoder((string) $vv); - } - $qs .= '&'; - } - } - } - - return $qs ? (string) substr($qs, 0, -1) : ''; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/phplint.dist.yml b/samples/client/petstore/php-nextgen/OpenAPIClient-php/phplint.dist.yml deleted file mode 100644 index 3a1d5b715e9f..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/phplint.dist.yml +++ /dev/null @@ -1,13 +0,0 @@ -path: - - src/ - - tests/ -jobs: 10 -extensions: - - php -exclude: - - vendor -warning: true -memory-limit: -1 -no-cache: false -log-json: false -log-junit: false diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/pom.xml b/samples/client/petstore/php-nextgen/OpenAPIClient-php/pom.xml deleted file mode 100644 index 16ead2bea4df..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - 4.0.0 - org.openapitools - PhpPetstoreOAS3Tests - pom - 1.0-SNAPSHOT - PHP OpenAPI OAS3 Client - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - bundle-install - pre-integration-test - - exec - - - composer - - install - - - - - check-php-syntax - integration-test - - exec - - - vendor/bin/phplint - - --configuration=phplint.dist.yml - - - - - bundle-test - integration-test - - exec - - - vendor/bin/phpunit - - test - - - - - - - - diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/CatAllOf.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/CatAllOf.php deleted file mode 100644 index 5703fe3cb0da..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/CatAllOf.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class CatAllOf implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Cat_allOf'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'declawed' => 'bool' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'declawed' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'declawed' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'declawed' => 'declawed' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'declawed' => 'setDeclawed' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'declawed' => 'getDeclawed' - ]; - - /** - * 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->setIfExists('declawed', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 declawed - * - * @return bool|null - */ - public function getDeclawed() - { - return $this->container['declawed']; - } - - /** - * Sets declawed - * - * @param bool|null $declawed declawed - * - * @return self - */ - public function setDeclawed($declawed) - { - if (is_null($declawed)) { - throw new \InvalidArgumentException('non-nullable declawed cannot be null'); - } - $this->container['declawed'] = $declawed; - - 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-nextgen/OpenAPIClient-php/src/Model/DogAllOf.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/DogAllOf.php deleted file mode 100644 index 0063d884f18a..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/DogAllOf.php +++ /dev/null @@ -1,409 +0,0 @@ - - */ -class DogAllOf implements ModelInterface, ArrayAccess, \JsonSerializable -{ - public const DISCRIMINATOR = null; - - /** - * The original name of the model. - * - * @var string - */ - protected static $openAPIModelName = 'Dog_allOf'; - - /** - * Array of property to type mappings. Used for (de)serialization - * - * @var string[] - */ - protected static $openAPITypes = [ - 'breed' => 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * - * @var string[] - * @phpstan-var array - * @psalm-var array - */ - protected static $openAPIFormats = [ - 'breed' => null - ]; - - /** - * Array of nullable properties. Used for (de)serialization - * - * @var boolean[] - */ - protected static array $openAPINullables = [ - 'breed' => false - ]; - - /** - * If a nullable field gets set to null, insert it here - * - * @var boolean[] - */ - protected array $openAPINullablesSetToNull = []; - - /** - * 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 nullable properties - * - * @return array - */ - protected static function openAPINullables(): array - { - return self::$openAPINullables; - } - - /** - * Array of nullable field names deliberately set to null - * - * @return boolean[] - */ - private function getOpenAPINullablesSetToNull(): array - { - return $this->openAPINullablesSetToNull; - } - - /** - * Setter - Array of nullable field names deliberately set to null - * - * @param boolean[] $openAPINullablesSetToNull - */ - private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void - { - $this->openAPINullablesSetToNull = $openAPINullablesSetToNull; - } - - /** - * Checks if a property is nullable - * - * @param string $property - * @return bool - */ - public static function isNullable(string $property): bool - { - return self::openAPINullables()[$property] ?? false; - } - - /** - * Checks if a nullable property is set to null. - * - * @param string $property - * @return bool - */ - public function isNullableSetToNull(string $property): bool - { - return in_array($property, $this->getOpenAPINullablesSetToNull(), true); - } - - /** - * Array of attributes where the key is the local name, - * and the value is the original name - * - * @var string[] - */ - protected static $attributeMap = [ - 'breed' => 'breed' - ]; - - /** - * Array of attributes to setter functions (for deserialization of responses) - * - * @var string[] - */ - protected static $setters = [ - 'breed' => 'setBreed' - ]; - - /** - * Array of attributes to getter functions (for serialization of requests) - * - * @var string[] - */ - protected static $getters = [ - 'breed' => 'getBreed' - ]; - - /** - * 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->setIfExists('breed', $data ?? [], null); - } - - /** - * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName - * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the - * $this->openAPINullablesSetToNull array - * - * @param string $variableName - * @param array $fields - * @param mixed $defaultValue - */ - private function setIfExists(string $variableName, array $fields, $defaultValue): void - { - if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) { - $this->openAPINullablesSetToNull[] = $variableName; - } - - $this->container[$variableName] = $fields[$variableName] ?? $defaultValue; - } - - /** - * 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 breed - * - * @return string|null - */ - public function getBreed() - { - return $this->container['breed']; - } - - /** - * Sets breed - * - * @param string|null $breed breed - * - * @return self - */ - public function setBreed($breed) - { - if (is_null($breed)) { - throw new \InvalidArgumentException('non-nullable breed cannot be null'); - } - $this->container['breed'] = $breed; - - 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-nextgen/OpenAPIClient-php/src/Model/EnumClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumClass.php index 309739e44c5a..554e0f359425 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumClass.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumClass.php @@ -41,7 +41,6 @@ enum EnumClass: string case EFG = '-efg'; case XYZ = '(xyz)'; - } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php index e27329183f4b..56d1a53b62b0 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php @@ -275,9 +275,9 @@ public function getModelName(): string public const ENUM_STRING_REQUIRED_UPPER = 'UPPER'; public const ENUM_STRING_REQUIRED_LOWER = 'lower'; public const ENUM_STRING_REQUIRED_EMPTY = ''; - public const ENUM_INTEGER_1 = 1; + public const ENUM_INTEGER_NUMBER_1 = 1; public const ENUM_INTEGER_MINUS_1 = -1; - public const ENUM_NUMBER_1_DOT_1 = 1.1; + public const ENUM_NUMBER_NUMBER_1_DOT_1 = 1.1; public const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; /** @@ -316,7 +316,7 @@ public function getEnumStringRequiredAllowableValues() public function getEnumIntegerAllowableValues() { return [ - self::ENUM_INTEGER_1, + self::ENUM_INTEGER_NUMBER_1, self::ENUM_INTEGER_MINUS_1, ]; } @@ -329,7 +329,7 @@ public function getEnumIntegerAllowableValues() public function getEnumNumberAllowableValues() { return [ - self::ENUM_NUMBER_1_DOT_1, + self::ENUM_NUMBER_NUMBER_1_DOT_1, self::ENUM_NUMBER_MINUS_1_DOT_2, ]; } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/SingleRefType.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumWithNameAndDescription.php similarity index 59% rename from samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/SingleRefType.php rename to samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumWithNameAndDescription.php index a785e84e9540..1bfaa9daf841 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/SingleRefType.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumWithNameAndDescription.php @@ -1,10 +1,9 @@ api = new Api\PetApi(); - - $this->petId = 10005; - $pet = new Model\Pet; - $pet->setId($this->petId); - $pet->setName("PHP Unit Test"); - $pet->setPhotoUrls(array("http://test_php_unit_test.com")); - // new tag - $tag= new Model\Tag; - $tag->setId($this->petId); // use the same id as pet - $tag->setName("test php tag"); - // new category - $category = new Model\Category; - $category->setId($this->petId); // use the same id as pet - $category->setName("test php category"); - - $pet->setTags(array($tag)); - $pet->setCategory($category); - - $pet_api = new Api\PetApi(); - // add a new pet (model) - $add_response = $pet_api->addPet($pet); - } - - public function testAsyncRequest() - { - $promise = $this->api->getPetByIdAsync(10005); - - $promise2 = $this->api->getPetByIdAsync(10005); - - $pet = $promise->wait(); - $pet2 = $promise2->wait(); - $this->assertInstanceOf(Pet::class, $pet); - $this->assertInstanceOf(Pet::class, $pet2); - } - - public function testAsyncRequestWithHttpInfo() - { - $promise = $this->api->getPetByIdAsyncWithHttpInfo($this->petId); - - list($pet, $status, $headers) = $promise->wait(); - $this->assertEquals(200, $status); - $this->assertIsArray($headers); - $this->assertInstanceOf(Pet::class, $pet); - } - - public function testAsyncThrowingException() - { - $this->expectException(\OpenAPI\Client\ApiException::class); - $promise = $this->api->getPetByIdAsync(0); - $promise->wait(); - } - - /** - * @doesNotPerformAssertions - */ - public function testAsyncApiExceptionWithoutWaitIsNotThrown() - { - $promise = $this->api->getPetByIdAsync(0); - sleep(1); - } - - public function testAsyncHttpInfoThrowingException() - { - $this->expectException(\OpenAPI\Client\ApiException::class); - $promise = $this->api->getPetByIdAsyncWithHttpInfo(0); - $promise->wait(); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/AuthTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/AuthTest.php deleted file mode 100644 index 5a4755bcc61b..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/AuthTest.php +++ /dev/null @@ -1,63 +0,0 @@ -setApiKey('api_key', '123qwe'); - - $fakeHttpClient = new FakeHttpClient(); - $api = new PetApi($fakeHttpClient, $authConfig); - $api->getPetById(123); - - $headers = $fakeHttpClient->getLastRequest()->getHeaders(); - - $this->assertArrayHasKey('api_key', $headers); - $this->assertEquals(['123qwe'], $headers['api_key']); - } - - public function testApiToken() - { - $authConfig = new Configuration(); - $authConfig->setAccessToken('asd123'); - - $fakeHttpClient = new FakeHttpClient(); - $api = new PetApi($fakeHttpClient, $authConfig); - $api->addPet(new Pet(array('name' => 'testing', 'photo_urls' => array('http://a.com')))); - - $headers = $fakeHttpClient->getLastRequest()->getHeaders(); - - $this->assertArrayHasKey('Authorization', $headers); - $this->assertEquals(['Bearer asd123'], $headers['Authorization']); - } - - public function testBasicAuth() - { - $username = 'user'; - $password = 'password'; - - $authConfig = new Configuration(); - $authConfig->setUsername($username); - $authConfig->setPassword($password); - - $fakeHttpClient = new FakeHttpClient(); - $api = new FakeApi($fakeHttpClient, $authConfig); - $api->testEndpointParameters(123, 100.1, 'ASD_', 'ASD'); - - $headers = $fakeHttpClient->getLastRequest()->getHeaders(); - - $this->assertArrayHasKey('Authorization', $headers); - $encodedCredentials = base64_encode("$username:$password"); - $this->assertEquals(["Basic $encodedCredentials"], $headers['Authorization']); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ConfigurationTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ConfigurationTest.php deleted file mode 100644 index eedbca0a89fc..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ConfigurationTest.php +++ /dev/null @@ -1,67 +0,0 @@ -getHostSettings(); - - $this->assertCount(3, $servers); - $this->assertSame("http://{server}.swagger.io:{port}/v2", $servers[0]["url"]); - $this->assertSame("petstore", $servers[0]["variables"]["server"]["default_value"]); - $this->assertSame("80", $servers[0]["variables"]["port"]["default_value"]); - $this->assertSame(array("80", "8080"), $servers[0]["variables"]["port"]["enum_values"]); - } - - /** - * Test server settings - */ - public function testServerUrl() - { - $config = new Configuration(); - // default value - $url = $config->getHostFromSettings(0); - $this->assertSame("http://petstore.swagger.io:80/v2", $url); - - // using a variable - $url = $config->getHostFromSettings(0, array("server" => "dev-petstore")); - $this->assertSame("http://dev-petstore.swagger.io:80/v2", $url); - - // using 2 variables - $url = $config->getHostFromSettings(0, array("server" => "dev-petstore", "port" => "8080")); - $this->assertSame("http://dev-petstore.swagger.io:8080/v2", $url); - } - - /** - * Test invalid index - */ - public function testInvalidIndex() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid index 3 when selecting the host. Must be less than 3'); - $config = new Configuration(); - $url = $config->getHostFromSettings(3); - } - - /** - * Test host settings with invalid values - */ - public function testHostUrlWithInvalidValues() - { - // using 2 variables with invalid values - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The variable `port` in the host URL has invalid value 8. Must be 80,8080'); - $config = new Configuration(); - $url = $config->getHostFromSettings(0, array("server" => "dev-petstore", "port" => "8")); - $this->assertSame("http://dev-petstore.swagger.io:8080/v2", $url); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/DateTimeSerializerTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/DateTimeSerializerTest.php deleted file mode 100644 index 5aee91c5a906..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/DateTimeSerializerTest.php +++ /dev/null @@ -1,48 +0,0 @@ - $dateTime, - 'date' => $dateTime, - 'number' => 123.45, - 'password' => 'password', - 'byte' => '0101' - ]); - - $data = ObjectSerializer::sanitizeForSerialization($input); - - $this->assertEquals('1973-04-30T17:05:00+02:00', $data->dateTime); - - ObjectSerializer::setDateTimeFormat(\DateTime::RFC3339_EXTENDED); - $dataFraction = ObjectSerializer::sanitizeForSerialization($input); - $this->assertEquals('1973-04-30T17:05:00.000+02:00', $dataFraction->dateTime); - ObjectSerializer::setDateTimeFormat(\DateTime::ATOM); - } - - public function testDateSanitation() - { - $dateTime = new \DateTime('April 30, 1973 17:05 CEST'); - - $input = new FormatTest([ - 'date_time' => $dateTime, - 'date' => $dateTime, - 'number' => 123.45, - 'password' => 'password', - 'byte' => '0101' - ]); - - $data = ObjectSerializer::sanitizeForSerialization($input); - - $this->assertEquals('1973-04-30', $data->date); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/DebugTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/DebugTest.php deleted file mode 100644 index b14dd018df03..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/DebugTest.php +++ /dev/null @@ -1,38 +0,0 @@ -setId(1); - $newPet->setName("PHP Unit Test"); - (new Api\PetApi())->addPetWithHttpInfo($newPet); - } - - public function testEnableDebugOutput() - { - $this->expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#'); - - $config = new Configuration(); - $config->setDebug(true); - $api = new Api\PetApi(null, $config); - $api->getPetById(1); - } - - public function testEnableDebugOutputAsync() - { - $this->expectOutputRegex('#GET /v2/pet/1 HTTP/1.1#'); - - $config = new Configuration(); - $config->setDebug(true); - $api = new Api\PetApi(null, $config); - $promise = $api->getPetByIdAsync(1); - $promise->wait(); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/EnumClassTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/EnumClassTest.php deleted file mode 100644 index fbc089c7f187..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/EnumClassTest.php +++ /dev/null @@ -1,16 +0,0 @@ -assertSame(EnumClass::ABC, '_abc'); - $this->assertSame(EnumClass::EFG, '-efg'); - $this->assertSame(EnumClass::XYZ, '(xyz)'); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/EnumTestTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/EnumTestTest.php deleted file mode 100644 index e1111d1223c0..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/EnumTestTest.php +++ /dev/null @@ -1,57 +0,0 @@ -assertSame(EnumTest::ENUM_STRING_UPPER, "UPPER"); - $this->assertSame(EnumTest::ENUM_STRING_LOWER, "lower"); - $this->assertSame(EnumTest::ENUM_INTEGER_1, 1); - $this->assertSame(EnumTest::ENUM_INTEGER_MINUS_1, -1); - $this->assertSame(EnumTest::ENUM_NUMBER_1_DOT_1, 1.1); - $this->assertSame(EnumTest::ENUM_NUMBER_MINUS_1_DOT_2, -1.2); - } - - public function testStrictValidation() - { - $enum = new EnumTest([ - 'enum_string' => 0, - ]); - - $this->assertFalse($enum->valid()); - - $expected = [ - "invalid value '0' for 'enum_string', must be one of 'UPPER', 'lower', ''", - "'enum_string_required' can't be null", - ]; - $this->assertSame($expected, $enum->listInvalidProperties()); - } - - public function testThrowExceptionWhenInvalidAmbiguousValueHasPassed() - { - $this->expectException(\InvalidArgumentException::class); - $enum = new EnumTest(); - $enum->setEnumString(0); - } - - public function testNonRequiredPropertyIsOptional() - { - $enum = new EnumTest([ - 'enum_string_required' => 'UPPER', - ]); - $this->assertSame([], $enum->listInvalidProperties()); - $this->assertTrue($enum->valid()); - } - - public function testRequiredProperty() - { - $enum = new EnumTest(); - $this->assertSame(["'enum_string_required' can't be null"], $enum->listInvalidProperties()); - $this->assertFalse($enum->valid()); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ExceptionTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ExceptionTest.php deleted file mode 100644 index c12388187fd3..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ExceptionTest.php +++ /dev/null @@ -1,39 +0,0 @@ -expectException(\OpenAPI\Client\ApiException::class); - $this->expectExceptionCode(404); - $this->expectExceptionMessage('http://petstore.swagger.io/INVALID_URL/store/inventory'); - $config = new Configuration(); - $config->setHost('http://petstore.swagger.io/INVALID_URL'); - - $api = new Api\StoreApi( - new Client(), - $config - ); - $api->getInventory(); - } - - public function testWrongHost() - { - $this->expectException(\OpenAPI\Client\ApiException::class); - $this->expectExceptionMessage('Could not resolve'); - $this->expectExceptionMessage('wrong_host.zxc'); - $config = new Configuration(); - $config->setHost('http://wrong_host.zxc'); - - $api = new Api\StoreApi( - new Client(), - $config - ); - $api->getInventory(); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/FakeHttpClient.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/FakeHttpClient.php deleted file mode 100644 index f5e32d4c6593..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/FakeHttpClient.php +++ /dev/null @@ -1,70 +0,0 @@ -request; - } - - /** - * @param null|ResponseInterface $response - */ - public function setResponse(ResponseInterface $response = null) - { - $this->response = $response; - } - - /** - * Send an HTTP request. - * - * @param RequestInterface $request Request to send - * @param array $options Request options to apply to the given - * request and to the transfer. - * - * @return ResponseInterface - * @throws GuzzleException - */ - public function send(RequestInterface $request, array $options = []): ResponseInterface - { - $this->request = $request; - return $this->response ?: new Response(200); - } - - public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface - { - throw new \RuntimeException('not implemented'); - } - - public function request($method, $uri, array $options = []): ResponseInterface - { - throw new \RuntimeException('not implemented'); - } - - public function requestAsync($method, $uri, array $options = []): PromiseInterface - { - throw new \RuntimeException('not implemented'); - } - - public function getConfig($option = null) - { - throw new \RuntimeException('not implemented'); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/FormatTestTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/FormatTestTest.php deleted file mode 100644 index 0d96987614c0..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/FormatTestTest.php +++ /dev/null @@ -1,27 +0,0 @@ - $the64MultiByteStrings, - // mandatory parameters - 'number' => 500, - 'byte' => base64_encode('test'), - 'date' => new DateTime(), - ]); - - $this->assertEmpty($formatTest->listInvalidProperties()); - - // Pass the strings via setter. - // Throws InvalidArgumentException if it doesn't count the length correctly. - $formatTest->setPassword($the64MultiByteStrings); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/HeaderSelectorTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/HeaderSelectorTest.php deleted file mode 100644 index f5c804b8e3b3..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/HeaderSelectorTest.php +++ /dev/null @@ -1,163 +0,0 @@ -selectHeaders($accept, $contentType, $isMultiple); - $this->assertEquals($expectedHeaders, $headers); - } - - /** - * @return array[][] - */ - public function headersProvider(): array - { - $data = [ - // array $accept, string $contentType, bool $isMultipart, array $expectedHeaders - [ - # No Accept, Content-Type - [], 'application/xml', false, ['Content-Type' => 'application/xml'], - ], - [ - # No Accept, Content-Type, multipart - [], 'application/xml', true, [], - ], - [ - # single Accept, no Content-Type - ['application/xml'], '', false, ['Accept' => 'application/xml', 'Content-Type' => 'application/json'], - ], - [ - # single Accept, no Content-Type, multipart - ['application/xml'], '', true, ['Accept' => 'application/xml'], - ], - [ - # single Accept, Content-Type - ['application/xml'], 'application/xml', false, ['Accept' => 'application/xml', 'Content-Type' => 'application/xml'], - ], - [ - # single Accept, Content-Type, multipart - ['application/xml'], 'application/xml', true, ['Accept' => 'application/xml'], - ], - [ - # single Accept with parameters, Content-Type with parameters - ['application/json;format=flowed'], 'text/plain;format=fixed', false, ['Accept' => 'application/json;format=flowed', 'Content-Type' => 'text/plain;format=fixed'], - ], - - # Tests for Accept headers - no change on Content-Type or multipart setting - [ - # Multiple Accept without Json - ['application/xml', 'text/html'], '', true, ['Accept' => 'application/xml,text/html'], - ], - [ - # Multiple Accept with application/json - ['application/json', 'text/html'], '', true, ['Accept' => 'application/json,text/html;q=0.9'], - ], - [ - # Multiple Accept with json-like - ['text/html', 'application/xml+json'], '', true, ['Accept' => 'application/xml+json,text/html;q=0.9'], - ], - [ - # Multiple Accept with application/json and json-like - ['text/html', 'application/json', 'application/xml+json'], '', true, ['Accept' => 'application/json,application/xml+json;q=0.9,text/html;q=0.8'], - ], - [ - # Multiple Accept, changing priority to application/json - ['application/xml', 'application/json;q=0.9', 'text/plain;format=flowed;q=0.8'], '', true, ['Accept' => 'application/json,application/xml;q=0.9,text/plain;format=flowed;q=0.8'], - ], - [ - # Multiple Accept, same priority for two headers, one being application/json - ['application/xml', 'application/json', 'text/plain;format=flowed;q=0.9'], '', true, ['Accept' => 'application/json,application/xml;q=0.9,text/plain;format=flowed;q=0.8'], - ], - [ - # Multiple Accept, same priority for two headers, both being application/json - ['application/json', 'application/json;IEEE754Compatible=true', 'text/plain;format=flowed;q=0.9'], '', true, ['Accept' => 'application/json,application/json;IEEE754Compatible=true,text/plain;format=flowed;q=0.9'], - ], - [ - # Multiple Accept, same priority for three headers, two being application/json, with changing priority - ['application/json;q=0.9', 'application/json;IEEE754Compatible=true;q=0.9', 'application/xml', 'text/plain;format=flowed;q=0.9'], '', true, ['Accept' => 'application/json,application/json;IEEE754Compatible=true,application/xml;q=0.9,text/plain;format=flowed;q=0.8'], - ], - ]; - - # More than 28 Accept headers - $data[] = $this->createTestDataForLargeNumberOfAcceptHeaders(30); - - # More than 1000 Accept headers - $data[] = $this->createTestDataForLargeNumberOfAcceptHeaders(1000); - - return $data; - } - - /** - * @param int $numberOfHeaders - * @return array - */ - private function createTestDataForLargeNumberOfAcceptHeaders(int $numberOfHeaders): array - { - $acceptHeaders = ['application/json;q=0.9']; - $expected = ['application/json']; - for ($i=1; $i<$numberOfHeaders; $i++) { - $q = rtrim(sprintf('%0.3f', (1000 - $i) / 1000), '0'); - $acceptHeaders[] = "application/xml;option=$i;q=$q"; - $expected[] = "application/xml;option=$i;q=$q"; - } - - return [ - $acceptHeaders, - '', - true, - ['Accept' => implode(',', $expected)] - ]; - } - - /** - * @dataProvider nextWeightProvider - * @param int $currentWeight - * @param bool $bHasMoreThan28Headers - * @param int $expected - */ - public function testGetNextWeight(int $currentWeight, bool $bHasMoreThan28Headers, int $expected): void - { - $selector = new HeaderSelector(); - - self::assertEquals($expected, $selector->getNextWeight($currentWeight, $bHasMoreThan28Headers)); - } - - public function nextWeightProvider(): array - { - return [ - [1000, true, 999], - [999, true, 998], - [2, true, 1], - [1, true, 1], - [1000, false, 900], - [900, false, 800], - [200, false, 100], - [100, false, 90], - [90, false, 80], - [20, false, 10], - [10, false, 9], - [9, false, 8], - [2, false, 1], - [1, false, 1], - [0, false, 1], - ]; - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ModelInheritanceTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ModelInheritanceTest.php deleted file mode 100644 index 333b88bbedaa..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ModelInheritanceTest.php +++ /dev/null @@ -1,96 +0,0 @@ -assertSame('red', $dog->getColor()); - $this->assertSame('red', $animal->getColor()); - } - - /** - * test inheritance in the model - */ - public function testInheritance() - { - $newDog = new Dog; - // the object should be an instance of the derived class - $this->assertInstanceOf(Dog::class, $newDog); - // the object should also be an instance of the parent class - $this->assertInstanceOf(Animal::class, $newDog); - } - - /** - * test inheritance constructor is working with data initialization - */ - public function testInheritanceConstructorDataInitialization() - { - // initialize the object with data in the constructor - $data = [ - 'class_name' => 'Dog', - 'breed' => 'Great Dane', - ]; - $newDog = new Dog($data); - - // the property on the derived class should be set - $this->assertSame('Great Dane', $newDog->getBreed()); - // the property on the parent class should be set - $this->assertSame('Dog', $newDog->getClassName()); - } - - /** - * test if discriminator is initialized automatically - */ - public function testDiscriminatorInitialization() - { - $newDog = new Dog(); - $this->assertSame('Dog', $newDog->getClassName()); - } - - /** - * test if ArrayAccess interface works - */ - public function testArrayStuff() - { - // create an array of Animal - $farm = array(); - - // add some animals to the farm to make sure the ArrayAccess interface works - $farm[] = new Dog(); - $farm[] = new Cat(); - $farm[] = new Animal(); - - // assert we can look up the animals in the farm by array indices (let's try a random order) - $this->assertInstanceOf(Cat::class, $farm[1]); - $this->assertInstanceOf(Dog::class, $farm[0]); - $this->assertInstanceOf(Animal::class, $farm[2]); - - // let's try to `foreach` the animals in the farm and let's try to use the objects we loop through - foreach ($farm as $animal) { - $this->assertContains($animal->getClassName(), ['Dog', 'Cat', 'Animal']); - $this->assertInstanceOf('OpenAPI\Client\Model\Animal', $animal); - } - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/NullableTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/NullableTest.php deleted file mode 100644 index c80812db339f..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/NullableTest.php +++ /dev/null @@ -1,45 +0,0 @@ -setName(1); - $this->assertEquals(1, $name->getName(), 'Non-nullable property can be set and retains its value'); - - // comment out below as strict type is now enabled - //$this->expectException(InvalidArgumentException::class); - //$this->expectExceptionMessage('non-nullable name cannot be null'); - - $this->expectException(TypeError::class); - $this->expectExceptionMessage('must be of type int, null given'); - - //Failed asserting that exception of type "TypeError" matches expected exception "InvalidArgumentException". Message was: "OpenAPI\Client\Model\Name::setName(): Argument #1 ($name) must be of type int, null given, called in /Users/williamcheng/Code/openapi-generator7/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/NullableTest.php on line 26" at - $name->setName(null); - - } - - public function testNullableobject(): void - { - $nullable = new NullableClass(); - - $nullable->setIntegerProp(null); - $this->assertNull($nullable->getIntegerProp(), 'Nullable property can be set to null retains its value'); - - $nullable->setIntegerProp(1); - $this->assertEquals(1, $nullable->getIntegerProp(), 'Nullable property can be set and retains its value'); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ObjectSerializerTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ObjectSerializerTest.php deleted file mode 100644 index aa1357161ac9..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ObjectSerializerTest.php +++ /dev/null @@ -1,634 +0,0 @@ -assertSame("sun.gif", ObjectSerializer::sanitizeFilename("sun.gif")); - $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("../sun.gif")); - $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("/var/tmp/sun.gif")); - $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("./sun.gif")); - - $this->assertSame("sun", ObjectSerializer::sanitizeFilename("sun")); - $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("..\sun.gif")); - $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("\var\tmp\sun.gif")); - $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename("c:\var\tmp\sun.gif")); - $this->assertSame("sun.gif", ObjectSerializer::sanitizeFilename(".\sun.gif")); - } - - /** - * Test SplFileObject class deserialization. - * - * @see https://github.com/OpenAPITools/openapi-generator/pull/11184 - * @covers ObjectSerializer::deserialize - * @dataProvider provideFileStreams - */ - public function testDeserializeFile($stream, ?array $httpHeaders = null, ?string $expectedFilename = null): void - { - $s = new ObjectSerializer(); - - /** @var SplFileObject $file */ - $file = ObjectSerializer::deserialize($stream, '\SplFileObject', $httpHeaders); - $this->assertInstanceOf(SplFileObject::class, $file); - - if (is_string($expectedFilename)) { - $this->assertEquals($expectedFilename, $file->getFilename()); - } else { - $this->assertNotEquals($expectedFilename, $file->getFilename()); - } - } - - /** - * File Streams Provider - * @return array[] - */ - public function provideFileStreams(): array - { - return [ - 'File stream without headers' => [ - Utils::streamFor(\fopen(__FILE__, 'r')), - null, - null, - ], - 'File stream with Content-Disposition header' => [ - Utils::streamFor(\fopen(__FILE__, 'r')), - ['Content-Disposition' => 'inline; filename=\'foobar.php\''], - 'foobar.php', - ], - 'File path' => [ - __FILE__, - null, - null, - ], - ]; - } - - /** - * @covers ObjectSerializer::sanitizeTimestamp - * @dataProvider provideTimestamps - */ - public function testSanitizeTimestamp(string $timestamp, string $expected): void - { - $this->assertEquals($expected, ObjectSerializer::sanitizeTimestamp($timestamp)); - } - - /** - * Test datetime deserialization. - * - * @covers ObjectSerializer::deserialize - * @dataProvider provideTimestamps - * - * @see https://github.com/OpenAPITools/openapi-generator/issues/7942 - * @see https://github.com/OpenAPITools/openapi-generator/issues/10548 - */ - public function testDateTimeParseSecondAccuracy(string $timestamp, string $expected): void - { - $dateTime = ObjectSerializer::deserialize($timestamp, '\DateTime'); - $this->assertEquals(new DateTime($expected), $dateTime); - } - - /** - * Timestamps provider - * - * @return string[][] - */ - public function provideTimestamps(): array - { - return [ - 'String from #7942' => [ - '2020-11-11T15:17:58.868722633Z', - '2020-11-11T15:17:58.868722Z', - ], - 'String from #10548' => [ - '2021-10-06T20:17:16.076372256Z', - '2021-10-06T20:17:16.076372Z', - ], - 'Without timezone' => [ - '2021-10-06T20:17:16.076372256', - '2021-10-06T20:17:16.076372', - ], - 'Without microseconds' => [ - '2021-10-06T20:17:16', - '2021-10-06T20:17:16', - ], - 'Without microseconds with timezone' => [ - '2021-10-06T20:17:16Z', - '2021-10-06T20:17:16Z', - ], - 'With numeric timezone' => [ - '2021-10-06T20:17:16.076372256+03:00', - '2021-10-06T20:17:16.076372+03:00', - ], - 'With numeric timezone without delimiter' => [ - '2021-10-06T20:17:16.076372256+0300', - '2021-10-06T20:17:16.076372+0300', - ], - 'With numeric short timezone' => [ - '2021-10-06T20:17:16.076372256+03', - '2021-10-06T20:17:16.076372+03', - ], - ]; - } - - /** - * @covers ObjectSerializer::toQueryValue - * @dataProvider provideQueryParams - */ - public function testToQueryValue( - $data, - string $paramName, - string $openApiType, - string $style, - bool $explode, - bool $required, - $expected - ): void { - $value = ObjectSerializer::toQueryValue($data, $paramName, $openApiType, $style, $explode, $required); - $query = ObjectSerializer::buildQuery($value); - $this->assertEquals($expected, $query); - } - - /** - * Query params provider - * - * @return array[] - */ - public function provideQueryParams(): array - { - $array = ['blue', 'black', 'brown']; - $object = ['R' => 100, 'G' => 200, 'B' => 150]; - - return [ - // style form - // skipValidation - 'form boolean, explode on, required false' => [ - false, 'skipValidation', 'boolean', 'form', true, false, 'skipValidation=0', - ], - 'form empty boolean, explode on, required false' => [ - null, 'skipValidation', 'boolean', 'form', true, false, '', - ], - 'form empty boolean, explode on, required true' => [ - null, 'skipValidation', 'boolean', 'form', true, true, 'skipValidation=', - ], - // color= - 'form empty, explode on, required true' => [ - '', 'color', 'string', 'form', true, true, 'color=', - ], - 'form empty, explode on, required false' => [ - '', 'color', 'string', 'form', true, false, '', - ], - // color= - 'form empty, explode off, required true' => [ - '', 'color', 'string', 'form', false, true, 'color=', - ], - // color=blue - 'form string, explode on, required true' => [ - 'blue', 'color', 'string', 'form', true, true, 'color=blue', - ], - // color=blue - 'form string, explode off, required true' => [ - 'blue', 'color', 'string', 'form', false, true, 'color=blue', - ], - // color=blue&color=black&color=brown - 'form array, explode on, required true' => [ - $array, 'color', 'array', 'form', true, true, 'color=blue&color=black&color=brown', - ], - // color=blue&color=black&color=brown - 'form nested array, explode on, required true' => [ - ['foobar' => $array], 'color', 'array', 'form', true, true, 'color=blue&color=black&color=brown', - ], - // color=blue,black,brown - 'form array, explode off, required true' => [ - $array, 'color', 'array', 'form', false, true, 'color=blue%2Cblack%2Cbrown', - ], - // color=blue,black,brown - 'form nested array, explode off, required true' => [ - ['foobar' => $array], 'color', 'array', 'form', false, true, 'color=blue%2Cblack%2Cbrown', - ], - // R=100&G=200&B=150 - 'form object, explode on, required true' => [ - $object, 'color', 'object', 'form', true, true, 'R=100&G=200&B=150', - ], - // color=R,100,G,200,B,150 - 'form object, explode off, required true' => [ - $object, 'color', 'object', 'form', false, true, 'color=R%2C100%2CG%2C200%2CB%2C150', - ], - - // SPACE DELIMITED - // color=blue - 'spaceDelimited primitive, explode off, required true' => [ - 'blue', 'color', 'string', 'spaceDelimited', false, true, 'color=blue', - ], - // color=blue - 'spaceDelimited primitive, explode on, required true' => [ - 'blue', 'color', 'string', 'spaceDelimited', true, true, 'color=blue', - ], - // color=blue%20black%20brown - 'spaceDelimited array, explode off, required true' => [ - $array, 'color', 'array', 'spaceDelimited', false, true, 'color=blue%20black%20brown', - ], - // color=blue&color=black&color=brown - 'spaceDelimited array, explode on, required true' => [ - $array, 'color', 'array', 'spaceDelimited', true, true, 'color=blue&color=black&color=brown', - ], - // color=R%20100%20G%20200%20B%20150 - // swagger editor gives color=R,100,G,200,B,150 - 'spaceDelimited object, explode off, required true' => [ - $object, 'color', 'object', 'spaceDelimited', false, true, 'color=R%20100%20G%20200%20B%20150', - ], - // R=100&G=200&B=150 - 'spaceDelimited object, explode on, required true' => [ - $object, 'color', 'object', 'spaceDelimited', true, true, 'R=100&G=200&B=150', - ], - - // PIPE DELIMITED - // color=blue - 'pipeDelimited primitive, explode off, required true' => [ - 'blue', 'color', 'string', 'pipeDelimited', false, true, 'color=blue', - ], - // color=blue - 'pipeDelimited primitive, explode on, required true' => [ - 'blue', 'color', 'string', 'pipeDelimited', true, true, 'color=blue', - ], - // color=blue|black|brown - 'pipeDelimited array, explode off, required true' => [ - $array, 'color', 'array', 'pipeDelimited', false, true, 'color=blue%7Cblack%7Cbrown', - ], - // color=blue&color=black&color=brown - 'pipeDelimited array, explode on, required true' => [ - $array, 'color', 'array', 'pipeDelimited', true, true, 'color=blue&color=black&color=brown', - ], - // color=R|100|G|200|B|150 - // swagger editor gives color=R,100,G,200,B,150 - 'pipeDelimited object, explode off, required true' => [ - $object, 'color', 'object', 'pipeDelimited', false, true, 'color=R%7C100%7CG%7C200%7CB%7C150', - ], - // R=100&G=200&B=150 - 'pipeDelimited object, explode on, required true' => [ - $object, 'color', 'object', 'pipeDelimited', true, true, 'R=100&G=200&B=150', - ], - - // DEEP OBJECT - // color=blue - 'deepObject primitive, explode off, required true' => [ - 'blue', 'color', 'string', 'deepObject', false, true, 'color=blue', - ], - 'deepObject primitive, explode on, required true' => [ - 'blue', 'color', 'string', 'deepObject', true, true, 'color=blue', - ], - // color=blue,black,brown - 'deepObject array, explode off, required true' => [ - $array, 'color', 'array', 'deepObject', false, true, 'color=blue%2Cblack%2Cbrown', - ], - // color=blue&color=black&color=brown - 'deepObject array, explode on, required true' => [ - $array, 'color', 'array', 'deepObject', true, true, 'color=blue&color=black&color=brown', - ], - // color[R]=100&color[G]=200&color[B]=150 - 'deepObject object, explode off, required true' => [ - $object, 'color', 'object', 'deepObject', false, true, 'color%5BR%5D=100&color%5BG%5D=200&color%5BB%5D=150', - ], - // color[R]=100&color[G]=200&color[B]=150 - 'deepObject object, explode on, required true' => [ - $object, 'color', 'object', 'deepObject', true, true, 'color%5BR%5D=100&color%5BG%5D=200&color%5BB%5D=150', - ], - // filter[or][0][name]=John&filter[or][1][email]=john@doe.com - 'example from @nadar' => [ - [ - 'or' => - [ - ['name' => 'John'], - ['email' => 'john@doe.com'], - ], - ], - 'filter', - 'object', - 'deepObject', - true, - true, - 'filter%5Bor%5D%5B0%5D%5Bname%5D=John&filter%5Bor%5D%5B1%5D%5Bemail%5D=john%40doe.com' - ], - 'form DateTime object, explode on, required true' => [ - new DateTime('2021-10-06T20:17:16'), 'dateTime', '\DateTime', 'form', true, true, 'dateTime=2021-10-06T20%3A17%3A16%2B00%3A00', - ], - 'form null DateTime object, explode on, required true' => [ - null, 'dateTime', '\DateTime', 'form', true, true, 'dateTime=', - ], - 'form null DateTime object, explode on, required false' => [ - null, 'dateTime', '\DateTime', 'form', true, false, '', - ], - 'form 1 int, explode on, required false' => [ - 1, 'field', 'int', 'form', true, false, 'field=1', - ], - 'form 0 int, explode on, required false' => [ - 0, 'field', 'int', 'form', true, false, 'field=0', - ], - 'form 0 int, explode on, required true' => [ - 0, 'field', 'int', 'form', true, true, 'field=0', - ], - 'form null int, explode on, required false' => [ - null, 'field', 'int', 'form', true, false, '', - ], - 'form null int, explode on, required true' => [ - null, 'field', 'int', 'form', true, true, 'field=', - ], - 'form 1 integer, explode on, required false' => [ - 1, 'field', 'integer', 'form', true, false, 'field=1', - ], - 'form 0 integer, explode on, required false' => [ - 0, 'field', 'integer', 'form', true, false, 'field=0', - ], - 'form 0 integer, explode on, required true' => [ - 0, 'field', 'integer', 'form', true, true, 'field=0', - ], - 'form null integer, explode on, required false' => [ - null, 'field', 'integer', 'form', true, false, '', - ], - 'form null integer, explode on, required true' => [ - null, 'field', 'integer', 'form', true, true, 'field=', - ], - 'form 1.1 float, explode on, required false' => [ - 1.1, 'field', 'float', 'form', true, false, 'field=1.1', - ], - 'form 0 float, explode on, required false' => [ - 0, 'field', 'float', 'form', true, false, 'field=0', - ], - 'form 0.0 float, explode on, required false' => [ - 0.0, 'field', 'float', 'form', true, false, 'field=0', - ], - 'form 0 float, explode on, required true' => [ - 0, 'field', 'float', 'form', true, true, 'field=0', - ], - 'form 0.0 float, explode on, required true' => [ - 0.0, 'field', 'float', 'form', true, true, 'field=0', - ], - 'form null float, explode on, required false' => [ - null, 'field', 'float', 'form', true, false, '', - ], - 'form null float, explode on, required true' => [ - null, 'field', 'float', 'form', true, true, 'field=', - ], - 'form 1.1 number, explode on, required false' => [ - 1.1, 'field', 'number', 'form', true, false, 'field=1.1', - ], - 'form 0 number, explode on, required false' => [ - 0, 'field', 'number', 'form', true, false, 'field=0', - ], - 'form 0.0 number, explode on, required false' => [ - 0.0, 'field', 'number', 'form', true, false, 'field=0', - ], - 'form 0 number, explode on, required true' => [ - 0, 'field', 'number', 'form', true, true, 'field=0', - ], - 'form 0.0 number, explode on, required true' => [ - 0.0, 'field', 'number', 'form', true, true, 'field=0', - ], - 'form null number, explode on, required false' => [ - null, 'field', 'number', 'form', true, false, '', - ], - 'form null number, explode on, required true' => [ - null, 'field', 'number', 'form', true, true, 'field=', - ], - 'form true bool, explode on, required false' => [ - true, 'field', 'bool', 'form', true, false, 'field=1', - ], - 'form false bool, explode on, required false' => [ - false, 'field', 'bool', 'form', true, false, 'field=0', - ], - 'form empty bool, explode on, required false' => [ - null, 'field', 'bool', 'form', true, false, '', - ], - 'form empty bool, explode on, required true' => [ - null, 'field', 'bool', 'form', true, true, 'field=', - ], - # Entries for "boolean" type are already covered in the beginning of this provider - 'form 1 bool, explode on, required false' => [ - 1, 'field', 'bool', 'form', true, false, 'field=1', - ], - 'form 0 bool, explode on, required false' => [ - 0, 'field', 'bool', 'form', true, false, 'field=0', - ], - ]; - } - - /** - * @covers ObjectSerializer::toQueryValue - * @dataProvider provideDeepObjects - */ - public function testDeepObjectStyleQueryParam( - $data, - $paramName, - $expected - ): void { - $value = ObjectSerializer::buildQuery(ObjectSerializer::toQueryValue($data, $paramName, 'object', 'deepObject', true)); - parse_str($value, $result); - $this->assertEquals($expected, $result); - } - - /** - * Deep Objects provider - * - * @return array - */ - public function provideDeepObjects(): array - { - return [ - /** example @see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-examples */ - 'example OpenAPISpec doc' => [ - ['R' => 100, 'G' => 200, 'B' => 150], - 'color', - [ - 'color' => [ - 'R' => 100, - 'G' => 200, - 'B' => 150, - ], - ], - ], - /** example @see https://swagger.io/docs/specification/serialization/ */ - 'example Swagger doc' => [ - ['role' => 'admin', 'firstName' => 'Alex'], - 'id', - [ - 'id' => [ - 'role' => 'admin', - 'firstName' => 'Alex', - ], - ], - ], - ]; - } - - /** - * @dataProvider provideToStringInput - */ - public function testToString($input, string $expected): void - { - $result = ObjectSerializer::toString($input); - - $this->assertSame($expected, $result); - } - - /** - * toString() input provider - * - * @return array - */ - public function provideToStringInput(): array - { - return [ - 'int' => [ - 'input' => 1, - 'expected' => '1', - ], - 'int 0' => [ - 'input' => 0, - 'expected' => '0', - ], - 'false' => [ - 'input' => false, - 'expected' => 'false', - ], - 'true' => [ - 'input' => true, - 'expected' => 'true', - ], - 'some string' => [ - 'input' => 'some string', - 'expected' => 'some string', - ], - 'a date' => [ - 'input' => new DateTime('14-04-2022'), - 'expected' => '2022-04-14T00:00:00+00:00', - ], - ]; - } - - /** - * @covers ObjectSerializer::toQueryValue - * @dataProvider provideQueryParamsWithStringBooleanFormatForQueryString - */ - public function testToQueryValueWithStringBooleanFormatForQueryString( - $data, - string $paramName, - string $openApiType, - string $style, - bool $explode, - bool $required, - $expected - ): void - { - $config = new Configuration(); - $config->setBooleanFormatForQueryString(Configuration::BOOLEAN_FORMAT_STRING); - $config::setDefaultConfiguration($config); - - $value = ObjectSerializer::toQueryValue($data, $paramName, $openApiType, $style, $explode, $required); - $query = ObjectSerializer::buildQuery($value); - $this->assertEquals($expected, $query); - } - - /** - * Query Params with string boolean format provider - * - * @return array[] - */ - public function provideQueryParamsWithStringBooleanFormatForQueryString(): array - { - return [ - // style form - // skipValidation - 'form boolean, required false' => [ - false, 'skipValidation', 'boolean', 'form', true, false, 'skipValidation=false', - ], - 'form empty boolean, required false' => [ - null, 'skipValidation', 'boolean', 'form', true, false, '', - ], - 'form empty boolean, required true' => [ - null, 'skipValidation', 'boolean', 'form', true, true, 'skipValidation=', - ], - 'form true boolean, required true' => [ - true, 'skipValidation', 'boolean', 'form', true, false, 'skipValidation=true', - ], - ]; - } - - /** - * @covers ObjectSerializer::buildQuery - * @dataProvider provideBuildQuery - */ - public function testToBuildQuery( - string $expected, - array $data, - string|null $booleanFormatString = null, - ): void - { - $config = new Configuration(); - if ($booleanFormatString !== null) { - $config->setBooleanFormatForQueryString($booleanFormatString); - } - $config::setDefaultConfiguration($config); - - $query = ObjectSerializer::buildQuery($data); - $this->assertEquals($expected, $query); - } - - /** @return Generator, 2?: Configuration::BOOLEAN_FORMAT_*}> */ - public function provideBuildQuery(): Generator - { - yield 'true as int' => ['foo=1', ['foo' => true]]; - yield 'true as int as default' => ['foo=1', ['foo' => true], Configuration::BOOLEAN_FORMAT_INT]; - yield 'false as int' => ['foo=0', ['foo' => false]]; - yield 'false as int as default' => ['foo=0', ['foo' => false], Configuration::BOOLEAN_FORMAT_INT]; - yield 'true as string' => ['foo=true', ['foo' => true], Configuration::BOOLEAN_FORMAT_STRING]; - yield 'false as string' => ['foo=false', ['foo' => false], Configuration::BOOLEAN_FORMAT_STRING]; - } - - /** - * Test array to class deserialization. - * - * @covers ObjectSerializer::deserialize - * - * @see https://github.com/OpenAPITools/openapi-generator/pull/12849#issuecomment-1186130098 - */ - public function testArrayGivenAsObjectForDeserialize(): void - { - $data = [ - 'name' => 'Pet Name', - 'status' => Pet::STATUS_AVAILABLE, - 'tags' => [ - ['name' => 'Tag Name'], - ] - ]; - - /** @var Pet $pet */ - $pet = ObjectSerializer::deserialize($data, Pet::class); - $this->assertEquals('Pet Name', $pet->getName()); - $this->assertEquals(Pet::STATUS_AVAILABLE, $pet->getStatus()); - - $tags = $pet->getTags(); - $this->assertIsArray($tags); - - $tag = $tags[0]; - $this->assertInstanceOf(Tag::class, $tag); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/OrderApiTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/OrderApiTest.php deleted file mode 100644 index 78cc9d3edf79..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/OrderApiTest.php +++ /dev/null @@ -1,150 +0,0 @@ -assertSame(Model\Order::STATUS_PLACED, "placed"); - $this->assertSame(Model\Order::STATUS_APPROVED, "approved"); - } - - // test get inventory - public function testOrder() - { - // initialize the API client - $order = new Model\Order(); - - $order->setStatus("placed"); - $this->assertSame("placed", $order->getStatus()); - } - - public function testOrderException() - { - // initialize the API client - $this->expectException(\InvalidArgumentException::class); - $order = new Model\Order(); - $order->setStatus("invalid_value"); - } - - // test deserialization of order - public function testDeserializationOfOrder() - { - $order_json = <<assertInstanceOf('OpenAPI\Client\Model\Order', $order); - $this->assertSame(10, $order->getId()); - $this->assertSame(20, $order->getPetId()); - $this->assertSame(30, $order->getQuantity()); - $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $order->getShipDate()); - $this->assertSame("placed", $order->getStatus()); - $this->assertSame(false, $order->getComplete()); - } - - // test deserialization of array of array of order - public function testDeserializationOfArrayOfArrayOfOrder() - { - $order_json = <<assertArrayHasKey(0, $order); - $this->assertArrayHasKey(0, $order[0]); - $_order = $order[0][0]; - $this->assertInstanceOf('OpenAPI\Client\Model\Order', $_order); - $this->assertSame(10, $_order->getId()); - $this->assertSame(20, $_order->getPetId()); - $this->assertSame(30, $_order->getQuantity()); - $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); - $this->assertSame("placed", $_order->getStatus()); - $this->assertSame(false, $_order->getComplete()); - } - - // test deserialization of map of map of order - public function testDeserializationOfMapOfMapOfOrder() - { - $order_json = <<assertArrayHasKey('test', $order); - $this->assertArrayHasKey('test2', $order['test']); - $_order = $order['test']['test2']; - $this->assertInstanceOf('OpenAPI\Client\Model\Order', $_order); - $this->assertSame(10, $_order->getId()); - $this->assertSame(20, $_order->getPetId()); - $this->assertSame(30, $_order->getQuantity()); - $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); - $this->assertSame("placed", $_order->getStatus()); - $this->assertSame(false, $_order->getComplete()); - - $order = ObjectSerializer::deserialize( - json_decode($order_json), - 'array>' - ); - - $this->assertArrayHasKey('test', $order); - $this->assertArrayHasKey('test2', $order['test']); - $_order = $order['test']['test2']; - $this->assertInstanceOf('OpenAPI\Client\Model\Order', $_order); - $this->assertSame(10, $_order->getId()); - $this->assertSame(20, $_order->getPetId()); - $this->assertSame(30, $_order->getQuantity()); - $this->assertTrue(new \DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); - $this->assertSame("placed", $_order->getStatus()); - $this->assertSame(false, $_order->getComplete()); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/OuterEnumTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/OuterEnumTest.php deleted file mode 100644 index 00777968f9ba..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/OuterEnumTest.php +++ /dev/null @@ -1,95 +0,0 @@ -assertIsString($result); - $this->assertEquals('placed', $result); - } - - public function testDeserializeInvalidValue() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid value for enum'); - ObjectSerializer::deserialize( - "lkjfalgkdfjg", - OuterEnum::class - ); - } - - public function testDeserializeNested() - { - $json = '{ - "enum_string": "UPPER", - "enum_integer": -1, - "enum_number": -1.2, - "outerEnum": "approved" - }'; - - /** * @var EnumTest $result */ - $result = ObjectSerializer::deserialize( - json_decode($json), - EnumTest::class - ); - - $this->assertInstanceOf(EnumTest::class, $result); - $this->assertEquals('approved', $result->getOuterEnum()); - } - - public function testSanitize() - { - $json = "placed"; - - $result = ObjectSerializer::sanitizeForSerialization( - $json - ); - - $this->assertIsString($result); - } - - public function testSanitizeNested() - { - $input = new EnumTest([ - 'enum_string' => 'UPPER', - 'enum_integer' => -1, - 'enum_number' => -1.2, - 'outer_enum' => 'approved' - ]); - - $result = ObjectSerializer::sanitizeForSerialization( - $input - ); - - $this->assertIsObject($result); - $this->assertInstanceOf(\stdClass::class, $result); - - $this->assertIsString($result->outerEnum); - $this->assertEquals('approved', $result->outerEnum); - } - - public function testSanitizeNestedInvalidValue() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid value for enum'); - $input = new EnumTest([ - 'enum_string' => 'UPPER', - 'enum_integer' => -1, - 'enum_number' => -1.2, - 'outer_enum' => 'invalid_value' - ]); - - ObjectSerializer::sanitizeForSerialization($input); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ParametersTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ParametersTest.php deleted file mode 100644 index 9bda987f53d0..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ParametersTest.php +++ /dev/null @@ -1,87 +0,0 @@ -fakeHttpClient = new FakeHttpClient(); - $this->fakeApi = new Api\FakeApi($this->fakeHttpClient); - $this->userApi = new Api\UserApi($this->fakeHttpClient); - } - - public function testHeaderParam() - { - $this->fakeApi->testEnumParameters([], 'something'); - - $request = $this->fakeHttpClient->getLastRequest(); - $headers = $request->getHeaders(); - - $this->assertArrayHasKey('enum_header_string', $headers); - $this->assertEquals(['something'], $headers['enum_header_string']); - } - - public function testHeaderParamCollection() - { - $this->fakeApi->testEnumParameters(['string1', 'string2']); - - $request = $this->fakeHttpClient->getLastRequest(); - $headers = $request->getHeaders(); - - $this->assertArrayHasKey('enum_header_string_array', $headers); - $this->assertEquals(['string1,string2'], $headers['enum_header_string_array']); - } - - public function testInlineAdditionalProperties() - { - $param = new \stdClass(); - $param->foo = 'bar'; - $this->fakeApi->testInlineAdditionalProperties(array($param)); - - $request = $this->fakeHttpClient->getLastRequest(); - $this->assertSame('[{"foo":"bar"}]', $request->getBody()->getContents()); - } - - /** - * @see https://github.com/OpenAPITools/openapi-generator/pull/11225 - * @dataProvider provideQueryParameters - */ - public function testQueryParameterCollectionFormatRequest($pipe, $ioutil, $http, $url, $context, $allow_empty, $language, $expected) - { - $request = $this->fakeApi->testQueryParameterCollectionFormatRequest($pipe, $ioutil, $http, $url, $context, $allow_empty, $language); - $this->assertEquals($expected, urldecode($request->getUri()->getQuery())); - } - - public function provideQueryParameters() - { - $array = ['blue', 'black', 'brown']; - $object = ['R' => 100, 'G' => 200, 'B' => 150]; - return [ - [ - $array, $array, $array, $array, $array, 'blue', $object, 'pipe=blue|black|brown&ioutil=blue,black,brown&http=blue black brown&url=blue,black,brown&context=blue&context=black&context=brown&R=100&G=200&B=150&allowEmpty=blue', - ], - ]; - } - -// missing example for collection path param in config -// public function testPathParamCollection() -// { -// $this->userApi->getUserByNameWithHttpInfo(['aa', 'bb']); -// $request = $this->fakeHttpClient->getLastRequest(); -// $this->assertEquals('user/aa,bb', urldecode($request->getUri()->getPath())); -// } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/PetApiTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/PetApiTest.php deleted file mode 100644 index 758dfda0d115..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/PetApiTest.php +++ /dev/null @@ -1,387 +0,0 @@ -setId($newPetId); - $newPet->setName("PHP Unit Test"); - $newPet->setPhotoUrls(["http://test_php_unit_test.com"]); - // new tag - $tag = new Model\Tag; - $tag->setId($newPetId); // use the same id as pet - $tag->setName("test php tag"); - // new category - $category = new Model\Category; - $category->setId($newPetId); // use the same id as pet - $category->setName("test php category"); - - $newPet->setTags(array($tag)); - $newPet->setCategory($category); - - $config = new Configuration(); - $petApi = new Api\PetApi(null, $config); - - // add a new pet (model) - list(, $status) = $petApi->addPetWithHttpInfo($newPet); - Assert::assertEquals(200, $status); - } - - public function setUp(): void - { - $this->api = new Api\PetApi(); - } - - public function testGetPetById() - { - $petId = 10005; - - $pet = $this->api->getPetById($petId); - $this->assertSame($petId, $pet->getId()); - $this->assertSame('PHP Unit Test', $pet->getName()); - $this->assertSame('http://test_php_unit_test.com', $pet->getPhotoUrls()[0]); - $this->assertSame($petId, $pet->getCategory()->getId()); - $this->assertSame('test php category', $pet->getCategory()->getName()); - $this->assertSame($petId, $pet->getTags()[0]->getId()); - $this->assertSame('test php tag', $pet->getTags()[0]->getName()); - } - - /** - * comment out as we've removed invalid endpoints from the spec, we'll introduce something - * similar in the future when we've time to update the petstore server - * - * // test getPetById with a Pet object (id 10005) - * public function testGetPetByIdInObject() - * { - * // initialize the API client without host - * $pet_id = 10005; // ID of pet that needs to be fetched - * $pet_api = new Api\PetApi(); - * $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - * // return Pet (inline model) - * $response = $pet_api->getPetByIdInObject($pet_id); - * $this->assertInstanceOf('OpenAPI\Client\Model\InlineResponse200', $response); - * $this->assertSame($response->getId(), $pet_id); - * $this->assertSame($response->getName(), 'PHP Unit Test'); - * $this->assertSame($response->getPhotoUrls()[0], 'http://test_php_unit_test.com'); - * - * // category is type "object" - * $this->assertInternalType('array', $response->getCategory()); - * $this->assertSame($response->getCategory()['id'], $pet_id); - * $this->assertSame($response->getCategory()['name'], 'test php category'); - * - * $this->assertSame($response->getTags()[0]->getId(), $pet_id); - * $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); - * } - */ - - // test getPetByIdWithHttpInfo with a Pet object (id 10005) - public function testGetPetByIdWithHttpInfo() - { - // initialize the API client without host - $petId = 10005; // ID of pet that needs to be fetched - - /** @var $pet Pet */ - list($pet, $status_code, $response_headers) = $this->api->getPetByIdWithHttpInfo($petId); - $this->assertSame($petId, $pet->getId()); - $this->assertSame('PHP Unit Test', $pet->getName()); - $this->assertSame($petId, $pet->getCategory()->getId()); - $this->assertSame('test php category', $pet->getCategory()->getName()); - $this->assertSame($petId, $pet->getTags()[0]->getId()); - $this->assertSame('test php tag', $pet->getTags()[0]->getName()); - $this->assertSame(200, $status_code); - $this->assertSame(['application/json'], $response_headers['Content-Type']); - } - - public function testFindPetByStatus() - { - $response = $this->api->findPetsByStatus(array('available')); - $this->assertGreaterThan(0, count($response)); // at least one object returned - - $this->assertInstanceOf(Pet::class, $response[0]); // verify the object is Pet - foreach ($response as $pet) { - $this->assertSame('available', $pet->getStatus()); - } - - $response = $this->api->findPetsByStatus(array('unknown_and_incorrect_status')); - $this->assertCount(0, $response); - } - - public function testUpdatePet() - { - $petId = 10001; - $updatedPet = new Model\Pet; - $updatedPet->setId($petId); - $updatedPet->setName('updatePet'); - $updatedPet->setStatus('pending'); - $updatedPet->setPhotoUrls(array('http://a.com')); - $result = $this->api->updatePet($updatedPet); - $this->assertNull($result); - - // verify updated Pet - $result = $this->api->getPetById($petId); - $this->assertSame($petId, $result->getId()); - $this->assertSame('pending', $result->getStatus()); - $this->assertSame('updatePet', $result->getName()); - } - - // test updatePetWithFormWithHttpInfo and verify by the "name" of the response - public function testUpdatePetWithFormWithHttpInfo() - { - $petId = 10001; // ID of pet that needs to be fetched - - // update Pet (form) - list($update_response, $status_code, $http_headers) = $this->api->updatePetWithFormWithHttpInfo( - $petId, - 'update pet with form with http info' - ); - // return nothing (void) - $this->assertNull($update_response); - $this->assertSame(200, $status_code); - $this->assertSame(['application/json'], $http_headers['Content-Type']); - $response = $this->api->getPetById($petId); - $this->assertSame($petId, $response->getId()); - $this->assertSame('update pet with form with http info', $response->getName()); - } - - // test updatePetWithForm and verify by the "name" and "status" of the response - public function testUpdatePetWithForm() - { - $pet_id = 10001; // ID of pet that needs to be fetched - $result = $this->api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); - // return nothing (void) - $this->assertNull($result); - - $response = $this->api->getPetById($pet_id); - $this->assertSame($pet_id, $response->getId()); - $this->assertSame('update pet with form', $response->getName()); - $this->assertSame('sold', $response->getStatus()); - } - - // test addPet and verify by the "id" and "name" of the response - public function testAddPet() - { - $new_pet_id = 10005; - $newPet = new Model\Pet; - $newPet->setId($new_pet_id); - $newPet->setName("PHP Unit Test 2"); - $newPet->setPhotoUrls(array("http://a.com")); - - // add a new pet (model) - $add_response = $this->api->addPet($newPet); - // return nothing (void) - $this->assertNull($add_response); - - // verify added Pet - $response = $this->api->getPetById($new_pet_id); - $this->assertSame($new_pet_id, $response->getId()); - $this->assertSame('PHP Unit Test 2', $response->getName()); - $this->assertSame(array("http://a.com"), $response->getPhotoUrls()); - } - - /* - * comment out as we've removed invalid endpoints from the spec, we'll introduce something - * similar in the future when we've time to update the petstore server - * - // test addPetUsingByteArray and verify by the "id" and "name" of the response - public function testAddPetUsingByteArray() - { - // initialize the API client - $config = (new Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new ApiClient($config); - - $new_pet_id = 10005; - $new_pet = new Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test 3"); - // new tag - $tag= new Model\Tag; - $tag->setId($new_pet_id); // use the same id as pet - $tag->setName("test php tag"); - // new category - $category = new Model\Category; - $category->setId($new_pet_id); // use the same id as pet - $category->setName("test php category"); - - $new_pet->setTags(array($tag)); - $new_pet->setCategory($category); - - $pet_api = new Api\PetApi($api_client); - // add a new pet (model) - $object_serializer = new ObjectSerializer(); - $pet_json_string = json_encode($object_serializer->sanitizeForSerialization($new_pet)); - $add_response = $pet_api->addPetUsingByteArray($pet_json_string); - // return nothing (void) - $this->assertSame($add_response, NULL); - // verify added Pet - $response = $pet_api->getPetById($new_pet_id); - $this->assertSame($response->getId(), $new_pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test 3'); - } - */ - - // test upload file - public function testUploadFile() - { - // upload file - $pet_id = 10001; - $response = $this->api->uploadFile($pet_id, 'test meta', __DIR__ . '/../composer.json'); - // return ApiResponse - $this->assertInstanceOf(ApiResponse::class, $response); - } - - /* - * comment out as we've removed invalid endpoints from the spec, we'll introduce something - * similar in the future when we've time to update the petstore server - * - // test byte array response - public function testGetPetByIdWithByteArray() - { - // initialize the API client - $config = new Configuration(); - $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new APIClient($config); - $pet_api = new Api\PetApi($api_client); - // test getPetByIdWithByteArray - $pet_id = 10005; - $bytes = $pet_api->petPetIdtestingByteArraytrueGet($pet_id); - $json = json_decode($bytes, true); - - $this->assertInternalType("string", $bytes); - - $this->assertSame($json['id'], $pet_id); - // not testing name as it's tested by addPetUsingByteArray - //$this->assertSame($json['name'], 'PHP Unit Test'); - $this->assertSame($json['category']['id'], $pet_id); - $this->assertSame($json['category']['name'], 'test php category'); - $this->assertSame($json['tags'][0]['id'], $pet_id); - $this->assertSame($json['tags'][0]['name'], 'test php tag'); - } - */ - - // test inheritance in the model - public function testInheritance() - { - $new_dog = new Model\Dog; - // the object should be an instance of the derived class - $this->assertInstanceOf('OpenAPI\Client\Model\Dog', $new_dog); - // the object should also be an instance of the parent class - $this->assertInstanceOf('OpenAPI\Client\Model\Animal', $new_dog); - } - - // test inheritance constructor is working with data - // initialization - public function testInheritanceConstructorDataInitialization() - { - // initialize the object with data in the constructor - $data = array( - 'class_name' => 'Dog', - 'breed' => 'Great Dane' - ); - $new_dog = new Model\Dog($data); - - // the property on the derived class should be set - $this->assertSame('Great Dane', $new_dog->getBreed()); - // the property on the parent class should be set - $this->assertSame('Dog', $new_dog->getClassName()); - } - - // test if discriminator is initialized automatically - public function testDiscriminatorInitialization() - { - $new_dog = new Model\Dog(); - $this->assertSame('Dog', $new_dog->getClassName()); - } - - // test if ArrayAccess interface works - public function testArrayStuff() - { - // create an array of Animal - $farm = array(); - - // add some animals to the farm to make sure the ArrayAccess - // interface works - $farm[] = new Model\Dog(); - $farm[] = new Model\Cat(); - $farm[] = new Model\Animal(); - - // assert we can look up the animals in the farm by array - // indices (let's try a random order) - $this->assertInstanceOf('OpenAPI\Client\Model\Cat', $farm[1]); - $this->assertInstanceOf('OpenAPI\Client\Model\Dog', $farm[0]); - $this->assertInstanceOf('OpenAPI\Client\Model\Animal', $farm[2]); - - // let's try to `foreach` the animals in the farm and let's - // try to use the objects we loop through - foreach ($farm as $animal) { - $this->assertContains($animal->getClassName(), array('Dog', 'Cat', 'Animal')); - $this->assertInstanceOf('OpenAPI\Client\Model\Animal', $animal); - } - } - - // test if default values works - public function testDefaultValues() - { - // add some animals to the farm to make sure the ArrayAccess - // interface works - $dog = new Model\Dog(); - $animal = new Model\Animal(); - - // assert we can look up the animals in the farm by array - // indices (let's try a random order) - $this->assertSame('red', $dog->getColor()); - $this->assertSame('red', $animal->getColor()); - } - - /** - * test invalid argument - */ - public function testInvalidArgument() - { - // the argument is required, and we must specify one or some from 'available', 'pending', 'sold' - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Missing the required parameter $status when calling findPetsByStatus'); - $this->api->findPetsByStatus([]); - } - -// Disabled as currently we don't have any endpoint that would return file -// For testing I just replaced url and return type in Api method. -// public function testDownloadingLargeFile() -// { -// $petId = 10005; -// $config = new Configuration(); -// $config->setHost('https://getcomposer.org'); -// $api = new PetApi(new Client(), $config); -// $result = $api->getPetById($petId); -// $this->assertInstanceOf(\SplFileObject::class, $result); -// var_dump([ -// 'peak mem (MiB)' => memory_get_peak_usage(true)/1024/1024, -// 'file size (MiB)' => $result->getSize()/1024/1024, -// 'path' => sys_get_temp_dir() . '/' . $result->getFilename() -// ]); -// } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/RequestTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/RequestTest.php deleted file mode 100644 index 834e27588a7c..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/RequestTest.php +++ /dev/null @@ -1,36 +0,0 @@ -fakeClient = new FakeHttpClient(); - $this->api = new Api\FakeApi($this->fakeClient); - } - - public function testFormDataEncodingToJson() - { - $this->api->testJsonFormData('value', 'value2'); - - $request = $this->fakeClient->getLastRequest(); - $contentType = $request->getHeader('Content-Type'); - $this->assertEquals(['application/x-www-form-urlencoded'], $contentType); - - $requestContent = $request->getBody()->getContents(); - - // JSON serialization of form data is not supported - $this->assertEquals('param=value¶m2=value2', $requestContent); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ResponseTypesTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ResponseTypesTest.php deleted file mode 100644 index 8d65396ccbc4..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ResponseTypesTest.php +++ /dev/null @@ -1,92 +0,0 @@ -fakeHttpClient = new FakeHttpClient(); - $this->api = new PetApi($this->fakeHttpClient); - } - - public function testDefined200ReturnType() - { - $this->fakeHttpClient->setResponse(new Response(200, [], json_encode([]))); - $result = $this->api->getPetById(123); - - $this->assertInstanceOf(Pet::class, $result); - } - - public function testDefault2xxReturnType() - { - $this->fakeHttpClient->setResponse(new Response(255, [], json_encode([]))); - $result = $this->api->getPetById(123); - - $this->assertInstanceOf(Pet::class, $result); - } - - public function testDefinedErrorException() - { - $this->expectExceptionCode(400); - $this->expectException(\OpenAPI\Client\ApiException::class); - $statusCode = 400; - - $this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}')); - $this->api->getPetById(123); - } - -// missing case in spec: -// responses: -// '400': -// description: failure -// schema: -// $ref: '#/definitions/Error' -// public function testDefinedErrorResponseObject() -// { -// $result = null; -// try { -// $this->fakeHttpClient->setResponse(new Response(400, [], '{}')); -// $this->api->getPetById(123); -// } catch (ApiException $e) { -// $result = $e->getResponseObject(); -// } -// -// $this->assertInstanceOf(Error::class, $result); -// } - - public function testDefaultErrorException() - { - $this->expectExceptionCode(404); - $this->expectException(\OpenAPI\Client\ApiException::class); - $statusCode = 404; - - $this->fakeHttpClient->setResponse(new Response($statusCode, [], '{}')); - $this->api->getPetById(123); - } - - public function testDefaultErrorResponseObject() - { - $result = null; - try { - $this->fakeHttpClient->setResponse(new Response(404, [], '{}')); - $this->api->getPetById(123); - } catch (ApiException $e) { - $result = $e->getResponseObject(); - } - - $this->assertNull($result); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ServerVariablesInOperationTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ServerVariablesInOperationTest.php deleted file mode 100644 index 385b895f0dc3..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/ServerVariablesInOperationTest.php +++ /dev/null @@ -1,60 +0,0 @@ -fakeHttpClient = new FakeHttpClient(); - $this->api = new Api\PetApi($this->fakeHttpClient); - $this->pet = new Model\Pet(); - $this->pet->setName("something"); - $this->pet->setPhotoUrls(array("https://a.com")); - } - - public function testServerVariablesInOperation(): void - { - # Test default values (if no variables are set) - $this->api->addPet($this->pet, 2); - $request = $this->fakeHttpClient->getLastRequest(); - - $this->assertEquals('petstore.swagger.io', $request->getUri()->getHost(), 'Server variable set to default value.'); - - # Test variables substitution - $this->api->addPet($this->pet, 2, [ 'server' => 'qa-petstore', 'port' => '8080']); - $request = $this->fakeHttpClient->getLastRequest(); - - $this->assertEquals('qa-petstore.swagger.io', $request->getUri()->getHost(), 'Server set to "qa-petstore"'); - $this->assertEquals(8080, $request->getUri()->getPort(), 'Port set to 8080'); - } - - public function testLegacyServerChoiceInOperation(): void - { - # Test legacy behavior (set server using api->setHostIndex() - $this->api->setHostIndex(1); - $this->api->addPet($this->pet); - $request = $this->fakeHttpClient->getLastRequest(); - - $this->assertEquals('path-server-test.petstore.local', $request->getUri()->getHost(), 'Server set using legacy behavior'); - } - - public function testInvalidVariableValueInOperation(): void - { - $this->expectException(InvalidArgumentException::class); - $this->api->addPet($this->pet, 2,['server' => 'invalid-value']); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/StoreApiTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/StoreApiTest.php deleted file mode 100644 index 51d64b8a93a3..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/StoreApiTest.php +++ /dev/null @@ -1,58 +0,0 @@ -api = new StoreApi(); - } - - /** - * Setup before running each test case - */ - public static function setUpBeforeClass(): void - { - // add a new pet (id 10005) to ensure the pet object is available for all the tests - // new pet - $id = 10005; - $pet = new Pet(); - $pet->setId($id); - $pet->setName('PHP Unit Test'); - $pet->setPhotoUrls(array('http://a.com')); - $pet->setStatus('available'); - // new tag - $tag = new Tag(); - $tag->setId($id); // use the same id as pet - $tag->setName('test php tag'); - // new category - $category = new Category(); - $category->setId($id); // use the same id as pet - $category->setName('test php category'); - - $pet->setTags([$tag]); - $pet->setCategory($category); - - $api = new PetApi(); - $api->addPet($pet); - } - - public function testGetInventory() - { - $result = $this->api->getInventory(); - - $this->assertIsArray($result); - $this->assertIsInt($result['available']); - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/UserApiTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/UserApiTest.php deleted file mode 100644 index 929789670f91..000000000000 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/test/UserApiTest.php +++ /dev/null @@ -1,37 +0,0 @@ -api = new Api\UserApi(); - } - - // test login use - public function testLoginUser() - { - // initialize the API client - // login - $response = $this->api->loginUser('xxxxx', 'yyyyyyyy'); - - $this->assertIsString($response); - - $pattern = '/logged in user session/'; - $assertMessage = "response string starts with 'logged in user session'"; - $this->assertIsString($response); - if (method_exists($this, 'assertMatchesRegularExpression')) { - $this->assertMatchesRegularExpression($pattern, $response, $assertMessage); - } else { - $this->assertRegExp($pattern, $response, $assertMessage); - } - } -} diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/tests/Api/AnotherFakeApiTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/tests/Api/AnotherFakeApiTest.php index 28b50fbc881a..d41d0bfbea86 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/tests/Api/AnotherFakeApiTest.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/tests/Api/AnotherFakeApiTest.php @@ -1,9 +1,8 @@ assertSame(EnumTest::ENUM_STRING_UPPER, "UPPER"); $this->assertSame(EnumTest::ENUM_STRING_LOWER, "lower"); - $this->assertSame(EnumTest::ENUM_INTEGER_1, 1); + $this->assertSame(EnumTest::ENUM_STRING_EMPTY, ""); + $this->assertSame(EnumTest::ENUM_STRING_REQUIRED_UPPER, "UPPER"); + $this->assertSame(EnumTest::ENUM_STRING_REQUIRED_LOWER, "lower"); + $this->assertSame(EnumTest::ENUM_STRING_REQUIRED_EMPTY, ""); + $this->assertSame(EnumTest::ENUM_INTEGER_NUMBER_1, 1); $this->assertSame(EnumTest::ENUM_INTEGER_MINUS_1, -1); - $this->assertSame(EnumTest::ENUM_NUMBER_1_DOT_1, 1.1); + $this->assertSame(EnumTest::ENUM_NUMBER_NUMBER_1_DOT_1, 1.1); $this->assertSame(EnumTest::ENUM_NUMBER_MINUS_1_DOT_2, -1.2); } diff --git a/samples/client/petstore/php/psr-18/.openapi-generator/FILES b/samples/client/petstore/php/psr-18/.openapi-generator/FILES index 34aee01b39f6..26dfe36c4c49 100644 --- a/samples/client/petstore/php/psr-18/.openapi-generator/FILES +++ b/samples/client/petstore/php/psr-18/.openapi-generator/FILES @@ -27,6 +27,7 @@ docs/Model/Dog.md docs/Model/EnumArrays.md docs/Model/EnumClass.md docs/Model/EnumTest.md +docs/Model/EnumWithNameAndDescription.md docs/Model/FakeBigDecimalMap200Response.md docs/Model/File.md docs/Model/FileSchemaTestClass.md @@ -88,6 +89,7 @@ lib/Model/Dog.php lib/Model/EnumArrays.php lib/Model/EnumClass.php lib/Model/EnumTest.php +lib/Model/EnumWithNameAndDescription.php lib/Model/FakeBigDecimalMap200Response.php lib/Model/File.php lib/Model/FileSchemaTestClass.php diff --git a/samples/client/petstore/php/psr-18/README.md b/samples/client/petstore/php/psr-18/README.md index e06bbb21aef1..001ba90f9477 100644 --- a/samples/client/petstore/php/psr-18/README.md +++ b/samples/client/petstore/php/psr-18/README.md @@ -149,6 +149,7 @@ Class | Method | HTTP request | Description - [EnumArrays](docs/Model/EnumArrays.md) - [EnumClass](docs/Model/EnumClass.md) - [EnumTest](docs/Model/EnumTest.md) +- [EnumWithNameAndDescription](docs/Model/EnumWithNameAndDescription.md) - [FakeBigDecimalMap200Response](docs/Model/FakeBigDecimalMap200Response.md) - [File](docs/Model/File.md) - [FileSchemaTestClass](docs/Model/FileSchemaTestClass.md) diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/InlineResponseDefault.md b/samples/client/petstore/php/psr-18/docs/Model/EnumWithNameAndDescription.md similarity index 71% rename from samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/InlineResponseDefault.md rename to samples/client/petstore/php/psr-18/docs/Model/EnumWithNameAndDescription.md index 57ae8e09d5ce..ab03446144aa 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Model/InlineResponseDefault.md +++ b/samples/client/petstore/php/psr-18/docs/Model/EnumWithNameAndDescription.md @@ -1,9 +1,8 @@ -# # InlineResponseDefault +# # EnumWithNameAndDescription ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**string** | [**\OpenAPI\Client\Model\Foo**](Foo.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/psr-18/lib/Model/EnumTest.php b/samples/client/petstore/php/psr-18/lib/Model/EnumTest.php index 89b7352ad5fb..83ff467736d6 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/psr-18/lib/Model/EnumTest.php @@ -276,9 +276,9 @@ public function getModelName() public const ENUM_STRING_REQUIRED_UPPER = 'UPPER'; public const ENUM_STRING_REQUIRED_LOWER = 'lower'; public const ENUM_STRING_REQUIRED_EMPTY = ''; - public const ENUM_INTEGER_1 = 1; + public const ENUM_INTEGER_NUMBER_1 = 1; public const ENUM_INTEGER_MINUS_1 = -1; - public const ENUM_NUMBER_1_DOT_1 = 1.1; + public const ENUM_NUMBER_NUMBER_1_DOT_1 = 1.1; public const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; /** @@ -317,7 +317,7 @@ public function getEnumStringRequiredAllowableValues() public function getEnumIntegerAllowableValues() { return [ - self::ENUM_INTEGER_1, + self::ENUM_INTEGER_NUMBER_1, self::ENUM_INTEGER_MINUS_1, ]; } @@ -330,7 +330,7 @@ public function getEnumIntegerAllowableValues() public function getEnumNumberAllowableValues() { return [ - self::ENUM_NUMBER_1_DOT_1, + self::ENUM_NUMBER_NUMBER_1_DOT_1, self::ENUM_NUMBER_MINUS_1_DOT_2, ]; } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php b/samples/client/petstore/php/psr-18/lib/Model/EnumWithNameAndDescription.php similarity index 66% rename from samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php rename to samples/client/petstore/php/psr-18/lib/Model/EnumWithNameAndDescription.php index ddb66f7515e0..570fe338101a 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php +++ b/samples/client/petstore/php/psr-18/lib/Model/EnumWithNameAndDescription.php @@ -1,8 +1,8 @@ $'); .toSet() as ReturnType; } if (value is Map && (match = _regMap.firstMatch(targetType)) != null) { - targetType = match![1]!; // ignore: parameter_assignments - return Map.fromIterables( - value.keys, + targetType = match![1]!.trim(); // ignore: parameter_assignments + return Map.fromIterables( + value.keys as Iterable, value.values.map((dynamic v) => deserialize(v, targetType, growable: growable)), ) as ReturnType; } break; - } + } throw Exception('Cannot deserialize'); } \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart index 7cedba75141f..8a187d3dc3c0 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/additional_properties_class.dart @@ -27,7 +27,7 @@ class AdditionalPropertiesClass { name: r'map_property', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class AdditionalPropertiesClass { name: r'map_of_map_property', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart index 2b799c619dc2..c196447ea5e4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/all_of_with_single_ref.dart @@ -28,7 +28,7 @@ class AllOfWithSingleRef { name: r'username', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -40,7 +40,8 @@ class AllOfWithSingleRef { name: r'SingleRefType', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: SingleRefType.unknownDefaultOpenApi, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart index 19c22c9351e7..732326357226 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/animal.dart @@ -27,7 +27,7 @@ class Animal { name: r'className', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class Animal { defaultValue: 'red', name: r'color', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart index 22cdcaff69ba..207cea16eabe 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/api_response.dart @@ -29,7 +29,7 @@ class ApiResponse { name: r'code', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -41,7 +41,7 @@ class ApiResponse { name: r'type', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -53,7 +53,7 @@ class ApiResponse { name: r'message', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart index 79f8bf64fee0..da8de0169296 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_array_of_number_only.dart @@ -25,7 +25,7 @@ class ArrayOfArrayOfNumberOnly { name: r'ArrayArrayNumber', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart index d4ecbeff86f2..4ead761e76f7 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_of_number_only.dart @@ -25,7 +25,7 @@ class ArrayOfNumberOnly { name: r'ArrayNumber', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart index c6f7c38ac76b..0968d4b12986 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/array_test.dart @@ -30,7 +30,7 @@ class ArrayTest { name: r'array_of_string', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -42,7 +42,7 @@ class ArrayTest { name: r'array_array_of_integer', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -54,7 +54,7 @@ class ArrayTest { name: r'array_array_of_model', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart index 2c996e5c71bf..d2bc40f33836 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/capitalization.dart @@ -35,7 +35,7 @@ class Capitalization { name: r'smallCamel', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -47,7 +47,7 @@ class Capitalization { name: r'CapitalCamel', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -59,7 +59,7 @@ class Capitalization { name: r'small_Snake', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -71,7 +71,7 @@ class Capitalization { name: r'Capital_Snake', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -83,7 +83,7 @@ class Capitalization { name: r'SCA_ETH_Flow_Points', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -96,7 +96,7 @@ class Capitalization { name: r'ATT_NAME', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart index b468550dce5a..e2df6f2cc557 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/cat.dart @@ -32,7 +32,7 @@ class Cat { name: r'className', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -44,7 +44,7 @@ class Cat { defaultValue: 'red', name: r'color', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -56,7 +56,7 @@ class Cat { name: r'declawed', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart index ffa8d07de9d5..6d078b06ae20 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/category.dart @@ -27,7 +27,7 @@ class Category { name: r'id', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class Category { defaultValue: 'default-name', name: r'name', required: true, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/child_with_nullable.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/child_with_nullable.dart index 22b9df5c55a4..dcda6f93ba6a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/child_with_nullable.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/child_with_nullable.dart @@ -32,7 +32,8 @@ class ChildWithNullable { name: r'type', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: ChildWithNullableTypeEnum.unknownDefaultOpenApi, ) @@ -44,7 +45,7 @@ class ChildWithNullable { name: r'nullableProperty', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -56,7 +57,7 @@ class ChildWithNullable { name: r'otherProperty', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -91,10 +92,17 @@ class ChildWithNullable { enum ChildWithNullableTypeEnum { - @JsonValue(r'ChildWithNullable') - childWithNullable, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, +@JsonValue(r'ChildWithNullable') +childWithNullable(r'ChildWithNullable'), +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const ChildWithNullableTypeEnum(this.value); + +final String value; + +@override +String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart index 28a10ad25734..40b6b45ac3c4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/class_model.dart @@ -25,7 +25,7 @@ class ClassModel { name: r'_class', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart index 7598e9464681..68d1df4016c1 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/deprecated_object.dart @@ -26,7 +26,7 @@ class DeprecatedObject { name: r'name', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart index 8a5b55baf106..deb271b6dc3b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/dog.dart @@ -32,7 +32,7 @@ class Dog { name: r'className', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -44,7 +44,7 @@ class Dog { defaultValue: 'red', name: r'color', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -56,7 +56,7 @@ class Dog { name: r'breed', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart index 46959e7ccd72..632fd933d6e8 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_arrays.dart @@ -27,7 +27,8 @@ class EnumArrays { name: r'just_symbol', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: EnumArraysJustSymbolEnum.unknownDefaultOpenApi, ) @@ -39,7 +40,8 @@ class EnumArrays { name: r'array_enum', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: List.unknownDefaultOpenApi, ) @@ -72,23 +74,37 @@ class EnumArrays { enum EnumArraysJustSymbolEnum { - @JsonValue(r'>=') - greaterThanEqual, - @JsonValue(r'$') - dollar, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, +@JsonValue(r'>=') +greaterThanEqual(r'>='), +@JsonValue(r'$') +dollar(r'$'), +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const EnumArraysJustSymbolEnum(this.value); + +final String value; + +@override +String toString() => value; } enum EnumArraysArrayEnumEnum { - @JsonValue(r'fish') - fish, - @JsonValue(r'crab') - crab, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, +@JsonValue(r'fish') +fish(r'fish'), +@JsonValue(r'crab') +crab(r'crab'), +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const EnumArraysArrayEnumEnum(this.value); + +final String value; + +@override +String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart index 687e674d211a..563f7038b97f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/enum_test.dart @@ -43,7 +43,8 @@ class EnumTest { name: r'enum_string', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: EnumTestEnumStringEnum.unknownDefaultOpenApi, ) @@ -55,7 +56,8 @@ class EnumTest { name: r'enum_string_required', required: true, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: EnumTestEnumStringRequiredEnum.unknownDefaultOpenApi, ) @@ -67,7 +69,8 @@ class EnumTest { name: r'enum_integer', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: EnumTestEnumIntegerEnum.unknownDefaultOpenApi, ) @@ -79,7 +82,8 @@ class EnumTest { name: r'enum_number', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: EnumTestEnumNumberEnum.unknownDefaultOpenApi, ) @@ -91,7 +95,8 @@ class EnumTest { name: r'outerEnum', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: OuterEnum.unknownDefaultOpenApi, ) @@ -103,7 +108,8 @@ class EnumTest { name: r'outerEnumInteger', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: OuterEnumInteger.unknownDefaultOpenApi, ) @@ -115,7 +121,8 @@ class EnumTest { name: r'outerEnumDefaultValue', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: OuterEnumDefaultValue.unknownDefaultOpenApi, ) @@ -127,7 +134,8 @@ class EnumTest { name: r'outerEnumIntegerDefaultValue', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: OuterEnumIntegerDefaultValue.unknownDefaultOpenApi, ) @@ -172,49 +180,77 @@ class EnumTest { enum EnumTestEnumStringEnum { - @JsonValue(r'UPPER') - UPPER, - @JsonValue(r'lower') - lower, - @JsonValue(r'') - empty, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, +@JsonValue(r'UPPER') +UPPER(r'UPPER'), +@JsonValue(r'lower') +lower(r'lower'), +@JsonValue(r'') +empty(r''), +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const EnumTestEnumStringEnum(this.value); + +final String value; + +@override +String toString() => value; } enum EnumTestEnumStringRequiredEnum { - @JsonValue(r'UPPER') - UPPER, - @JsonValue(r'lower') - lower, - @JsonValue(r'') - empty, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, +@JsonValue(r'UPPER') +UPPER(r'UPPER'), +@JsonValue(r'lower') +lower(r'lower'), +@JsonValue(r'') +empty(r''), +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const EnumTestEnumStringRequiredEnum(this.value); + +final String value; + +@override +String toString() => value; } enum EnumTestEnumIntegerEnum { - @JsonValue(1) - number1, - @JsonValue(-1) - numberNegative1, - @JsonValue(11184809) - unknownDefaultOpenApi, +@JsonValue(1) +number1('1'), +@JsonValue(-1) +numberNegative1('-1'), +@JsonValue(11184809) +unknownDefaultOpenApi('11184809'); + +const EnumTestEnumIntegerEnum(this.value); + +final String value; + +@override +String toString() => value; } enum EnumTestEnumNumberEnum { - @JsonValue('1.1') - number1Period1, - @JsonValue('-1.2') - numberNegative1Period2, - @JsonValue('11184809') - unknownDefaultOpenApi, +@JsonValue('1.1') +number1Period1(''1.1''), +@JsonValue('-1.2') +numberNegative1Period2(''-1.2''), +@JsonValue('11184809') +unknownDefaultOpenApi(''11184809''); + +const EnumTestEnumNumberEnum(this.value); + +final String value; + +@override +String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/fake_big_decimal_map200_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/fake_big_decimal_map200_response.dart index d413eadb223e..1f0f2950a71c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/fake_big_decimal_map200_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/fake_big_decimal_map200_response.dart @@ -27,7 +27,7 @@ class FakeBigDecimalMap200Response { name: r'someId', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class FakeBigDecimalMap200Response { name: r'someMap', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart index 55195af35dbd..cde81139a620 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/file_schema_test_class.dart @@ -28,7 +28,7 @@ class FileSchemaTestClass { name: r'file', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -40,7 +40,7 @@ class FileSchemaTestClass { name: r'files', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart index b8d2d1f2da85..13d38bc30f0d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo.dart @@ -25,7 +25,7 @@ class Foo { defaultValue: 'bar', name: r'bar', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart index 1702a8fcebdd..e153e16cce1a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/foo_get_default_response.dart @@ -26,7 +26,7 @@ class FooGetDefaultResponse { name: r'string', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart index 65edad5d6461..a20ba417fa54 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/format_test.dart @@ -58,7 +58,7 @@ class FormatTest { name: r'integer', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -72,7 +72,7 @@ class FormatTest { name: r'int32', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -84,7 +84,7 @@ class FormatTest { name: r'int64', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -98,7 +98,7 @@ class FormatTest { name: r'number', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -112,7 +112,7 @@ class FormatTest { name: r'float', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -126,7 +126,7 @@ class FormatTest { name: r'double', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -138,7 +138,7 @@ class FormatTest { name: r'decimal', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -150,7 +150,7 @@ class FormatTest { name: r'string', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -162,7 +162,7 @@ class FormatTest { name: r'byte', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -181,7 +181,7 @@ class FormatTest { name: r'date', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -193,7 +193,7 @@ class FormatTest { name: r'dateTime', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -205,7 +205,7 @@ class FormatTest { name: r'uuid', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -217,7 +217,7 @@ class FormatTest { name: r'password', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -230,7 +230,7 @@ class FormatTest { name: r'pattern_with_digits', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -243,7 +243,7 @@ class FormatTest { name: r'pattern_with_digits_and_delimiter', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart index 1cf233f8c337..ef63a2980c30 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/has_only_read_only.dart @@ -27,7 +27,7 @@ class HasOnlyReadOnly { name: r'bar', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class HasOnlyReadOnly { name: r'foo', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart index a77a95c2e4c8..6fd362cdf351 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/health_check_result.dart @@ -25,7 +25,7 @@ class HealthCheckResult { name: r'NullableMessage', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart index beb4547b7702..59f9377d253a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/map_test.dart @@ -31,7 +31,7 @@ class MapTest { name: r'map_map_of_string', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -43,7 +43,8 @@ class MapTest { name: r'map_of_enum_string', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: Map.unknownDefaultOpenApi, ) @@ -55,7 +56,7 @@ class MapTest { name: r'direct_map', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -67,7 +68,7 @@ class MapTest { name: r'indirect_map', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -104,12 +105,19 @@ class MapTest { enum MapTestMapOfEnumStringEnum { - @JsonValue(r'UPPER') - UPPER, - @JsonValue(r'lower') - lower, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, +@JsonValue(r'UPPER') +UPPER(r'UPPER'), +@JsonValue(r'lower') +lower(r'lower'), +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const MapTestMapOfEnumStringEnum(this.value); + +final String value; + +@override +String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart index c7262a747b22..458d2bd0534b 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/mixed_properties_and_additional_properties_class.dart @@ -30,7 +30,7 @@ class MixedPropertiesAndAdditionalPropertiesClass { name: r'uuid', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -42,7 +42,7 @@ class MixedPropertiesAndAdditionalPropertiesClass { name: r'dateTime', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -54,7 +54,7 @@ class MixedPropertiesAndAdditionalPropertiesClass { name: r'map', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart index 4e84da142bd4..47609c700da2 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model200_response.dart @@ -27,7 +27,7 @@ class Model200Response { name: r'name', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class Model200Response { name: r'class', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart index 29e587b33ac3..8ff470611f22 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_client.dart @@ -25,7 +25,7 @@ class ModelClient { name: r'client', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart index 6fc79d9a0690..cccca0412f46 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_file.dart @@ -26,7 +26,7 @@ class ModelFile { name: r'sourceURI', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart index cc626409a89c..11421881ae57 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_list.dart @@ -25,7 +25,7 @@ class ModelList { name: r'123-list', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart index 5d414ad454d5..ea5427115232 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_return.dart @@ -25,7 +25,7 @@ class ModelReturn { name: r'return', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart index 172e70e7a9d3..3d16d98780b3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/name.dart @@ -31,7 +31,7 @@ class Name { name: r'name', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -43,7 +43,7 @@ class Name { name: r'snake_case', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -55,7 +55,7 @@ class Name { name: r'property', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -67,7 +67,7 @@ class Name { name: r'123Number', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart index 811eaa2118a7..6f6a484551e4 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/nullable_class.dart @@ -47,7 +47,7 @@ class NullableClass { name: r'integer_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -59,7 +59,7 @@ class NullableClass { name: r'number_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -71,7 +71,7 @@ class NullableClass { name: r'boolean_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -83,7 +83,7 @@ class NullableClass { name: r'string_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -95,7 +95,7 @@ class NullableClass { name: r'date_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -107,7 +107,7 @@ class NullableClass { name: r'datetime_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -119,7 +119,7 @@ class NullableClass { name: r'array_nullable_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -131,7 +131,7 @@ class NullableClass { name: r'array_and_items_nullable_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -143,7 +143,7 @@ class NullableClass { name: r'array_items_nullable', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -155,7 +155,7 @@ class NullableClass { name: r'object_nullable_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -167,7 +167,7 @@ class NullableClass { name: r'object_and_items_nullable_prop', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -179,7 +179,7 @@ class NullableClass { name: r'object_items_nullable', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart index 71bb0aa221e8..44e9d41a189d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/number_only.dart @@ -25,7 +25,7 @@ class NumberOnly { name: r'JustNumber', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart index 7beda7d4aa87..5a36ffb5147e 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/object_with_deprecated_fields.dart @@ -32,7 +32,7 @@ class ObjectWithDeprecatedFields { name: r'uuid', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -45,7 +45,7 @@ class ObjectWithDeprecatedFields { name: r'id', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -58,7 +58,7 @@ class ObjectWithDeprecatedFields { name: r'deprecatedRef', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -71,7 +71,7 @@ class ObjectWithDeprecatedFields { name: r'bars', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart index 00b4e62e0a14..dfbc4f5c5e41 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/order.dart @@ -35,7 +35,7 @@ class Order { name: r'id', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -47,7 +47,7 @@ class Order { name: r'petId', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -59,7 +59,7 @@ class Order { name: r'quantity', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -71,7 +71,7 @@ class Order { name: r'shipDate', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -84,7 +84,8 @@ class Order { name: r'status', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: OrderStatusEnum.unknownDefaultOpenApi, ) @@ -96,7 +97,7 @@ class Order { defaultValue: false, name: r'complete', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -137,14 +138,25 @@ class Order { /// Order Status enum OrderStatusEnum { - @JsonValue(r'placed') - placed, - @JsonValue(r'approved') - approved, - @JsonValue(r'delivered') - delivered, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, + /// Order Status +@JsonValue(r'placed') +placed(r'placed'), + /// Order Status +@JsonValue(r'approved') +approved(r'approved'), + /// Order Status +@JsonValue(r'delivered') +delivered(r'delivered'), + /// Order Status +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const OrderStatusEnum(this.value); + +final String value; + +@override +String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart index 9986dc4f7d16..a4df9cc62544 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_composite.dart @@ -29,7 +29,7 @@ class OuterComposite { name: r'my_number', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -41,7 +41,7 @@ class OuterComposite { name: r'my_string', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -53,7 +53,7 @@ class OuterComposite { name: r'my_boolean', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart index a8602e9183a3..f78d6b5c8b3d 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_object_with_enum_property.dart @@ -26,7 +26,8 @@ class OuterObjectWithEnumProperty { name: r'value', required: true, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: OuterEnumInteger.unknownDefaultOpenApi, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/parent_with_nullable.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/parent_with_nullable.dart index 880c2c33cec1..bda5847df5ad 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/parent_with_nullable.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/parent_with_nullable.dart @@ -27,7 +27,8 @@ class ParentWithNullable { name: r'type', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: ParentWithNullableTypeEnum.unknownDefaultOpenApi, ) @@ -39,7 +40,7 @@ class ParentWithNullable { name: r'nullableProperty', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -72,10 +73,17 @@ class ParentWithNullable { enum ParentWithNullableTypeEnum { - @JsonValue(r'ChildWithNullable') - childWithNullable, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, +@JsonValue(r'ChildWithNullable') +childWithNullable(r'ChildWithNullable'), +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const ParentWithNullableTypeEnum(this.value); + +final String value; + +@override +String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart index 1e7a108b7600..fdb70f9ce89a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/pet.dart @@ -37,7 +37,7 @@ class Pet { name: r'id', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -49,7 +49,7 @@ class Pet { name: r'category', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -61,7 +61,7 @@ class Pet { name: r'name', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -73,7 +73,7 @@ class Pet { name: r'photoUrls', required: true, - includeIfNull: false + includeIfNull: false, ) @@ -85,7 +85,7 @@ class Pet { name: r'tags', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -98,7 +98,8 @@ class Pet { name: r'status', required: false, - includeIfNull: false + includeIfNull: false, + unknownEnumValue: PetStatusEnum.unknownDefaultOpenApi, ) @@ -139,14 +140,25 @@ class Pet { /// pet status in the store enum PetStatusEnum { - @JsonValue(r'available') - available, - @JsonValue(r'pending') - pending, - @JsonValue(r'sold') - sold, - @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, + /// pet status in the store +@JsonValue(r'available') +available(r'available'), + /// pet status in the store +@JsonValue(r'pending') +pending(r'pending'), + /// pet status in the store +@JsonValue(r'sold') +sold(r'sold'), + /// pet status in the store +@JsonValue(r'unknown_default_open_api') +unknownDefaultOpenApi(r'unknown_default_open_api'); + +const PetStatusEnum(this.value); + +final String value; + +@override +String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart index 0a57599c7c3a..0ec8a7710c60 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/read_only_first.dart @@ -27,7 +27,7 @@ class ReadOnlyFirst { name: r'bar', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class ReadOnlyFirst { name: r'baz', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart index d3a033358f8c..175b6fb274ce 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/special_model_name.dart @@ -25,7 +25,7 @@ class SpecialModelName { name: r'$special[property.name]', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart index 00c6ff8cb702..abe588b27d6f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/tag.dart @@ -27,7 +27,7 @@ class Tag { name: r'id', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -39,7 +39,7 @@ class Tag { name: r'name', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/test_inline_freeform_additional_properties_request.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/test_inline_freeform_additional_properties_request.dart index 8f5947509baa..5eda7d48b384 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/test_inline_freeform_additional_properties_request.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/test_inline_freeform_additional_properties_request.dart @@ -25,7 +25,7 @@ class TestInlineFreeformAdditionalPropertiesRequest { name: r'someProperty', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart index 44a437d51349..56c95cb75f15 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/user.dart @@ -39,7 +39,7 @@ class User { name: r'id', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -51,7 +51,7 @@ class User { name: r'username', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -63,7 +63,7 @@ class User { name: r'firstName', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -75,7 +75,7 @@ class User { name: r'lastName', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -87,7 +87,7 @@ class User { name: r'email', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -99,7 +99,7 @@ class User { name: r'password', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -111,7 +111,7 @@ class User { name: r'phone', required: false, - includeIfNull: false + includeIfNull: false, ) @@ -124,7 +124,7 @@ class User { name: r'userStatus', required: false, - includeIfNull: false + includeIfNull: false, ) diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java index bfec468da5f3..8f9a776f1218 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java @@ -1112,7 +1112,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java index 5bbc08bb43f1..39656bea8944 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java @@ -1253,7 +1253,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java index 5bbc08bb43f1..39656bea8944 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java @@ -1253,7 +1253,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index 185c976cfade..a7fa592b744a 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -1351,7 +1351,11 @@ private Response sendRequest(String method, Invocation.Builder invocationBuilder } else if ("PUT".equals(method)) { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { - response = invocationBuilder.method("DELETE", entity); + if ("".equals(entity.getEntity())) { + response = invocationBuilder.method("DELETE"); + } else { + response = invocationBuilder.method("DELETE", entity); + } } else if ("PATCH".equals(method)) { response = invocationBuilder.method("PATCH", entity); } else { diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index 36cb0392c334..8558e1d2f58a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -112,6 +112,7 @@ docs/TestObjectForMultipartRequestsRequestMarker.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md docs/UnnamedDictWithAdditionalStringListProperties.md +docs/UploadFileWithAdditionalPropertiesRequestObject.md docs/User.md docs/UserApi.md docs/WithNestedOneOf.md @@ -233,6 +234,7 @@ petstore_api/models/test_object_for_multipart_requests_request_marker.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +petstore_api/models/upload_file_with_additional_properties_request_object.py petstore_api/models/user.py petstore_api/models/with_nested_one_of.py petstore_api/py.typed diff --git a/samples/openapi3/client/petstore/python-aiohttp/README.md b/samples/openapi3/client/petstore/python-aiohttp/README.md index 93a8e0a22566..5e4bef3e4142 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-aiohttp/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_object_for_multipart_requests**](docs/FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | *FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | *FakeApi* | [**test_string_map_reference**](docs/FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +*FakeApi* | [**upload_file_with_additional_properties**](docs/FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *ImportTestDatetimeApi* | [**import_test_return_datetime**](docs/ImportTestDatetimeApi.md#import_test_return_datetime) | **GET** /import_test/return_datetime | test date time *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -252,6 +253,7 @@ Class | Method | HTTP request | Description - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) - [UnnamedDictWithAdditionalStringListProperties](docs/UnnamedDictWithAdditionalStringListProperties.md) + - [UploadFileWithAdditionalPropertiesRequestObject](docs/UploadFileWithAdditionalPropertiesRequestObject.md) - [User](docs/User.md) - [WithNestedOneOf](docs/WithNestedOneOf.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md index 7d895e650b3a..901471b5477b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md @@ -40,6 +40,7 @@ Method | HTTP request | Description [**test_object_for_multipart_requests**](FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | [**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | [**test_string_map_reference**](FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +[**upload_file_with_additional_properties**](FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data # **fake_any_type_request_body** @@ -2482,3 +2483,76 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **upload_file_with_additional_properties** +> ModelApiResponse upload_file_with_additional_properties(file, object=object, count=count) + +uploads a file and additional properties using multipart/form-data + + + +### Example + + +```python +import petstore_api +from petstore_api.models.model_api_response import ModelApiResponse +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + file = None # bytearray | file to upload + object = petstore_api.UploadFileWithAdditionalPropertiesRequestObject() # UploadFileWithAdditionalPropertiesRequestObject | (optional) + count = 56 # int | Integer count (optional) + + try: + # uploads a file and additional properties using multipart/form-data + api_response = await api_instance.upload_file_with_additional_properties(file, object=object, count=count) + print("The response of FakeApi->upload_file_with_additional_properties:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->upload_file_with_additional_properties: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file** | **bytearray**| file to upload | + **object** | [**UploadFileWithAdditionalPropertiesRequestObject**](UploadFileWithAdditionalPropertiesRequestObject.md)| | [optional] + **count** | **int**| Integer count | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..141027780371 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -0,0 +1,30 @@ +# UploadFileWithAdditionalPropertiesRequestObject + +Additional object + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject + +# TODO update the JSON string below +json = "{}" +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +# print the JSON string representation of the object +print(UploadFileWithAdditionalPropertiesRequestObject.to_json()) + +# convert the object into a dict +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py index 5c8b494eec36..27cc58ac25b6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py @@ -141,5 +141,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py index cb55e0371cbe..ff7f136569f5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py @@ -24,6 +24,7 @@ from petstore_api.models.enum_class import EnumClass from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.health_check_result import HealthCheckResult +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty @@ -31,6 +32,7 @@ from petstore_api.models.tag import Tag from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.test_object_for_multipart_requests_request_marker import TestObjectForMultipartRequestsRequestMarker +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.api_client import ApiClient, RequestSerialized @@ -9812,3 +9814,306 @@ def _test_string_map_reference_serialize( ) + + + @validate_call + async def upload_file_with_additional_properties( + self, + file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")], + object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, + count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelApiResponse: + """uploads a file and additional properties using multipart/form-data + + + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_additional_properties_serialize( + file=file, + object=object, + count=count, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def upload_file_with_additional_properties_with_http_info( + self, + file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")], + object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, + count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelApiResponse]: + """uploads a file and additional properties using multipart/form-data + + + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_additional_properties_serialize( + file=file, + object=object, + count=count, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def upload_file_with_additional_properties_without_preload_content( + self, + file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")], + object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, + count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """uploads a file and additional properties using multipart/form-data + + + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_additional_properties_serialize( + file=file, + object=object, + count=count, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _upload_file_with_additional_properties_serialize( + self, + file, + object, + count, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if file is not None: + _files['file'] = file + if object is not None: + _form_params.append(('object', object)) + if count is not None: + _form_params.append(('count', count)) + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/upload_file_with_additional_properties', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py index b1dbefee666d..12531e2d9063 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..9040618ac0d7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): + """ + Additional object + """ # noqa: E501 + name: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py index 53b81b840d2c..ea9f42a51c4c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py @@ -184,6 +184,11 @@ async def request( content_type=v[2] ) else: + # Ensures that dict objects are serialized + if isinstance(v, dict): + v = json.dumps(v) + elif isinstance(v, int): + v = str(v) data.add_field(k, v) args["data"] = data @@ -208,8 +213,3 @@ async def request( r = await pool_manager.request(**args) return RESTResponse(r) - - - - - diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..8b3fa3b90840 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject + +class TestUploadFileWithAdditionalPropertiesRequestObject(unittest.TestCase): + """UploadFileWithAdditionalPropertiesRequestObject unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> UploadFileWithAdditionalPropertiesRequestObject: + """Test UploadFileWithAdditionalPropertiesRequestObject + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `UploadFileWithAdditionalPropertiesRequestObject` + """ + model = UploadFileWithAdditionalPropertiesRequestObject() + if include_optional: + return UploadFileWithAdditionalPropertiesRequestObject( + name = '' + ) + else: + return UploadFileWithAdditionalPropertiesRequestObject( + ) + """ + + def testUploadFileWithAdditionalPropertiesRequestObject(self): + """Test UploadFileWithAdditionalPropertiesRequestObject""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py new file mode 100644 index 000000000000..8de3969aa065 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/tests/test_rest.py @@ -0,0 +1,74 @@ +import os +import unittest +from unittest.mock import AsyncMock, Mock, patch + +import petstore_api + + +def get_field_from_formdata(formdata, name): + return next(filter(lambda x: x[0]["name"] == name, formdata._fields))[-1] + + +class TestMultipleResponseTypes(unittest.IsolatedAsyncioTestCase): + def setUpFiles(self): + self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles") + self.test_file_dir = os.path.realpath(self.test_file_dir) + self.test_file_path = os.path.join(self.test_file_dir, "foo.png") + + def setUp(self): + self.setUpFiles() + + async def test_multipart_requests(self): + mock_resp = AsyncMock() + mock_resp.return_value.read.return_value = b"some text" + mock_resp.return_value.status = 200 + mock_resp.return_value.headers = {} + + marker = petstore_api.TestObjectForMultipartRequestsRequestMarker( + name="name", + ) + + with patch("aiohttp.ClientSession.request", mock_resp): + async with petstore_api.ApiClient() as api_client: + fake_api = petstore_api.FakeApi(api_client) + await fake_api.test_object_for_multipart_requests(marker=marker) + + # success if no errors + + async def test_multipart_requests_with_file_and_additional_properties(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.read = AsyncMock( + return_value=b'{"code": 200, "type": "success", "message": "OK"}' + ) + mock_resp.headers = {"Content-Type": "application/json"} + + mock_request = AsyncMock(return_value=mock_resp) + with open(self.test_file_path, "rb") as f, patch( + "aiohttp.ClientSession.request", mock_request + ): + async with petstore_api.ApiClient() as api_client: + fake_api = petstore_api.FakeApi(api_client) + returned = await fake_api.upload_file_with_additional_properties( + file=(self.test_file_path, f.read()), + count=100, + object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( + name="foo" + ), + ) + + assert ( + returned.code == 200 + and returned.type == "success" + and returned.message == "OK" + ) + + mock_request.assert_called_once() + + formdata = mock_request.call_args_list[0].kwargs["data"] + + data_object = get_field_from_formdata(formdata, "object") + data_count = get_field_from_formdata(formdata, "count") + + assert type(data_count) is str + assert type(data_object) is str diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES index aa4a8eee280b..cafa99c6a715 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES @@ -112,6 +112,7 @@ docs/TestObjectForMultipartRequestsRequestMarker.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md docs/UnnamedDictWithAdditionalStringListProperties.md +docs/UploadFileWithAdditionalPropertiesRequestObject.md docs/User.md docs/UserApi.md docs/WithNestedOneOf.md @@ -233,6 +234,7 @@ petstore_api/models/test_object_for_multipart_requests_request_marker.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +petstore_api/models/upload_file_with_additional_properties_request_object.py petstore_api/models/user.py petstore_api/models/with_nested_one_of.py petstore_api/py.typed diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md index c01c6e92fef4..ee6d85b7df5f 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md @@ -124,6 +124,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_object_for_multipart_requests**](docs/FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | *FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | *FakeApi* | [**test_string_map_reference**](docs/FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +*FakeApi* | [**upload_file_with_additional_properties**](docs/FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *ImportTestDatetimeApi* | [**import_test_return_datetime**](docs/ImportTestDatetimeApi.md#import_test_return_datetime) | **GET** /import_test/return_datetime | test date time *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -253,6 +254,7 @@ Class | Method | HTTP request | Description - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) - [UnnamedDictWithAdditionalStringListProperties](docs/UnnamedDictWithAdditionalStringListProperties.md) + - [UploadFileWithAdditionalPropertiesRequestObject](docs/UploadFileWithAdditionalPropertiesRequestObject.md) - [User](docs/User.md) - [WithNestedOneOf](docs/WithNestedOneOf.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md index e33215808a67..512323e3286a 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md @@ -40,6 +40,7 @@ Method | HTTP request | Description [**test_object_for_multipart_requests**](FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | [**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | [**test_string_map_reference**](FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +[**upload_file_with_additional_properties**](FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data # **fake_any_type_request_body** @@ -2446,3 +2447,75 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **upload_file_with_additional_properties** +> ApiResponse upload_file_with_additional_properties(file, object=object, count=count) + +uploads a file and additional properties using multipart/form-data + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + file = None # bytearray | file to upload + object = petstore_api.UploadFileWithAdditionalPropertiesRequestObject() # UploadFileWithAdditionalPropertiesRequestObject | (optional) + count = 56 # int | Integer count (optional) + + try: + # uploads a file and additional properties using multipart/form-data + api_response = await api_instance.upload_file_with_additional_properties(file, object=object, count=count) + print("The response of FakeApi->upload_file_with_additional_properties:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->upload_file_with_additional_properties: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file** | **bytearray**| file to upload | + **object** | [**UploadFileWithAdditionalPropertiesRequestObject**](UploadFileWithAdditionalPropertiesRequestObject.md)| | [optional] + **count** | **int**| Integer count | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..7b983039ab90 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -0,0 +1,29 @@ +# UploadFileWithAdditionalPropertiesRequestObject + +Additional object + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject + +# TODO update the JSON string below +json = "{}" +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +# print the JSON string representation of the object +print UploadFileWithAdditionalPropertiesRequestObject.to_json() + +# convert the object into a dict +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py index 0d1b6af243ff..f178ffe52f18 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py @@ -141,5 +141,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py index ab7bdb1b0d60..7ee53259a5b9 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py @@ -26,6 +26,7 @@ from typing import Any, Dict, List, Optional, Union +from petstore_api.models.api_response import ApiResponse from petstore_api.models.client import Client from petstore_api.models.enum_class import EnumClass from petstore_api.models.file_schema_test_class import FileSchemaTestClass @@ -37,6 +38,7 @@ from petstore_api.models.tag import Tag from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.test_object_for_multipart_requests_request_marker import TestObjectForMultipartRequestsRequestMarker +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.api_client import ApiClient @@ -4662,3 +4664,150 @@ async def test_string_map_reference_with_http_info(self, request_body : Annotate _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + + @validate_arguments + async def upload_file_with_additional_properties(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: ApiResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the upload_file_with_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return await self.upload_file_with_additional_properties_with_http_info(file, object, count, **kwargs) # noqa: E501 + + @validate_arguments + async def upload_file_with_additional_properties_with_http_info(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'file', + 'object', + 'count' + ] + _all_params.extend( + [ + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method upload_file_with_additional_properties" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + if _params['file'] is not None: + _files['file'] = _params['file'] + + if _params['object'] is not None: + _form_params.append(('object', _params['object'])) + + if _params['count'] is not None: + _form_params.append(('count', _params['count'])) + + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "ApiResponse", + } + + return await self.api_client.call_api( + '/fake/upload_file_with_additional_properties', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py index de87c281c8fb..b6a5d674a51c 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_color.py index 60dbbe6dd7e9..d1ed38dc9b1b 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_color.py @@ -146,7 +146,8 @@ def to_dict(self) -> dict: if callable(to_json): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + # primitive type + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_pig.py index 1254f6789a8c..018d892467b6 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/any_of_pig.py @@ -125,7 +125,8 @@ def to_dict(self) -> dict: if callable(to_json): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + # primitive type + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..bafe5045c0d5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -0,0 +1,71 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Optional +from pydantic import BaseModel, StrictStr + +class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): + """ + Additional object # noqa: E501 + """ + name: Optional[StrictStr] = None + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + }, + exclude_none=True) + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return UploadFileWithAdditionalPropertiesRequestObject.parse_obj(obj) + + _obj = UploadFileWithAdditionalPropertiesRequestObject.parse_obj({ + "name": obj.get("name") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py index 7daf8c921c84..c71fbc6dea92 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/rest.py @@ -153,6 +153,11 @@ async def request(self, method, url, query_params=None, headers=None, filename=v[0], content_type=v[2]) else: + # Ensures that dict objects are serialized + if isinstance(v, dict): + v = json.dumps(v) + elif isinstance(v, int): + v = str(v) data.add_field(k, v) args["data"] = data diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..32ead9222dd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject # noqa: E501 + +class TestUploadFileWithAdditionalPropertiesRequestObject(unittest.TestCase): + """UploadFileWithAdditionalPropertiesRequestObject unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> UploadFileWithAdditionalPropertiesRequestObject: + """Test UploadFileWithAdditionalPropertiesRequestObject + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `UploadFileWithAdditionalPropertiesRequestObject` + """ + model = UploadFileWithAdditionalPropertiesRequestObject() # noqa: E501 + if include_optional: + return UploadFileWithAdditionalPropertiesRequestObject( + name = '' + ) + else: + return UploadFileWithAdditionalPropertiesRequestObject( + ) + """ + + def testUploadFileWithAdditionalPropertiesRequestObject(self): + """Test UploadFileWithAdditionalPropertiesRequestObject""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/tests/test_rest.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/tests/test_rest.py new file mode 100644 index 000000000000..7503fe1bc306 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/tests/test_rest.py @@ -0,0 +1,75 @@ +import os +import unittest +from unittest.mock import AsyncMock, Mock, patch + +import petstore_api + + +def get_field_from_formdata(formdata, name): + return next(filter(lambda x: x[0]["name"] == name, formdata._fields))[-1] + + +class TestMultipleResponseTypes(unittest.IsolatedAsyncioTestCase): + def setUpFiles(self): + self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles") + self.test_file_dir = os.path.realpath(self.test_file_dir) + self.test_file_path = os.path.join(self.test_file_dir, "foo.png") + + def setUp(self): + self.setUpFiles() + + async def test_multipart_requests(self): + mock_resp = AsyncMock() + mock_resp.return_value.read.return_value = b"some text" + mock_resp.return_value.status = 200 + mock_resp.return_value.headers = {} + + marker = petstore_api.TestObjectForMultipartRequestsRequestMarker( + name="name", + ) + + with patch("aiohttp.ClientSession.request", mock_resp): + async with petstore_api.ApiClient() as api_client: + fake_api = petstore_api.FakeApi(api_client) + await fake_api.test_object_for_multipart_requests(marker=marker) + + # success if no errors + + async def test_multipart_requests_with_file_and_additional_properties(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.read = AsyncMock( + return_value=b'{"code": 200, "type": "success", "message": "OK"}' + ) + mock_resp.headers = {"Content-Type": "application/json"} + + mock_request = AsyncMock(return_value=mock_resp) + with patch("aiohttp.ClientSession.request", mock_request): + async with petstore_api.ApiClient() as api_client: + fake_api = petstore_api.FakeApi(api_client) + returned = await fake_api.upload_file_with_additional_properties( + file=self.test_file_path, + count=100, + object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( + name="foo" + ), + ) + + # response shape is actually petstore_api.models.api_response.ApiResponse, + # but return type is annotated petstore_api.api_response.ApiResponse, thus + # the type: ignores + assert ( + returned.code == 200 # type: ignore + and returned.type == "success" # type: ignore + and returned.message == "OK" # type: ignore + ) + + mock_request.assert_called_once() + + formdata = mock_request.call_args_list[0].kwargs["data"] + + data_object = get_field_from_formdata(formdata, "object") + data_count = get_field_from_formdata(formdata, "count") + + assert type(data_count) is str + assert type(data_object) is str diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES index aa4a8eee280b..cafa99c6a715 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES @@ -112,6 +112,7 @@ docs/TestObjectForMultipartRequestsRequestMarker.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md docs/UnnamedDictWithAdditionalStringListProperties.md +docs/UploadFileWithAdditionalPropertiesRequestObject.md docs/User.md docs/UserApi.md docs/WithNestedOneOf.md @@ -233,6 +234,7 @@ petstore_api/models/test_object_for_multipart_requests_request_marker.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +petstore_api/models/upload_file_with_additional_properties_request_object.py petstore_api/models/user.py petstore_api/models/with_nested_one_of.py petstore_api/py.typed diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/README.md b/samples/openapi3/client/petstore/python-pydantic-v1/README.md index 684881a19a9b..aff627886543 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/README.md @@ -124,6 +124,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_object_for_multipart_requests**](docs/FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | *FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | *FakeApi* | [**test_string_map_reference**](docs/FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +*FakeApi* | [**upload_file_with_additional_properties**](docs/FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *ImportTestDatetimeApi* | [**import_test_return_datetime**](docs/ImportTestDatetimeApi.md#import_test_return_datetime) | **GET** /import_test/return_datetime | test date time *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -253,6 +254,7 @@ Class | Method | HTTP request | Description - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) - [UnnamedDictWithAdditionalStringListProperties](docs/UnnamedDictWithAdditionalStringListProperties.md) + - [UploadFileWithAdditionalPropertiesRequestObject](docs/UploadFileWithAdditionalPropertiesRequestObject.md) - [User](docs/User.md) - [WithNestedOneOf](docs/WithNestedOneOf.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md index 59d600df9879..3777d3d76e0e 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md @@ -40,6 +40,7 @@ Method | HTTP request | Description [**test_object_for_multipart_requests**](FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | [**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | [**test_string_map_reference**](FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +[**upload_file_with_additional_properties**](FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data # **fake_any_type_request_body** @@ -2446,3 +2447,75 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **upload_file_with_additional_properties** +> ApiResponse upload_file_with_additional_properties(file, object=object, count=count) + +uploads a file and additional properties using multipart/form-data + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.models.api_response import ApiResponse +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + file = None # bytearray | file to upload + object = petstore_api.UploadFileWithAdditionalPropertiesRequestObject() # UploadFileWithAdditionalPropertiesRequestObject | (optional) + count = 56 # int | Integer count (optional) + + try: + # uploads a file and additional properties using multipart/form-data + api_response = api_instance.upload_file_with_additional_properties(file, object=object, count=count) + print("The response of FakeApi->upload_file_with_additional_properties:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->upload_file_with_additional_properties: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file** | **bytearray**| file to upload | + **object** | [**UploadFileWithAdditionalPropertiesRequestObject**](UploadFileWithAdditionalPropertiesRequestObject.md)| | [optional] + **count** | **int**| Integer count | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..7b983039ab90 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -0,0 +1,29 @@ +# UploadFileWithAdditionalPropertiesRequestObject + +Additional object + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject + +# TODO update the JSON string below +json = "{}" +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +# print the JSON string representation of the object +print UploadFileWithAdditionalPropertiesRequestObject.to_json() + +# convert the object into a dict +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py index 0d1b6af243ff..f178ffe52f18 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py @@ -141,5 +141,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py index 88992b423cc3..62ef06ed6b0e 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py @@ -25,6 +25,7 @@ from typing import Any, Dict, List, Optional, Union +from petstore_api.models.api_response import ApiResponse from petstore_api.models.client import Client from petstore_api.models.enum_class import EnumClass from petstore_api.models.file_schema_test_class import FileSchemaTestClass @@ -36,6 +37,7 @@ from petstore_api.models.tag import Tag from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.test_object_for_multipart_requests_request_marker import TestObjectForMultipartRequestsRequestMarker +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.api_client import ApiClient @@ -5237,3 +5239,166 @@ def test_string_map_reference_with_http_info(self, request_body : Annotated[Dict _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + + @validate_arguments + def upload_file_with_additional_properties(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.upload_file_with_additional_properties(file, object, count, async_req=True) + >>> result = thread.get() + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: ApiResponse + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the upload_file_with_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.upload_file_with_additional_properties_with_http_info(file, object, count, **kwargs) # noqa: E501 + + @validate_arguments + def upload_file_with_additional_properties_with_http_info(self, file : Annotated[Union[StrictBytes, StrictStr], Field(..., description="file to upload")], object : Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, count : Annotated[Optional[StrictInt], Field(description="Integer count")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """uploads a file and additional properties using multipart/form-data # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.upload_file_with_additional_properties_with_http_info(file, object, count, async_req=True) + >>> result = thread.get() + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'file', + 'object', + 'count' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method upload_file_with_additional_properties" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + if _params['file'] is not None: + _files['file'] = _params['file'] + + if _params['object'] is not None: + _form_params.append(('object', _params['object'])) + + if _params['count'] is not None: + _form_params.append(('count', _params['count'])) + + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "ApiResponse", + } + + return self.api_client.call_api( + '/fake/upload_file_with_additional_properties', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py index de87c281c8fb..b6a5d674a51c 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_color.py index 60dbbe6dd7e9..d1ed38dc9b1b 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_color.py @@ -146,7 +146,8 @@ def to_dict(self) -> dict: if callable(to_json): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + # primitive type + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_pig.py index 1254f6789a8c..018d892467b6 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/any_of_pig.py @@ -125,7 +125,8 @@ def to_dict(self) -> dict: if callable(to_json): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + # primitive type + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..a8820b0262b4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -0,0 +1,83 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, Dict, Optional +from pydantic import BaseModel, StrictStr + +class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): + """ + Additional object # noqa: E501 + """ + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties = ["name"] + + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.dict(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self): + """Returns the dictionary representation of the model using alias""" + _dict = self.dict(by_alias=True, + exclude={ + "additional_properties" + }, + exclude_none=True) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: dict) -> UploadFileWithAdditionalPropertiesRequestObject: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return UploadFileWithAdditionalPropertiesRequestObject.parse_obj(obj) + + _obj = UploadFileWithAdditionalPropertiesRequestObject.parse_obj({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py index fcbbdab49ab9..a4a233273c5e 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py @@ -200,6 +200,8 @@ def request(self, method, url, query_params=None, headers=None, # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] r = self.pool_manager.request( method, url, fields=post_params, diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..32ead9222dd8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject # noqa: E501 + +class TestUploadFileWithAdditionalPropertiesRequestObject(unittest.TestCase): + """UploadFileWithAdditionalPropertiesRequestObject unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> UploadFileWithAdditionalPropertiesRequestObject: + """Test UploadFileWithAdditionalPropertiesRequestObject + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `UploadFileWithAdditionalPropertiesRequestObject` + """ + model = UploadFileWithAdditionalPropertiesRequestObject() # noqa: E501 + if include_optional: + return UploadFileWithAdditionalPropertiesRequestObject( + name = '' + ) + else: + return UploadFileWithAdditionalPropertiesRequestObject( + ) + """ + + def testUploadFileWithAdditionalPropertiesRequestObject(self): + """Test UploadFileWithAdditionalPropertiesRequestObject""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_model.py b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_model.py index b66a414f913c..ce84e0b035ff 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_model.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_model.py @@ -177,7 +177,7 @@ def test_anyOf_array_of_integers(self): except ValueError as e: self.assertTrue("ensure this value is less than or equal to 255" in str(e)) - # test from_josn + # test from_json json_str = '[12,34,56]' p = petstore_api.AnyOfColor.from_json(json_str) self.assertEqual(p.actual_instance, [12, 34,56]) @@ -187,6 +187,28 @@ def test_anyOf_array_of_integers(self): except ValueError as e: self.assertTrue("ensure this value is less than or equal to 255" in str(e)) + # test from_json, schema 3 + json_str = '"#123456"' + p = petstore_api.AnyOfColor.from_json(json_str) + self.assertIsInstance(p.actual_instance, str) + self.assertEqual(p.actual_instance, '#123456') + + # test to_json, schema 3 + p = petstore_api.AnyOfColor(actual_instance='#123456') + self.assertEqual(p.to_json(), '"#123456"') + + # test from_dict, schema 3 + obj = '#123456' + p = petstore_api.AnyOfColor.from_dict(obj) + self.assertIsInstance(p.actual_instance, str) + self.assertEqual(p.actual_instance, '#123456') + + # test to_dict, schema 3 + p = petstore_api.AnyOfColor(actual_instance='#123456') + self.assertEqual(p.to_dict(), '#123456') + p = petstore_api.AnyOfColor.from_dict(p.to_dict()) + self.assertEqual(p.actual_instance, '#123456') + def test_oneOf(self): # test new Pig bp = petstore_api.BasquePig.from_dict({"className": "BasquePig", "color": "red"}) @@ -300,6 +322,9 @@ def test_anyOf(self): " DanishPig expected dict not int (type=type_error)") self.assertEqual(str(e), error_message) + # test to_dict + self.assertEqual(p.to_dict(), {'className': 'BasquePig', 'color': 'red'}) + # test to_json self.assertEqual(p.to_json(), '{"className": "BasquePig", "color": "red"}') diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_rest.py b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_rest.py new file mode 100644 index 000000000000..d655f7da1f9c --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_rest.py @@ -0,0 +1,57 @@ +import os +import unittest +from unittest.mock import Mock, patch + +import petstore_api + + +class TestMultipleResponseTypes(unittest.TestCase): + def setUpFiles(self): + self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles") + self.test_file_dir = os.path.realpath(self.test_file_dir) + self.test_file_path = os.path.join(self.test_file_dir, "pix.gif") + + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.fake_api = petstore_api.FakeApi(self.api_client) + self.setUpFiles() + + def test_multipart_requests(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.data = b"some text" + mock_resp.headers = {} + + marker = petstore_api.TestObjectForMultipartRequestsRequestMarker( + name="name", + ) + + with patch("urllib3.PoolManager.urlopen", return_value=mock_resp): + returned = self.fake_api.test_object_for_multipart_requests(marker=marker) + assert returned is None + + def test_multipart_requests_with_file_and_additional_properties(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.data = b'{"code": 200, "type": "success", "message": "OK"}' + mock_resp.headers = {"Content-Type": "application/json"} + with patch("urllib3.PoolManager.urlopen", return_value=mock_resp): + returned = self.fake_api.upload_file_with_additional_properties( + file=self.test_file_path, + count=100, + object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( + name="foo" + ), + ) + + # response shape is actually petstore_api.models.api_response.ApiResponse, + # but return type is annotated petstore_api.api_response.ApiResponse, thus + # the type: ignores + assert ( + returned.code == 200 # type: ignore + and returned.type == "success" # type: ignore + and returned.message == "OK" # type: ignore + ) + + # if the request is successful, both int and dict body parameters were + # successfully serialized diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index 36cb0392c334..8558e1d2f58a 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -112,6 +112,7 @@ docs/TestObjectForMultipartRequestsRequestMarker.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md docs/UnnamedDictWithAdditionalStringListProperties.md +docs/UploadFileWithAdditionalPropertiesRequestObject.md docs/User.md docs/UserApi.md docs/WithNestedOneOf.md @@ -233,6 +234,7 @@ petstore_api/models/test_object_for_multipart_requests_request_marker.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +petstore_api/models/upload_file_with_additional_properties_request_object.py petstore_api/models/user.py petstore_api/models/with_nested_one_of.py petstore_api/py.typed diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index 3b0793204ba6..130f174208fe 100755 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**test_object_for_multipart_requests**](docs/FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | *FakeApi* | [**test_query_parameter_collection_format**](docs/FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | *FakeApi* | [**test_string_map_reference**](docs/FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +*FakeApi* | [**upload_file_with_additional_properties**](docs/FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data *FakeClassnameTags123Api* | [**test_classname**](docs/FakeClassnameTags123Api.md#test_classname) | **PATCH** /fake_classname_test | To test class name in snake case *ImportTestDatetimeApi* | [**import_test_return_datetime**](docs/ImportTestDatetimeApi.md#import_test_return_datetime) | **GET** /import_test/return_datetime | test date time *PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store @@ -252,6 +253,7 @@ Class | Method | HTTP request | Description - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) - [UnnamedDictWithAdditionalStringListProperties](docs/UnnamedDictWithAdditionalStringListProperties.md) + - [UploadFileWithAdditionalPropertiesRequestObject](docs/UploadFileWithAdditionalPropertiesRequestObject.md) - [User](docs/User.md) - [WithNestedOneOf](docs/WithNestedOneOf.md) diff --git a/samples/openapi3/client/petstore/python/docs/FakeApi.md b/samples/openapi3/client/petstore/python/docs/FakeApi.md index a45bd7670a8c..7b0665800fd5 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python/docs/FakeApi.md @@ -40,6 +40,7 @@ Method | HTTP request | Description [**test_object_for_multipart_requests**](FakeApi.md#test_object_for_multipart_requests) | **POST** /fake/object_for_multipart_requests | [**test_query_parameter_collection_format**](FakeApi.md#test_query_parameter_collection_format) | **PUT** /fake/test-query-parameters | [**test_string_map_reference**](FakeApi.md#test_string_map_reference) | **POST** /fake/stringMap-reference | test referenced string map +[**upload_file_with_additional_properties**](FakeApi.md#upload_file_with_additional_properties) | **POST** /fake/upload_file_with_additional_properties | uploads a file and additional properties using multipart/form-data # **fake_any_type_request_body** @@ -2482,3 +2483,76 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **upload_file_with_additional_properties** +> ModelApiResponse upload_file_with_additional_properties(file, object=object, count=count) + +uploads a file and additional properties using multipart/form-data + + + +### Example + + +```python +import petstore_api +from petstore_api.models.model_api_response import ModelApiResponse +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + file = None # bytearray | file to upload + object = petstore_api.UploadFileWithAdditionalPropertiesRequestObject() # UploadFileWithAdditionalPropertiesRequestObject | (optional) + count = 56 # int | Integer count (optional) + + try: + # uploads a file and additional properties using multipart/form-data + api_response = api_instance.upload_file_with_additional_properties(file, object=object, count=count) + print("The response of FakeApi->upload_file_with_additional_properties:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->upload_file_with_additional_properties: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file** | **bytearray**| file to upload | + **object** | [**UploadFileWithAdditionalPropertiesRequestObject**](UploadFileWithAdditionalPropertiesRequestObject.md)| | [optional] + **count** | **int**| Integer count | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md b/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md new file mode 100644 index 000000000000..141027780371 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/UploadFileWithAdditionalPropertiesRequestObject.md @@ -0,0 +1,30 @@ +# UploadFileWithAdditionalPropertiesRequestObject + +Additional object + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject + +# TODO update the JSON string below +json = "{}" +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string +upload_file_with_additional_properties_request_object_instance = UploadFileWithAdditionalPropertiesRequestObject.from_json(json) +# print the JSON string representation of the object +print(UploadFileWithAdditionalPropertiesRequestObject.to_json()) + +# convert the object into a dict +upload_file_with_additional_properties_request_object_dict = upload_file_with_additional_properties_request_object_instance.to_dict() +# create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict +upload_file_with_additional_properties_request_object_from_dict = UploadFileWithAdditionalPropertiesRequestObject.from_dict(upload_file_with_additional_properties_request_object_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/__init__.py index 5c8b494eec36..27cc58ac25b6 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -141,5 +141,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py index 1848c6c44065..78d16e5f5045 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py @@ -24,6 +24,7 @@ from petstore_api.models.enum_class import EnumClass from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.health_check_result import HealthCheckResult +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.outer_composite import OuterComposite from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty @@ -31,6 +32,7 @@ from petstore_api.models.tag import Tag from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.test_object_for_multipart_requests_request_marker import TestObjectForMultipartRequestsRequestMarker +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.api_client import ApiClient, RequestSerialized @@ -9812,3 +9814,306 @@ def _test_string_map_reference_serialize( ) + + + @validate_call + def upload_file_with_additional_properties( + self, + file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")], + object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, + count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelApiResponse: + """uploads a file and additional properties using multipart/form-data + + + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_additional_properties_serialize( + file=file, + object=object, + count=count, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def upload_file_with_additional_properties_with_http_info( + self, + file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")], + object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, + count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelApiResponse]: + """uploads a file and additional properties using multipart/form-data + + + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_additional_properties_serialize( + file=file, + object=object, + count=count, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def upload_file_with_additional_properties_without_preload_content( + self, + file: Annotated[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]], Field(description="file to upload")], + object: Optional[UploadFileWithAdditionalPropertiesRequestObject] = None, + count: Annotated[Optional[StrictInt], Field(description="Integer count")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """uploads a file and additional properties using multipart/form-data + + + + :param file: file to upload (required) + :type file: bytearray + :param object: + :type object: UploadFileWithAdditionalPropertiesRequestObject + :param count: Integer count + :type count: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_additional_properties_serialize( + file=file, + object=object, + count=count, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _upload_file_with_additional_properties_serialize( + self, + file, + object, + count, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if file is not None: + _files['file'] = file + if object is not None: + _form_params.append(('object', object)) + if count is not None: + _form_params.append(('count', count)) + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/upload_file_with_additional_properties', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index b1dbefee666d..12531e2d9063 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -116,5 +116,6 @@ from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties from petstore_api.models.unnamed_dict_with_additional_string_list_properties import UnnamedDictWithAdditionalStringListProperties +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject from petstore_api.models.user import User from petstore_api.models.with_nested_one_of import WithNestedOneOf diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..6d79131bfe79 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/upload_file_with_additional_properties_request_object.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, ConfigDict, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class UploadFileWithAdditionalPropertiesRequestObject(BaseModel): + """ + Additional object + """ # noqa: E501 + name: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of UploadFileWithAdditionalPropertiesRequestObject from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/test/test_upload_file_with_additional_properties_request_object.py b/samples/openapi3/client/petstore/python/test/test_upload_file_with_additional_properties_request_object.py new file mode 100644 index 000000000000..8b3fa3b90840 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_upload_file_with_additional_properties_request_object.py @@ -0,0 +1,51 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest + +from petstore_api.models.upload_file_with_additional_properties_request_object import UploadFileWithAdditionalPropertiesRequestObject + +class TestUploadFileWithAdditionalPropertiesRequestObject(unittest.TestCase): + """UploadFileWithAdditionalPropertiesRequestObject unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> UploadFileWithAdditionalPropertiesRequestObject: + """Test UploadFileWithAdditionalPropertiesRequestObject + include_optional is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `UploadFileWithAdditionalPropertiesRequestObject` + """ + model = UploadFileWithAdditionalPropertiesRequestObject() + if include_optional: + return UploadFileWithAdditionalPropertiesRequestObject( + name = '' + ) + else: + return UploadFileWithAdditionalPropertiesRequestObject( + ) + """ + + def testUploadFileWithAdditionalPropertiesRequestObject(self): + """Test UploadFileWithAdditionalPropertiesRequestObject""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests/test_rest.py b/samples/openapi3/client/petstore/python/tests/test_rest.py index 4c69b5d72a53..47989845e356 100644 --- a/samples/openapi3/client/petstore/python/tests/test_rest.py +++ b/samples/openapi3/client/petstore/python/tests/test_rest.py @@ -1,16 +1,20 @@ -import json +import os import unittest -from unittest.mock import patch, Mock - -import pytest +from unittest.mock import Mock, patch import petstore_api class TestMultipleResponseTypes(unittest.TestCase): + def setUpFiles(self): + self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles") + self.test_file_dir = os.path.realpath(self.test_file_dir) + self.test_file_path = os.path.join(self.test_file_dir, "pix.gif") + def setUp(self): self.api_client = petstore_api.ApiClient() self.fake_api = petstore_api.FakeApi(self.api_client) + self.setUpFiles() def test_multipart_requests(self): mock_resp = Mock() @@ -22,10 +26,31 @@ def test_multipart_requests(self): name="name", ) - with patch( + with patch("urllib3.PoolManager.urlopen", return_value=mock_resp): + returned = self.fake_api.test_object_for_multipart_requests(marker=marker) + assert returned is None + + def test_multipart_requests_with_file_and_additional_properties(self): + mock_resp = Mock() + mock_resp.status = 200 + mock_resp.data = b'{"code": 200, "type": "success", "message": "OK"}' + mock_resp.headers = {"Content-Type": "application/json"} + with open(self.test_file_path, "rb") as f, patch( "urllib3.PoolManager.urlopen", return_value=mock_resp ): - returned = self.fake_api.test_object_for_multipart_requests( - marker=marker + returned = self.fake_api.upload_file_with_additional_properties( + file=(self.test_file_path, f.read()), + count=100, + object=petstore_api.UploadFileWithAdditionalPropertiesRequestObject( + name="foo" + ), ) - assert returned is None \ No newline at end of file + + assert ( + returned.code == 200 + and returned.type == "success" + and returned.message == "OK" + ) + + # if the request is successful, both int and dict body parameters were + # successfully serialized diff --git a/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator-ignore b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/FILES b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/FILES new file mode 100644 index 000000000000..d9ea5ba5025b --- /dev/null +++ b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/FILES @@ -0,0 +1 @@ +Sample.avsc diff --git a/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION new file mode 100644 index 000000000000..17f2442ff3bc --- /dev/null +++ b/samples/openapi3/schema/valid-enums/avro-schema-enum/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.9.0-SNAPSHOT diff --git a/samples/openapi3/schema/valid-enums/avro-schema-enum/Sample.avsc b/samples/openapi3/schema/valid-enums/avro-schema-enum/Sample.avsc new file mode 100644 index 000000000000..23281b4a7dde --- /dev/null +++ b/samples/openapi3/schema/valid-enums/avro-schema-enum/Sample.avsc @@ -0,0 +1,26 @@ +{ + "namespace": "model", + "type": "record", + "doc": "", + "name": "Sample", + "fields": [ + { + "name": "type", + "type": ["null", { + "type": "enum", + "name": "Sample_type", + "symbols": [ + "a", + "b", + "uh_oh", + "_0h_oh", + "coll_ision", + "coll_ision2" + ] + }], + "doc": "", + "default": null + } + ] + +} diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api.go b/samples/openapi3/server/petstore/go/go-petstore/go/api.go index 9fdfee3fcefd..6524cd7a8c23 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api.go @@ -22,24 +22,24 @@ import ( // The PetAPIRouter implementation should parse necessary information from the http request, // pass the data to a PetAPIServicer to perform the required actions, then write the service results to the http response. type PetAPIRouter interface { + UpdatePet(http.ResponseWriter, *http.Request) AddPet(http.ResponseWriter, *http.Request) - DeletePet(http.ResponseWriter, *http.Request) FindPetsByStatus(http.ResponseWriter, *http.Request) // Deprecated FindPetsByTags(http.ResponseWriter, *http.Request) GetPetById(http.ResponseWriter, *http.Request) - UpdatePet(http.ResponseWriter, *http.Request) UpdatePetWithForm(http.ResponseWriter, *http.Request) + DeletePet(http.ResponseWriter, *http.Request) UploadFile(http.ResponseWriter, *http.Request) } // StoreAPIRouter defines the required methods for binding the api requests to a responses for the StoreAPI // The StoreAPIRouter implementation should parse necessary information from the http request, // pass the data to a StoreAPIServicer to perform the required actions, then write the service results to the http response. type StoreAPIRouter interface { - DeleteOrder(http.ResponseWriter, *http.Request) GetInventory(http.ResponseWriter, *http.Request) - GetOrderById(http.ResponseWriter, *http.Request) PlaceOrder(http.ResponseWriter, *http.Request) + GetOrderById(http.ResponseWriter, *http.Request) + DeleteOrder(http.ResponseWriter, *http.Request) } // UserAPIRouter defines the required methods for binding the api requests to a responses for the UserAPI // The UserAPIRouter implementation should parse necessary information from the http request, @@ -48,11 +48,11 @@ type UserAPIRouter interface { CreateUser(http.ResponseWriter, *http.Request) CreateUsersWithArrayInput(http.ResponseWriter, *http.Request) CreateUsersWithListInput(http.ResponseWriter, *http.Request) - DeleteUser(http.ResponseWriter, *http.Request) - GetUserByName(http.ResponseWriter, *http.Request) LoginUser(http.ResponseWriter, *http.Request) LogoutUser(http.ResponseWriter, *http.Request) + GetUserByName(http.ResponseWriter, *http.Request) UpdateUser(http.ResponseWriter, *http.Request) + DeleteUser(http.ResponseWriter, *http.Request) } @@ -61,14 +61,14 @@ type UserAPIRouter interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type PetAPIServicer interface { + UpdatePet(context.Context, Pet) (ImplResponse, error) AddPet(context.Context, Pet) (ImplResponse, error) - DeletePet(context.Context, int64, string) (ImplResponse, error) FindPetsByStatus(context.Context, []string) (ImplResponse, error) // Deprecated FindPetsByTags(context.Context, []string) (ImplResponse, error) GetPetById(context.Context, int64) (ImplResponse, error) - UpdatePet(context.Context, Pet) (ImplResponse, error) UpdatePetWithForm(context.Context, int64, string, string) (ImplResponse, error) + DeletePet(context.Context, int64, string) (ImplResponse, error) UploadFile(context.Context, int64, string, *os.File) (ImplResponse, error) } @@ -78,10 +78,10 @@ type PetAPIServicer interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type StoreAPIServicer interface { - DeleteOrder(context.Context, string) (ImplResponse, error) GetInventory(context.Context) (ImplResponse, error) - GetOrderById(context.Context, int64) (ImplResponse, error) PlaceOrder(context.Context, Order) (ImplResponse, error) + GetOrderById(context.Context, int64) (ImplResponse, error) + DeleteOrder(context.Context, string) (ImplResponse, error) } @@ -93,9 +93,9 @@ type UserAPIServicer interface { CreateUser(context.Context, User) (ImplResponse, error) CreateUsersWithArrayInput(context.Context, []User) (ImplResponse, error) CreateUsersWithListInput(context.Context, []User) (ImplResponse, error) - DeleteUser(context.Context, string, bool) (ImplResponse, error) - GetUserByName(context.Context, string) (ImplResponse, error) LoginUser(context.Context, string, string, int32, int64, float32, float64, bool) (ImplResponse, error) LogoutUser(context.Context) (ImplResponse, error) + GetUserByName(context.Context, string) (ImplResponse, error) UpdateUser(context.Context, string, User) (ImplResponse, error) + DeleteUser(context.Context, string, bool) (ImplResponse, error) } diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go index 5b043ad51bcd..25d09e53378b 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go @@ -52,16 +52,16 @@ func NewPetAPIController(s PetAPIServicer, opts ...PetAPIOption) *PetAPIControll // Routes returns all the api routes for the PetAPIController func (c *PetAPIController) Routes() Routes { return Routes{ + "UpdatePet": Route{ + strings.ToUpper("Put"), + "/v2/pet", + c.UpdatePet, + }, "AddPet": Route{ strings.ToUpper("Post"), "/v2/pet", c.AddPet, }, - "DeletePet": Route{ - strings.ToUpper("Delete"), - "/v2/pet/{petId}", - c.DeletePet, - }, "FindPetsByStatus": Route{ strings.ToUpper("Get"), "/v2/pet/findByStatus", @@ -77,16 +77,16 @@ func (c *PetAPIController) Routes() Routes { "/v2/pet/{petId}", c.GetPetById, }, - "UpdatePet": Route{ - strings.ToUpper("Put"), - "/v2/pet", - c.UpdatePet, - }, "UpdatePetWithForm": Route{ strings.ToUpper("Post"), "/v2/pet/{petId}", c.UpdatePetWithForm, }, + "DeletePet": Route{ + strings.ToUpper("Delete"), + "/v2/pet/{petId}", + c.DeletePet, + }, "UploadFile": Route{ strings.ToUpper("Post"), "/v2/pet/{petId}/uploadImage", @@ -95,8 +95,8 @@ func (c *PetAPIController) Routes() Routes { } } -// AddPet - Add a new pet to the store -func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { +// UpdatePet - Update an existing pet +func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { petParam := Pet{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() @@ -112,7 +112,7 @@ func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { c.errorHandler(w, r, err, nil) return } - result, err := c.service.AddPet(r.Context(), petParam) + result, err := c.service.UpdatePet(r.Context(), petParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -122,18 +122,24 @@ func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// DeletePet - Deletes a pet -func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { - petIdParam, err := parseNumericParameter[int64]( - chi.URLParam(r, "petId"), - WithRequire[int64](parseInt64), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) +// AddPet - Add a new pet to the store +func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { + petParam := Pet{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&petParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - apiKeyParam := r.Header.Get("api_key") - result, err := c.service.DeletePet(r.Context(), petIdParam, apiKeyParam) + if err := AssertPetRequired(petParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + if err := AssertPetConstraints(petParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.AddPet(r.Context(), petParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -206,24 +212,27 @@ func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// UpdatePet - Update an existing pet -func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { - petParam := Pet{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&petParam); err != nil { +// UpdatePetWithForm - Updates a pet in the store with form data +func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - if err := AssertPetRequired(petParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - if err := AssertPetConstraints(petParam); err != nil { - c.errorHandler(w, r, err, nil) + petIdParam, err := parseNumericParameter[int64]( + chi.URLParam(r, "petId"), + WithRequire[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - result, err := c.service.UpdatePet(r.Context(), petParam) + + + nameParam := r.FormValue("name") + + + statusParam := r.FormValue("status") + result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -233,12 +242,8 @@ func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// UpdatePetWithForm - Updates a pet in the store with form data -func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) { - if err := r.ParseForm(); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } +// DeletePet - Deletes a pet +func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { petIdParam, err := parseNumericParameter[int64]( chi.URLParam(r, "petId"), WithRequire[int64](parseInt64), @@ -247,13 +252,8 @@ func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Requ c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - - - nameParam := r.FormValue("name") - - - statusParam := r.FormValue("status") - result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) + apiKeyParam := r.Header.Get("api_key") + result, err := c.service.DeletePet(r.Context(), petIdParam, apiKeyParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_pet_service.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_pet_service.go index cea78ae519a5..b7730e3980ec 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_pet_service.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_pet_service.go @@ -28,29 +28,38 @@ func NewPetAPIService() *PetAPIService { return &PetAPIService{} } -// AddPet - Add a new pet to the store -func (s *PetAPIService) AddPet(ctx context.Context, pet Pet) (ImplResponse, error) { - // TODO - update AddPet with the required logic for this service method. +// UpdatePet - Update an existing pet +func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { + // TODO - update UpdatePet with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ... // return Response(200, Pet{}), nil + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... // return Response(405, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("AddPet method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented") } -// DeletePet - Deletes a pet -func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) { - // TODO - update DeletePet with the required logic for this service method. +// AddPet - Add a new pet to the store +func (s *PetAPIService) AddPet(ctx context.Context, pet Pet) (ImplResponse, error) { + // TODO - update AddPet with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil + // TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ... + // return Response(200, Pet{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") + // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... + // return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("AddPet method not implemented") } // FindPetsByStatus - Finds Pets by status @@ -99,35 +108,26 @@ func (s *PetAPIService) GetPetById(ctx context.Context, petId int64) (ImplRespon return Response(http.StatusNotImplemented, nil), errors.New("GetPetById method not implemented") } -// UpdatePet - Update an existing pet -func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { - // TODO - update UpdatePet with the required logic for this service method. +// UpdatePetWithForm - Updates a pet in the store with form data +func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) { + // TODO - update UpdatePetWithForm with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ... - // return Response(200, Pet{}), nil - - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil - // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... // return Response(405, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented") } -// UpdatePetWithForm - Updates a pet in the store with form data -func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) { - // TODO - update UpdatePetWithForm with the required logic for this service method. +// DeletePet - Deletes a pet +func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) { + // TODO - update DeletePet with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... - // return Response(405, nil),nil + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") } // UploadFile - uploads an image diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go index e364efe39889..be4a6289e97a 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go @@ -51,37 +51,32 @@ func NewStoreAPIController(s StoreAPIServicer, opts ...StoreAPIOption) *StoreAPI // Routes returns all the api routes for the StoreAPIController func (c *StoreAPIController) Routes() Routes { return Routes{ - "DeleteOrder": Route{ - strings.ToUpper("Delete"), - "/v2/store/order/{orderId}", - c.DeleteOrder, - }, "GetInventory": Route{ strings.ToUpper("Get"), "/v2/store/inventory", c.GetInventory, }, + "PlaceOrder": Route{ + strings.ToUpper("Post"), + "/v2/store/order", + c.PlaceOrder, + }, "GetOrderById": Route{ strings.ToUpper("Get"), "/v2/store/order/{orderId}", c.GetOrderById, }, - "PlaceOrder": Route{ - strings.ToUpper("Post"), - "/v2/store/order", - c.PlaceOrder, + "DeleteOrder": Route{ + strings.ToUpper("Delete"), + "/v2/store/order/{orderId}", + c.DeleteOrder, }, } } -// DeleteOrder - Delete purchase order by ID -func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { - orderIdParam := chi.URLParam(r, "orderId") - if orderIdParam == "" { - c.errorHandler(w, r, &RequiredError{"orderId"}, nil) - return - } - result, err := c.service.DeleteOrder(r.Context(), orderIdParam) +// GetInventory - Returns pet inventories by status +func (c *StoreAPIController) GetInventory(w http.ResponseWriter, r *http.Request) { + result, err := c.service.GetInventory(r.Context()) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -91,9 +86,24 @@ func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetInventory - Returns pet inventories by status -func (c *StoreAPIController) GetInventory(w http.ResponseWriter, r *http.Request) { - result, err := c.service.GetInventory(r.Context()) +// PlaceOrder - Place an order for a pet +func (c *StoreAPIController) PlaceOrder(w http.ResponseWriter, r *http.Request) { + orderParam := Order{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&orderParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + if err := AssertOrderRequired(orderParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + if err := AssertOrderConstraints(orderParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.PlaceOrder(r.Context(), orderParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -125,24 +135,14 @@ func (c *StoreAPIController) GetOrderById(w http.ResponseWriter, r *http.Request _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// PlaceOrder - Place an order for a pet -func (c *StoreAPIController) PlaceOrder(w http.ResponseWriter, r *http.Request) { - orderParam := Order{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&orderParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertOrderRequired(orderParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - if err := AssertOrderConstraints(orderParam); err != nil { - c.errorHandler(w, r, err, nil) +// DeleteOrder - Delete purchase order by ID +func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { + orderIdParam := chi.URLParam(r, "orderId") + if orderIdParam == "" { + c.errorHandler(w, r, &RequiredError{"orderId"}, nil) return } - result, err := c.service.PlaceOrder(r.Context(), orderParam) + result, err := c.service.DeleteOrder(r.Context(), orderIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_store_service.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_store_service.go index 46671f7a9fd9..b42eb74efb91 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_store_service.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_store_service.go @@ -27,20 +27,6 @@ func NewStoreAPIService() *StoreAPIService { return &StoreAPIService{} } -// DeleteOrder - Delete purchase order by ID -func (s *StoreAPIService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) { - // TODO - update DeleteOrder with the required logic for this service method. - // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("DeleteOrder method not implemented") -} - // GetInventory - Returns pet inventories by status func (s *StoreAPIService) GetInventory(ctx context.Context) (ImplResponse, error) { // TODO - update GetInventory with the required logic for this service method. @@ -52,6 +38,20 @@ func (s *StoreAPIService) GetInventory(ctx context.Context) (ImplResponse, error return Response(http.StatusNotImplemented, nil), errors.New("GetInventory method not implemented") } +// PlaceOrder - Place an order for a pet +func (s *StoreAPIService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) { + // TODO - update PlaceOrder with the required logic for this service method. + // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ... + // return Response(200, Order{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("PlaceOrder method not implemented") +} + // GetOrderById - Find purchase order by ID func (s *StoreAPIService) GetOrderById(ctx context.Context, orderId int64) (ImplResponse, error) { // TODO - update GetOrderById with the required logic for this service method. @@ -69,16 +69,16 @@ func (s *StoreAPIService) GetOrderById(ctx context.Context, orderId int64) (Impl return Response(http.StatusNotImplemented, nil), errors.New("GetOrderById method not implemented") } -// PlaceOrder - Place an order for a pet -func (s *StoreAPIService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) { - // TODO - update PlaceOrder with the required logic for this service method. +// DeleteOrder - Delete purchase order by ID +func (s *StoreAPIService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) { + // TODO - update DeleteOrder with the required logic for this service method. // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ... - // return Response(200, Order{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("PlaceOrder method not implemented") + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeleteOrder method not implemented") } diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go index 1d28ab73b753..37cebbe7117d 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go @@ -66,16 +66,6 @@ func (c *UserAPIController) Routes() Routes { "/v2/user/createWithList", c.CreateUsersWithListInput, }, - "DeleteUser": Route{ - strings.ToUpper("Delete"), - "/v2/user/{username}", - c.DeleteUser, - }, - "GetUserByName": Route{ - strings.ToUpper("Get"), - "/v2/user/{username}", - c.GetUserByName, - }, "LoginUser": Route{ strings.ToUpper("Get"), "/v2/user/login", @@ -86,11 +76,21 @@ func (c *UserAPIController) Routes() Routes { "/v2/user/logout", c.LogoutUser, }, + "GetUserByName": Route{ + strings.ToUpper("Get"), + "/v2/user/{username}", + c.GetUserByName, + }, "UpdateUser": Route{ strings.ToUpper("Put"), "/v2/user/{username}", c.UpdateUser, }, + "DeleteUser": Route{ + strings.ToUpper("Delete"), + "/v2/user/{username}", + c.DeleteUser, + }, } } @@ -171,59 +171,6 @@ func (c *UserAPIController) CreateUsersWithListInput(w http.ResponseWriter, r *h _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// DeleteUser - Delete user -func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { - query, err := parseQuery(r.URL.RawQuery) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - usernameParam := chi.URLParam(r, "username") - if usernameParam == "" { - c.errorHandler(w, r, &RequiredError{"username"}, nil) - return - } - var booleanTestParam bool - if query.Has("boolean_test") { - param, err := parseBoolParameter( - query.Get("boolean_test"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "boolean_test", Err: err}, nil) - return - } - - booleanTestParam = param - } else { - } - result, err := c.service.DeleteUser(r.Context(), usernameParam, booleanTestParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// GetUserByName - Get user by user name -func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { - usernameParam := chi.URLParam(r, "username") - if usernameParam == "" { - c.errorHandler(w, r, &RequiredError{"username"}, nil) - return - } - result, err := c.service.GetUserByName(r.Context(), usernameParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - // LoginUser - Logs user into the system func (c *UserAPIController) LoginUser(w http.ResponseWriter, r *http.Request) { query, err := parseQuery(r.URL.RawQuery) @@ -341,6 +288,23 @@ func (c *UserAPIController) LogoutUser(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// GetUserByName - Get user by user name +func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { + usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } + result, err := c.service.GetUserByName(r.Context(), usernameParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // UpdateUser - Updated user func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { usernameParam := chi.URLParam(r, "username") @@ -372,3 +336,39 @@ func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { // If no error, encode the body and the result code _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } + +// DeleteUser - Delete user +func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { + query, err := parseQuery(r.URL.RawQuery) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } + var booleanTestParam bool + if query.Has("boolean_test") { + param, err := parseBoolParameter( + query.Get("boolean_test"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "boolean_test", Err: err}, nil) + return + } + + booleanTestParam = param + } else { + } + result, err := c.service.DeleteUser(r.Context(), usernameParam, booleanTestParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_user_service.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_user_service.go index 4be92131dc0b..c758b0ef57ba 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_user_service.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_user_service.go @@ -60,18 +60,29 @@ func (s *UserAPIService) CreateUsersWithListInput(ctx context.Context, user []Us return Response(http.StatusNotImplemented, nil), errors.New("CreateUsersWithListInput method not implemented") } -// DeleteUser - Delete user -func (s *UserAPIService) DeleteUser(ctx context.Context, username string, booleanTest bool) (ImplResponse, error) { - // TODO - update DeleteUser with the required logic for this service method. +// LoginUser - Logs user into the system +func (s *UserAPIService) LoginUser(ctx context.Context, username string, password string, int32Test int32, int64Test int64, float32Test float32, float64Test float64, booleanTest bool) (ImplResponse, error) { + // TODO - update LoginUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + // TODO: Uncomment the next line to return response Response(200, string{}) or use other options such as http.Ok ... + // return Response(200, string{}), nil + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil + return Response(http.StatusNotImplemented, nil), errors.New("LoginUser method not implemented") +} - return Response(http.StatusNotImplemented, nil), errors.New("DeleteUser method not implemented") +// LogoutUser - Logs out current logged in user session +func (s *UserAPIService) LogoutUser(ctx context.Context) (ImplResponse, error) { + // TODO - update LogoutUser with the required logic for this service method. + // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ... + // return Response(0, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented") } // GetUserByName - Get user by user name @@ -91,34 +102,23 @@ func (s *UserAPIService) GetUserByName(ctx context.Context, username string) (Im return Response(http.StatusNotImplemented, nil), errors.New("GetUserByName method not implemented") } -// LoginUser - Logs user into the system -func (s *UserAPIService) LoginUser(ctx context.Context, username string, password string, int32Test int32, int64Test int64, float32Test float32, float64Test float64, booleanTest bool) (ImplResponse, error) { - // TODO - update LoginUser with the required logic for this service method. +// UpdateUser - Updated user +func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) { + // TODO - update UpdateUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(200, string{}) or use other options such as http.Ok ... - // return Response(200, string{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("LoginUser method not implemented") -} - -// LogoutUser - Logs out current logged in user session -func (s *UserAPIService) LogoutUser(ctx context.Context) (ImplResponse, error) { - // TODO - update LogoutUser with the required logic for this service method. - // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ... - // return Response(0, nil),nil + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UpdateUser method not implemented") } -// UpdateUser - Updated user -func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) { - // TODO - update UpdateUser with the required logic for this service method. +// DeleteUser - Delete user +func (s *UserAPIService) DeleteUser(ctx context.Context, username string, booleanTest bool) (ImplResponse, error) { + // TODO - update DeleteUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... @@ -127,5 +127,5 @@ func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user U // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... // return Response(404, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("UpdateUser method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("DeleteUser method not implemented") } diff --git a/samples/openapi3/server/petstore/springboot-3/pom.xml b/samples/openapi3/server/petstore/springboot-3/pom.xml index e8636ac3ca09..54c3603cbc9d 100644 --- a/samples/openapi3/server/petstore/springboot-3/pom.xml +++ b/samples/openapi3/server/petstore/springboot-3/pom.xml @@ -10,8 +10,8 @@ ${java.version} ${java.version} UTF-8 - 2.2.0 - 5.3.1 + 2.6.0 + 5.17.14 org.springframework.boot diff --git a/samples/server/echo_api/erlang-server/.openapi-generator-ignore b/samples/server/echo_api/erlang-server/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/echo_api/erlang-server/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/echo_api/erlang-server/.openapi-generator/FILES b/samples/server/echo_api/erlang-server/.openapi-generator/FILES new file mode 100644 index 000000000000..3aa7956b7dab --- /dev/null +++ b/samples/server/echo_api/erlang-server/.openapi-generator/FILES @@ -0,0 +1,15 @@ +README.md +priv/openapi.json +rebar.config +src/openapi.app.src +src/openapi_api.erl +src/openapi_auth.erl +src/openapi_auth_handler.erl +src/openapi_body_handler.erl +src/openapi_form_handler.erl +src/openapi_header_handler.erl +src/openapi_logic_handler.erl +src/openapi_path_handler.erl +src/openapi_query_handler.erl +src/openapi_router.erl +src/openapi_server.erl diff --git a/samples/server/echo_api/erlang-server/.openapi-generator/VERSION b/samples/server/echo_api/erlang-server/.openapi-generator/VERSION new file mode 100644 index 000000000000..17f2442ff3bc --- /dev/null +++ b/samples/server/echo_api/erlang-server/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.9.0-SNAPSHOT diff --git a/samples/server/echo_api/erlang-server/README.md b/samples/server/echo_api/erlang-server/README.md new file mode 100644 index 000000000000..887f730062fe --- /dev/null +++ b/samples/server/echo_api/erlang-server/README.md @@ -0,0 +1,36 @@ +# OpenAPI server library for Erlang + +## Overview + +An Erlang server stub generated by [OpenAPI Generator](https://openapi-generator.tech) given an OpenAPI spec. + +Dependencies: Erlang OTP/27 and rebar3. Also: +- [Cowboy](https://hex.pm/packages/cowboy) +- [Ranch](https://hex.pm/packages/ranch) +- [Jesse](https://hex.pm/packages/jesse) + +## Prerequisites + +## Getting started +Use erlang-server with rebar3 + + 1, Create an application by using rebar3 + $ rebar3 new app http_server + + 2, Generate erlang-server project using openapi-generator + https://github.com/OpenAPITools/openapi-generator#2---getting-started + + 3, Copy erlang-server file to http_server project, and don't forget the 'priv' folder. + + 4, Start in the http_server project: + 1, Introduce the following line in the http_server_app:start(_Type, _Args) function + openapi_server:start(http_server, #{ip => {127,0,0,1}, port => 8080}) + 2, Compile your http_server project + $ rebar3 compile + 3, Start erlang virtual machine + $ rebar3 shell + 4, Start project + application:ensure_all_started(http_server). + +To implement your own business logic, create a module called `http_server_logic` that implements the +behaviour `openapi_logic_handler`. Refer to `openapi_logic_handler` documentation for details. diff --git a/samples/server/echo_api/erlang-server/pom.xml b/samples/server/echo_api/erlang-server/pom.xml new file mode 100644 index 000000000000..69d236d7cda2 --- /dev/null +++ b/samples/server/echo_api/erlang-server/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + org.openapitools + ErlangServerEchoTests + pom + 1.0-SNAPSHOT + Erlang Echo Server + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + compile-test + integration-test + + exec + + + rebar3 + + compile + + + + + + + + diff --git a/samples/server/echo_api/erlang-server/priv/openapi.json b/samples/server/echo_api/erlang-server/priv/openapi.json new file mode 100644 index 000000000000..be217ad12e5d --- /dev/null +++ b/samples/server/echo_api/erlang-server/priv/openapi.json @@ -0,0 +1,1282 @@ +{ + "openapi" : "3.0.3", + "info" : { + "contact" : { + "email" : "team@openapitools.org" + }, + "description" : "Echo Server API", + "license" : { + "name" : "Apache 2.0", + "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" + }, + "title" : "Echo Server API", + "version" : "0.1.0" + }, + "servers" : [ { + "url" : "http://localhost:3000/" + } ], + "paths" : { + "/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}" : { + "get" : { + "description" : "Test path parameter(s)", + "operationId" : "tests/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}", + "parameters" : [ { + "explode" : false, + "in" : "path", + "name" : "path_string", + "required" : true, + "schema" : { + "type" : "string" + }, + "style" : "simple" + }, { + "explode" : false, + "in" : "path", + "name" : "path_integer", + "required" : true, + "schema" : { + "type" : "integer" + }, + "style" : "simple" + }, { + "explode" : false, + "in" : "path", + "name" : "enum_nonref_string_path", + "required" : true, + "schema" : { + "enum" : [ "success", "failure", "unclassified" ], + "type" : "string" + }, + "style" : "simple" + }, { + "explode" : false, + "in" : "path", + "name" : "enum_ref_string_path", + "required" : true, + "schema" : { + "$ref" : "#/components/schemas/StringEnumRef" + }, + "style" : "simple" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test path parameter(s)", + "tags" : [ "path" ] + } + }, + "/form/integer/boolean/string" : { + "post" : { + "description" : "Test form parameter(s)", + "operationId" : "test/form/integer/boolean/string", + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "$ref" : "#/components/schemas/test_form_integer_boolean_string_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test form parameter(s)", + "tags" : [ "form" ] + } + }, + "/form/oneof" : { + "post" : { + "description" : "Test form parameter(s) for oneOf schema", + "operationId" : "test/form/oneof", + "requestBody" : { + "content" : { + "application/x-www-form-urlencoded" : { + "schema" : { + "$ref" : "#/components/schemas/test_form_oneof_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test form parameter(s) for oneOf schema", + "tags" : [ "form" ] + } + }, + "/form/object/multipart" : { + "post" : { + "description" : "Test form parameter(s) for multipart schema", + "operationId" : "test/form/object/multipart", + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/test_form_object_multipart_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test form parameter(s) for multipart schema", + "tags" : [ "form" ] + } + }, + "/header/integer/boolean/string/enums" : { + "get" : { + "description" : "Test header parameter(s)", + "operationId" : "test/header/integer/boolean/string/enums", + "parameters" : [ { + "explode" : true, + "in" : "header", + "name" : "integer_header", + "required" : false, + "schema" : { + "type" : "integer" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "header", + "name" : "boolean_header", + "required" : false, + "schema" : { + "type" : "boolean" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "header", + "name" : "string_header", + "required" : false, + "schema" : { + "type" : "string" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "header", + "name" : "enum_nonref_string_header", + "required" : false, + "schema" : { + "enum" : [ "success", "failure", "unclassified" ], + "type" : "string" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "header", + "name" : "enum_ref_string_header", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/StringEnumRef" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test header parameter(s)", + "tags" : [ "header" ] + } + }, + "/query/enum_ref_string" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/enum_ref_string", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "enum_nonref_string_query", + "required" : false, + "schema" : { + "enum" : [ "success", "failure", "unclassified" ], + "type" : "string" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "query", + "name" : "enum_ref_string_query", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/StringEnumRef" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/datetime/date/string" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/datetime/date/string", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "datetime_query", + "required" : false, + "schema" : { + "format" : "date-time", + "type" : "string" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "query", + "name" : "date_query", + "required" : false, + "schema" : { + "format" : "date", + "type" : "string" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "query", + "name" : "string_query", + "required" : false, + "schema" : { + "type" : "string" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/integer/boolean/string" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/integer/boolean/string", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "integer_query", + "required" : false, + "schema" : { + "type" : "integer" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "query", + "name" : "boolean_query", + "required" : false, + "schema" : { + "type" : "boolean" + }, + "style" : "form" + }, { + "explode" : true, + "in" : "query", + "name" : "string_query", + "required" : false, + "schema" : { + "type" : "string" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/style_form/explode_true/array_string" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/style_form/explode_true/array_string", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "query_object", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/test_query_style_form_explode_true_array_string_query_object_parameter" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/style_form/explode_false/array_integer" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/style_form/explode_false/array_integer", + "parameters" : [ { + "explode" : false, + "in" : "query", + "name" : "query_object", + "required" : false, + "schema" : { + "items" : { + "type" : "integer" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/style_form/explode_false/array_string" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/style_form/explode_false/array_string", + "parameters" : [ { + "explode" : false, + "in" : "query", + "name" : "query_object", + "required" : false, + "schema" : { + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/style_form/explode_true/object" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/style_form/explode_true/object", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "query_object", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/Pet" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/style_form/explode_true/object/allOf" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/style_form/explode_true/object/allOf", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "query_object", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/DataQuery" + }, + "style" : "form" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/style_deepObject/explode_true/object" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/style_deepObject/explode_true/object", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "query_object", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/Pet" + }, + "style" : "deepObject" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/query/style_deepObject/explode_true/object/allOf" : { + "get" : { + "description" : "Test query parameter(s)", + "operationId" : "test/query/style_deepObject/explode_true/object/allOf", + "parameters" : [ { + "explode" : true, + "in" : "query", + "name" : "query_object", + "required" : false, + "schema" : { + "$ref" : "#/components/schemas/test_query_style_deepObject_explode_true_object_allOf_query_object_parameter" + }, + "style" : "deepObject" + } ], + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test query parameter(s)", + "tags" : [ "query" ] + } + }, + "/body/application/octetstream/binary" : { + "post" : { + "description" : "Test body parameter(s)", + "operationId" : "test/body/application/octetstream/binary", + "requestBody" : { + "content" : { + "application/octet-stream" : { + "schema" : { + "format" : "binary", + "type" : "string" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test body parameter(s)", + "tags" : [ "body" ] + } + }, + "/echo/body/Pet" : { + "post" : { + "description" : "Test body parameter(s)", + "operationId" : "test/echo/body/Pet", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test body parameter(s)", + "tags" : [ "body" ] + } + }, + "/echo/body/allOf/Pet" : { + "post" : { + "description" : "Test body parameter(s)", + "operationId" : "test/echo/body/allOf/Pet", + "requestBody" : { + "$ref" : "#/components/requestBodies/AllOfPet" + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test body parameter(s)", + "tags" : [ "body" ] + } + }, + "/echo/body/Pet/response_string" : { + "post" : { + "description" : "Test empty response body", + "operationId" : "test/echo/body/Pet/response_string", + "requestBody" : { + "$ref" : "#/components/requestBodies/Pet" + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test empty response body", + "tags" : [ "body" ] + } + }, + "/echo/body/Tag/response_string" : { + "post" : { + "description" : "Test empty json (request body)", + "operationId" : "test/echo/body/Tag/response_string", + "requestBody" : { + "$ref" : "#/components/requestBodies/Tag" + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test empty json (request body)", + "tags" : [ "body" ] + } + }, + "/echo/body/FreeFormObject/response_string" : { + "post" : { + "description" : "Test free form object", + "operationId" : "test/echo/body/FreeFormObject/response_string", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "type" : "object" + } + } + }, + "description" : "Free form object" + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test free form object", + "tags" : [ "body" ] + } + }, + "/echo/body/string_enum" : { + "post" : { + "description" : "Test string enum response body", + "operationId" : "test/echo/body/string_enum", + "requestBody" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/StringEnumRef" + } + } + }, + "description" : "String enum" + }, + "responses" : { + "200" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/StringEnumRef" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test string enum response body", + "tags" : [ "body" ] + } + }, + "/binary/gif" : { + "post" : { + "description" : "Test binary (gif) response body", + "operationId" : "test/binary/gif", + "responses" : { + "200" : { + "content" : { + "image/gif" : { + "schema" : { + "format" : "binary", + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test binary (gif) response body", + "tags" : [ "body" ] + } + }, + "/body/application/octetstream/single_binary" : { + "post" : { + "description" : "Test single binary in multipart mime", + "operationId" : "test/body/multipart/formdata/single_binary", + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/test_body_multipart_formdata_single_binary_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test single binary in multipart mime", + "tags" : [ "body" ] + } + }, + "/body/application/octetstream/array_of_binary" : { + "post" : { + "description" : "Test array of binary in multipart mime", + "operationId" : "test/body/multipart/formdata/array_of_binary", + "requestBody" : { + "content" : { + "multipart/form-data" : { + "schema" : { + "$ref" : "#/components/schemas/test_body_multipart_formdata_array_of_binary_request" + } + } + } + }, + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "summary" : "Test array of binary in multipart mime", + "tags" : [ "body" ] + } + }, + "/auth/http/basic" : { + "post" : { + "description" : "To test HTTP basic authentication", + "operationId" : "test/auth/http/basic", + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "security" : [ { + "http_auth" : [ ] + } ], + "summary" : "To test HTTP basic authentication", + "tags" : [ "auth" ] + } + }, + "/auth/http/bearer" : { + "post" : { + "description" : "To test HTTP bearer authentication", + "operationId" : "test/auth/http/bearer", + "responses" : { + "200" : { + "content" : { + "text/plain" : { + "schema" : { + "type" : "string" + } + } + }, + "description" : "Successful operation" + } + }, + "security" : [ { + "http_bearer_auth" : [ ] + } ], + "summary" : "To test HTTP bearer authentication", + "tags" : [ "auth" ] + } + } + }, + "components" : { + "requestBodies" : { + "Pet" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + }, + "description" : "Pet object that needs to be added to the store" + }, + "AllOfPet" : { + "content" : { + "application/json" : { + "schema" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Pet" + } ] + } + } + }, + "description" : "Pet object that needs to be added to the store" + }, + "Tag" : { + "content" : { + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Tag" + } + } + }, + "description" : "Tag object" + } + }, + "schemas" : { + "Category" : { + "example" : { + "name" : "Dogs", + "id" : 1 + }, + "properties" : { + "id" : { + "example" : 1, + "format" : "int64", + "type" : "integer" + }, + "name" : { + "example" : "Dogs", + "type" : "string" + } + }, + "type" : "object", + "xml" : { + "name" : "category" + } + }, + "Tag" : { + "example" : { + "name" : "name", + "id" : 0 + }, + "properties" : { + "id" : { + "format" : "int64", + "type" : "integer" + }, + "name" : { + "type" : "string" + } + }, + "type" : "object", + "xml" : { + "name" : "tag" + } + }, + "Pet" : { + "example" : { + "photoUrls" : [ "photoUrls", "photoUrls" ], + "name" : "doggie", + "id" : 10, + "category" : { + "name" : "Dogs", + "id" : 1 + }, + "tags" : [ { + "name" : "name", + "id" : 0 + }, { + "name" : "name", + "id" : 0 + } ], + "status" : "available" + }, + "properties" : { + "id" : { + "example" : 10, + "format" : "int64", + "type" : "integer" + }, + "name" : { + "example" : "doggie", + "type" : "string" + }, + "category" : { + "$ref" : "#/components/schemas/Category" + }, + "photoUrls" : { + "items" : { + "type" : "string", + "xml" : { + "name" : "photoUrl" + } + }, + "type" : "array", + "xml" : { + "wrapped" : true + } + }, + "tags" : { + "items" : { + "$ref" : "#/components/schemas/Tag" + }, + "type" : "array", + "xml" : { + "wrapped" : true + } + }, + "status" : { + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ], + "type" : "string" + } + }, + "required" : [ "name", "photoUrls" ], + "type" : "object", + "xml" : { + "name" : "pet" + } + }, + "StringEnumRef" : { + "enum" : [ "success", "failure", "unclassified" ], + "type" : "string" + }, + "DefaultValue" : { + "description" : "to test the default value of properties", + "properties" : { + "array_string_enum_ref_default" : { + "default" : [ "success", "failure" ], + "items" : { + "$ref" : "#/components/schemas/StringEnumRef" + }, + "type" : "array" + }, + "array_string_enum_default" : { + "default" : [ "success", "failure" ], + "items" : { + "enum" : [ "success", "failure", "unclassified" ], + "type" : "string" + }, + "type" : "array" + }, + "array_string_default" : { + "default" : [ "failure", "skipped" ], + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "array_integer_default" : { + "default" : [ 1, 3 ], + "items" : { + "type" : "integer" + }, + "type" : "array" + }, + "array_string" : { + "items" : { + "type" : "string" + }, + "type" : "array" + }, + "array_string_nullable" : { + "items" : { + "type" : "string" + }, + "nullable" : true, + "type" : "array" + }, + "array_string_extension_nullable" : { + "items" : { + "type" : "string" + }, + "type" : "array", + "x-nullable" : true + }, + "string_nullable" : { + "nullable" : true, + "type" : "string" + } + }, + "type" : "object" + }, + "Bird" : { + "properties" : { + "size" : { + "type" : "string" + }, + "color" : { + "type" : "string" + } + }, + "type" : "object" + }, + "Query" : { + "properties" : { + "id" : { + "description" : "Query", + "format" : "int64", + "type" : "integer" + }, + "outcomes" : { + "default" : [ "SUCCESS", "FAILURE" ], + "items" : { + "enum" : [ "SUCCESS", "FAILURE", "SKIPPED" ], + "type" : "string" + }, + "type" : "array" + } + }, + "type" : "object", + "x-parent" : true + }, + "DataQuery" : { + "allOf" : [ { + "properties" : { + "suffix" : { + "description" : "test suffix", + "type" : "string" + }, + "text" : { + "description" : "Some text containing white spaces", + "example" : "Some text", + "type" : "string" + }, + "date" : { + "description" : "A date", + "format" : "date-time", + "type" : "string" + } + }, + "type" : "object" + }, { + "$ref" : "#/components/schemas/Query" + } ] + }, + "NumberPropertiesOnly" : { + "properties" : { + "number" : { + "type" : "number" + }, + "float" : { + "format" : "float", + "type" : "number" + }, + "double" : { + "format" : "double", + "maximum" : 50.2, + "minimum" : 0.8, + "type" : "number" + } + }, + "type" : "object" + }, + "test_form_integer_boolean_string_request" : { + "properties" : { + "integer_form" : { + "type" : "integer" + }, + "boolean_form" : { + "type" : "boolean" + }, + "string_form" : { + "type" : "string" + } + }, + "type" : "object" + }, + "test_form_oneof_request_oneOf" : { + "properties" : { + "form1" : { + "type" : "string" + }, + "form2" : { + "type" : "integer" + } + }, + "type" : "object" + }, + "test_form_oneof_request_oneOf_1" : { + "properties" : { + "form3" : { + "type" : "string" + }, + "form4" : { + "type" : "boolean" + } + }, + "type" : "object" + }, + "test_form_oneof_request" : { + "oneOf" : [ { + "$ref" : "#/components/schemas/test_form_oneof_request_oneOf" + }, { + "$ref" : "#/components/schemas/test_form_oneof_request_oneOf_1" + }, { + "$ref" : "#/components/schemas/Tag" + } ], + "type" : "object" + }, + "test_form_object_multipart_request_marker" : { + "properties" : { + "name" : { + "type" : "string" + } + }, + "type" : "object" + }, + "test_form_object_multipart_request" : { + "properties" : { + "marker" : { + "$ref" : "#/components/schemas/test_form_object_multipart_request_marker" + } + }, + "required" : [ "marker" ], + "type" : "object" + }, + "test_query_style_form_explode_true_array_string_query_object_parameter" : { + "properties" : { + "values" : { + "items" : { + "type" : "string" + }, + "type" : "array" + } + }, + "type" : "object" + }, + "test_query_style_deepObject_explode_true_object_allOf_query_object_parameter" : { + "allOf" : [ { + "$ref" : "#/components/schemas/Bird" + }, { + "$ref" : "#/components/schemas/Category" + } ] + }, + "test_body_multipart_formdata_single_binary_request" : { + "properties" : { + "my-file" : { + "format" : "binary", + "type" : "string" + } + }, + "type" : "object" + }, + "test_body_multipart_formdata_array_of_binary_request" : { + "properties" : { + "files" : { + "items" : { + "format" : "binary", + "type" : "string" + }, + "type" : "array" + } + }, + "required" : [ "files" ], + "type" : "object" + } + }, + "securitySchemes" : { + "http_auth" : { + "scheme" : "basic", + "type" : "http" + }, + "http_bearer_auth" : { + "scheme" : "bearer", + "type" : "http" + } + } + } +} diff --git a/samples/server/echo_api/erlang-server/rebar.config b/samples/server/echo_api/erlang-server/rebar.config new file mode 100644 index 000000000000..50cd482ca39b --- /dev/null +++ b/samples/server/echo_api/erlang-server/rebar.config @@ -0,0 +1,15 @@ +{minimum_otp_vsn, "27"}. + +{deps, [ + {cowboy, "2.12.0"}, + {ranch, "2.1.0"}, + {jesse, "1.8.1"} +]}. + +{dialyzer, + [{plt_extra_apps, [cowboy, cowlib, ranch, jesse]}, + {warnings, [missing_return, unknown]} +]}. + +{xref_checks, + [undefined_function_calls, deprecated_function_calls, deprecated_functions]}. diff --git a/samples/server/echo_api/erlang-server/src/openapi.app.src b/samples/server/echo_api/erlang-server/src/openapi.app.src new file mode 100644 index 000000000000..95507ce40e9c --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi.app.src @@ -0,0 +1,11 @@ +{application, + openapi, + [{description, + "Echo Server API"}, + {vsn, "1.0.0"}, + {registered, []}, + {applications, [kernel, stdlib, public_key, ssl, inets, ranch, cowboy]}, + {env, []}, + {modules, []}, + {licenses, ["Apache 2.0"]}, + {links, []}]}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_api.erl b/samples/server/echo_api/erlang-server/src/openapi_api.erl new file mode 100644 index 000000000000..b796f2df4a36 --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_api.erl @@ -0,0 +1,942 @@ +-module(openapi_api). +-moduledoc """ +This module offers an API for JSON schema validation, using `jesse` under the hood. + +If validation is desired, a jesse state can be loaded using `prepare_validator/1`, +and request and response can be validated using `populate_request/3` +and `validate_response/4` respectively. + +For example, the user-defined `Module:accept_callback/4` can be implemented as follows: +``` +-spec accept_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy:http_status(), cowboy:http_headers(), json:encode_value()}. +accept_callback(Class, OperationID, Req, Context) -> + ValidatorState = openapi_api:prepare_validator(), + case openapi_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = openapi_logic_handler:handle_request( + LogicHandler, + OperationID, + Req1, + maps:merge(State#state.context, Populated) + ), + _ = openapi_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = prepare_body(Code, Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. +``` +""". + +-export([prepare_validator/0, prepare_validator/1, prepare_validator/2]). +-export([populate_request/3, validate_response/4]). + +-ignore_xref([populate_request/3, validate_response/4]). +-ignore_xref([prepare_validator/0, prepare_validator/1, prepare_validator/2]). + +-type operation_id() :: atom(). +-type request_param() :: atom(). + +-export_type([operation_id/0]). + +-dialyzer({nowarn_function, [to_binary/1, to_list/1, validate_response_body/4]}). + +-type rule() :: + {type, binary} | + {type, integer} | + {type, float} | + {type, boolean} | + {type, date} | + {type, datetime} | + {enum, [atom()]} | + {max, Max :: number()} | + {exclusive_max, Max :: number()} | + {min, Min :: number()} | + {exclusive_min, Min :: number()} | + {max_length, MaxLength :: integer()} | + {min_length, MaxLength :: integer()} | + {pattern, Pattern :: string()} | + schema | + required | + not_required. + +-doc #{equiv => prepare_validator/2}. +-spec prepare_validator() -> jesse_state:state(). +prepare_validator() -> + prepare_validator(<<"http://json-schema.org/draft-06/schema#">>). + +-doc #{equiv => prepare_validator/2}. +-spec prepare_validator(binary()) -> jesse_state:state(). +prepare_validator(SchemaVer) -> + prepare_validator(get_openapi_path(), SchemaVer). + +-doc """ +Loads the JSON schema and the desired validation draft into a `t:jesse_state:state()`. +""". +-spec prepare_validator(file:name_all(), binary()) -> jesse_state:state(). +prepare_validator(OpenApiPath, SchemaVer) -> + {ok, FileContents} = file:read_file(OpenApiPath), + R = json:decode(FileContents), + jesse_state:new(R, [{default_schema_ver, SchemaVer}]). + +-doc """ +Automatically loads the entire body from the cowboy req +and validates the JSON body against the schema. +""". +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state()) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). + +-doc """ +Validates that the provided `Code` and `Body` comply with the `ValidatorState` schema +for the `OperationID` operation. +""". +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state()) -> + ok | {ok, term()} | [ok | {ok, term()}] | no_return(). +validate_response('TestAuthHttpBasic', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestAuthHttpBearer', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestBinaryGif', 200, Body, ValidatorState) -> + validate_response_body('file', 'file', Body, ValidatorState); +validate_response('TestBodyApplicationOctetstreamBinary', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestBodyMultipartFormdataArrayOfBinary', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestBodyMultipartFormdataSingleBinary', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestEchoBodyAllOfPet', 200, Body, ValidatorState) -> + validate_response_body('Pet', 'Pet', Body, ValidatorState); +validate_response('TestEchoBodyFreeFormObjectResponseString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestEchoBodyPet', 200, Body, ValidatorState) -> + validate_response_body('Pet', 'Pet', Body, ValidatorState); +validate_response('TestEchoBodyPetResponseString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestEchoBodyStringEnum', 200, Body, ValidatorState) -> + validate_response_body('StringEnumRef', 'StringEnumRef', Body, ValidatorState); +validate_response('TestEchoBodyTagResponseString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestFormIntegerBooleanString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestFormObjectMultipart', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestFormOneof', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestHeaderIntegerBooleanStringEnums', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestEnumRefString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryDatetimeDateString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryIntegerBooleanString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryStyleDeepObjectExplodeTrueObject', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryStyleDeepObjectExplodeTrueObjectAllOf', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryStyleFormExplodeFalseArrayInteger', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryStyleFormExplodeFalseArrayString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryStyleFormExplodeTrueArrayString', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryStyleFormExplodeTrueObject', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('TestQueryStyleFormExplodeTrueObjectAllOf', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. + +%%% +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. +request_params('TestAuthHttpBasic') -> + [ + ]; +request_params('TestAuthHttpBearer') -> + [ + ]; +request_params('TestBinaryGif') -> + [ + ]; +request_params('TestBodyApplicationOctetstreamBinary') -> + [ + 'file' + ]; +request_params('TestBodyMultipartFormdataArrayOfBinary') -> + [ + 'files' + ]; +request_params('TestBodyMultipartFormdataSingleBinary') -> + [ + 'my-file' + ]; +request_params('TestEchoBodyAllOfPet') -> + [ + 'Pet' + ]; +request_params('TestEchoBodyFreeFormObjectResponseString') -> + [ + 'object' + ]; +request_params('TestEchoBodyPet') -> + [ + 'Pet' + ]; +request_params('TestEchoBodyPetResponseString') -> + [ + 'Pet' + ]; +request_params('TestEchoBodyStringEnum') -> + [ + 'binary' + ]; +request_params('TestEchoBodyTagResponseString') -> + [ + 'Tag' + ]; +request_params('TestFormIntegerBooleanString') -> + [ + 'integer_form', + 'boolean_form', + 'string_form' + ]; +request_params('TestFormObjectMultipart') -> + [ + 'marker' + ]; +request_params('TestFormOneof') -> + [ + 'form1', + 'form2', + 'form3', + 'form4', + 'id', + 'name' + ]; +request_params('TestHeaderIntegerBooleanStringEnums') -> + [ + 'integer_header', + 'boolean_header', + 'string_header', + 'enum_nonref_string_header', + 'enum_ref_string_header' + ]; +request_params('TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}') -> + [ + 'path_string', + 'path_integer', + 'enum_nonref_string_path', + 'enum_ref_string_path' + ]; +request_params('TestEnumRefString') -> + [ + 'enum_nonref_string_query', + 'enum_ref_string_query' + ]; +request_params('TestQueryDatetimeDateString') -> + [ + 'datetime_query', + 'date_query', + 'string_query' + ]; +request_params('TestQueryIntegerBooleanString') -> + [ + 'integer_query', + 'boolean_query', + 'string_query' + ]; +request_params('TestQueryStyleDeepObjectExplodeTrueObject') -> + [ + 'query_object' + ]; +request_params('TestQueryStyleDeepObjectExplodeTrueObjectAllOf') -> + [ + 'query_object' + ]; +request_params('TestQueryStyleFormExplodeFalseArrayInteger') -> + [ + 'query_object' + ]; +request_params('TestQueryStyleFormExplodeFalseArrayString') -> + [ + 'query_object' + ]; +request_params('TestQueryStyleFormExplodeTrueArrayString') -> + [ + 'query_object' + ]; +request_params('TestQueryStyleFormExplodeTrueObject') -> + [ + 'query_object' + ]; +request_params('TestQueryStyleFormExplodeTrueObjectAllOf') -> + [ + 'query_object' + ]; +request_params(_) -> + error(unknown_operation). + +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> + #{source => qs_val | binding | header | body, rules => [rule()]}. +request_param_info('TestBodyApplicationOctetstreamBinary', 'file') -> + #{ + source => body, + rules => [ + {type, binary}, + schema, + not_required + ] + }; +request_param_info('TestBodyMultipartFormdataArrayOfBinary', 'files') -> + #{ + source => body, + rules => [ + required + ] + }; +request_param_info('TestBodyMultipartFormdataSingleBinary', 'my-file') -> + #{ + source => body, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestEchoBodyAllOfPet', 'Pet') -> + #{ + source => body, + rules => [ + schema, + not_required + ] + }; +request_param_info('TestEchoBodyFreeFormObjectResponseString', 'object') -> + #{ + source => body, + rules => [ + schema, + not_required + ] + }; +request_param_info('TestEchoBodyPet', 'Pet') -> + #{ + source => body, + rules => [ + schema, + not_required + ] + }; +request_param_info('TestEchoBodyPetResponseString', 'Pet') -> + #{ + source => body, + rules => [ + schema, + not_required + ] + }; +request_param_info('TestEchoBodyStringEnum', 'binary') -> + #{ + source => body, + rules => [ + schema, + not_required + ] + }; +request_param_info('TestEchoBodyTagResponseString', 'Tag') -> + #{ + source => body, + rules => [ + schema, + not_required + ] + }; +request_param_info('TestFormIntegerBooleanString', 'integer_form') -> + #{ + source => body, + rules => [ + {type, integer}, + not_required + ] + }; +request_param_info('TestFormIntegerBooleanString', 'boolean_form') -> + #{ + source => body, + rules => [ + {type, boolean}, + not_required + ] + }; +request_param_info('TestFormIntegerBooleanString', 'string_form') -> + #{ + source => body, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestFormObjectMultipart', 'marker') -> + #{ + source => body, + rules => [ + required + ] + }; +request_param_info('TestFormOneof', 'form1') -> + #{ + source => body, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestFormOneof', 'form2') -> + #{ + source => body, + rules => [ + {type, integer}, + not_required + ] + }; +request_param_info('TestFormOneof', 'form3') -> + #{ + source => body, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestFormOneof', 'form4') -> + #{ + source => body, + rules => [ + {type, boolean}, + not_required + ] + }; +request_param_info('TestFormOneof', 'id') -> + #{ + source => body, + rules => [ + {type, integer}, + not_required + ] + }; +request_param_info('TestFormOneof', 'name') -> + #{ + source => body, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestHeaderIntegerBooleanStringEnums', 'integer_header') -> + #{ + source => header, + rules => [ + {type, integer}, + not_required + ] + }; +request_param_info('TestHeaderIntegerBooleanStringEnums', 'boolean_header') -> + #{ + source => header, + rules => [ + {type, boolean}, + not_required + ] + }; +request_param_info('TestHeaderIntegerBooleanStringEnums', 'string_header') -> + #{ + source => header, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestHeaderIntegerBooleanStringEnums', 'enum_nonref_string_header') -> + #{ + source => header, + rules => [ + {type, binary}, + {enum, ['success', 'failure', 'unclassified'] }, + not_required + ] + }; +request_param_info('TestHeaderIntegerBooleanStringEnums', 'enum_ref_string_header') -> + #{ + source => header, + rules => [ + not_required + ] + }; +request_param_info('TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}', 'path_string') -> + #{ + source => binding, + rules => [ + {type, binary}, + required + ] + }; +request_param_info('TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}', 'path_integer') -> + #{ + source => binding, + rules => [ + {type, integer}, + required + ] + }; +request_param_info('TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}', 'enum_nonref_string_path') -> + #{ + source => binding, + rules => [ + {type, binary}, + {enum, ['success', 'failure', 'unclassified'] }, + required + ] + }; +request_param_info('TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}', 'enum_ref_string_path') -> + #{ + source => binding, + rules => [ + required + ] + }; +request_param_info('TestEnumRefString', 'enum_nonref_string_query') -> + #{ + source => qs_val, + rules => [ + {type, binary}, + {enum, ['success', 'failure', 'unclassified'] }, + not_required + ] + }; +request_param_info('TestEnumRefString', 'enum_ref_string_query') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info('TestQueryDatetimeDateString', 'datetime_query') -> + #{ + source => qs_val, + rules => [ + {type, datetime}, + not_required + ] + }; +request_param_info('TestQueryDatetimeDateString', 'date_query') -> + #{ + source => qs_val, + rules => [ + {type, date}, + not_required + ] + }; +request_param_info('TestQueryDatetimeDateString', 'string_query') -> + #{ + source => qs_val, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestQueryIntegerBooleanString', 'integer_query') -> + #{ + source => qs_val, + rules => [ + {type, integer}, + not_required + ] + }; +request_param_info('TestQueryIntegerBooleanString', 'boolean_query') -> + #{ + source => qs_val, + rules => [ + {type, boolean}, + not_required + ] + }; +request_param_info('TestQueryIntegerBooleanString', 'string_query') -> + #{ + source => qs_val, + rules => [ + {type, binary}, + not_required + ] + }; +request_param_info('TestQueryStyleDeepObjectExplodeTrueObject', 'query_object') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info('TestQueryStyleDeepObjectExplodeTrueObjectAllOf', 'query_object') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info('TestQueryStyleFormExplodeFalseArrayInteger', 'query_object') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info('TestQueryStyleFormExplodeFalseArrayString', 'query_object') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info('TestQueryStyleFormExplodeTrueArrayString', 'query_object') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info('TestQueryStyleFormExplodeTrueObject', 'query_object') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info('TestQueryStyleFormExplodeTrueObjectAllOf', 'query_object') -> + #{ + source => qs_val, + rules => [ + not_required + ] + }; +request_param_info(OperationID, Name) -> + error({unknown_param, OperationID, Name}). + +populate_request_params(_, [], Req, _, Model) -> + {ok, Model, Req}; +populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> + case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of + {ok, K, V, Req} -> + populate_request_params(OperationID, T, Req, ValidatorState, maps:put(K, V, Model)); + Error -> + Error + end. + +populate_request_param(OperationID, Name, Req0, ValidatorState) -> + #{rules := Rules, source := Source} = request_param_info(OperationID, Name), + case get_value(Source, Name, Req0) of + {error, Reason, Req} -> + {error, Reason, Req}; + {Value, Req} -> + case prepare_param(Rules, Name, Value, ValidatorState) of + {ok, Result} -> {ok, Name, Result, Req}; + {error, Reason} -> + {error, Reason, Req} + end + end. + +-include_lib("kernel/include/logger.hrl"). + +validate_response_body(list, ReturnBaseType, Body, ValidatorState) -> + [ + validate(schema, ReturnBaseType, Item, ValidatorState) + || Item <- Body]; + +validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> + validate(schema, ReturnBaseType, Body, ValidatorState). + +validate(Rule = required, Name, Value, _ValidatorState) -> + case Value of + undefined -> validation_error(Rule, Name); + _ -> ok + end; +validate(not_required, _Name, _Value, _ValidatorState) -> + ok; +validate(_, _Name, undefined, _ValidatorState) -> + ok; +validate(Rule = {type, integer}, Name, Value, _ValidatorState) -> + try + {ok, to_int(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; +validate(Rule = {type, float}, Name, Value, _ValidatorState) -> + try + {ok, to_float(Value)} + catch + error:badarg -> + validation_error(Rule, Name) + end; +validate(Rule = {type, binary}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(_Rule = {type, boolean}, _Name, Value, _ValidatorState) when is_boolean(Value) -> + {ok, Value}; +validate(Rule = {type, boolean}, Name, Value, _ValidatorState) -> + V = binary_to_lower(Value), + try + case binary_to_existing_atom(V, utf8) of + B when is_boolean(B) -> {ok, B}; + _ -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; +validate(Rule = {type, date}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {type, datetime}, Name, Value, _ValidatorState) -> + case is_binary(Value) of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> + try + FormattedValue = erlang:binary_to_existing_atom(Value, utf8), + case lists:member(FormattedValue, Values) of + true -> {ok, FormattedValue}; + false -> validation_error(Rule, Name) + end + catch + error:badarg -> + validation_error(Rule, Name) + end; +validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> + case Value =< Max of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> + case Value > ExclusiveMax of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> + case Value >= Min of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> + case Value =< ExclusiveMin of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> + case size(Value) =< MaxLength of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> + case size(Value) >= MinLength of + true -> ok; + false -> validation_error(Rule, Name) + end; +validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> + {ok, MP} = re:compile(Pattern), + case re:run(Value, MP) of + {match, _} -> ok; + _ -> validation_error(Rule, Name) + end; +validate(Rule = schema, Name, Value, ValidatorState) -> + Definition = list_to_binary("#/components/schemas/" ++ to_list(Name)), + try + _ = validate_with_schema(Value, Definition, ValidatorState), + ok + catch + throw:[{schema_invalid, _, Error} | _] -> + Info = #{ + type => schema_invalid, + error => Error + }, + validation_error(Rule, Name, Info); + throw:[{data_invalid, Schema, Error, _, Path} | _] -> + Info = #{ + type => data_invalid, + error => Error, + schema => Schema, + path => Path + }, + validation_error(Rule, Name, Info) + end; +validate(Rule, Name, _Value, _ValidatorState) -> + ?LOG_INFO(#{what => "Cannot validate rule", name => Name, rule => Rule}), + error({unknown_validation_rule, Rule}). + +-spec validation_error(Rule :: any(), Name :: any()) -> no_return(). +validation_error(ViolatedRule, Name) -> + validation_error(ViolatedRule, Name, #{}). + +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{_ := _}) -> no_return(). +validation_error(ViolatedRule, Name, Info) -> + throw({wrong_param, Name, ViolatedRule, Info}). + +-spec get_value(body | qs_val | header | binding, Name :: any(), Req0 :: cowboy_req:req()) -> + {Value :: any(), Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. +get_value(body, _Name, Req0) -> + {ok, Body, Req} = cowboy_req:read_body(Req0), + case prepare_body(Body) of + {error, Reason} -> + {error, Reason, Req}; + Value -> + {Value, Req} + end; +get_value(qs_val, Name, Req) -> + QS = cowboy_req:parse_qs(Req), + Value = get_opt(to_qs(Name), QS), + {Value, Req}; +get_value(header, Name, Req) -> + Headers = cowboy_req:headers(Req), + Value = maps:get(to_header(Name), Headers, undefined), + {Value, Req}; +get_value(binding, Name, Req) -> + Value = cowboy_req:binding(to_binding(Name), Req), + {Value, Req}. + +prepare_body(<<>>) -> + <<>>; +prepare_body(Body) -> + try + json:decode(Body) + catch + error:_ -> + {error, {invalid_body, not_json, Body}} + end. + +validate_with_schema(Body, Definition, ValidatorState) -> + jesse_schema_validator:validate_with_state( + [{<<"$ref">>, Definition}], + Body, + ValidatorState + ). + +prepare_param(Rules, Name, Value, ValidatorState) -> + try + Result = lists:foldl( + fun(Rule, Acc) -> + case validate(Rule, Name, Acc, ValidatorState) of + ok -> Acc; + {ok, Prepared} -> Prepared + end + end, + Value, + Rules + ), + {ok, Result} + catch + throw:Reason -> + {error, Reason} + end. + +-spec to_binary(iodata() | atom() | number()) -> binary(). +to_binary(V) when is_binary(V) -> V; +to_binary(V) when is_list(V) -> iolist_to_binary(V); +to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); +to_binary(V) when is_integer(V) -> integer_to_binary(V); +to_binary(V) when is_float(V) -> float_to_binary(V). + +-spec to_list(iodata() | atom() | number()) -> binary(). +to_list(V) when is_list(V) -> V; +to_list(V) when is_binary(V) -> binary_to_list(V); +to_list(V) when is_atom(V) -> atom_to_list(V); +to_list(V) when is_integer(V) -> integer_to_list(V); +to_list(V) when is_float(V) -> float_to_list(V). + +-spec to_float(iodata()) -> float(). +to_float(V) -> + binary_to_float(iolist_to_binary([V])). + +-spec to_int(integer() | binary() | list()) -> integer(). +to_int(Data) when is_integer(Data) -> + Data; +to_int(Data) when is_binary(Data) -> + binary_to_integer(Data); +to_int(Data) when is_list(Data) -> + list_to_integer(Data). + +-spec to_header(iodata() | atom() | number()) -> binary(). +to_header(Name) -> + to_binary(string:lowercase(to_binary(Name))). + +binary_to_lower(V) when is_binary(V) -> + string:lowercase(V). + +-spec to_qs(iodata() | atom() | number()) -> binary(). +to_qs(Name) -> + to_binary(Name). + +-spec to_binding(iodata() | atom() | number()) -> atom(). +to_binding(Name) -> + Prepared = to_binary(Name), + binary_to_existing_atom(Prepared, utf8). + +-spec get_opt(any(), []) -> any(). +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> Value; + false -> Default + end. + +get_openapi_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join(priv_dir(AppName), "openapi.json"). + +-include_lib("kernel/include/file.hrl"). + +-spec priv_dir(Application :: atom()) -> file:name_all(). +priv_dir(AppName) -> + case code:priv_dir(AppName) of + Value when is_list(Value) -> + Value ++ "/"; + _Error -> + select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) + end. + +select_priv_dir(Paths) -> + case lists:dropwhile(fun test_priv_dir/1, Paths) of + [Path | _] -> Path; + _ -> exit(no_priv_dir) + end. + +test_priv_dir(Path) -> + case file:read_file_info(Path) of + {ok, #file_info{type = directory}} -> + false; + _ -> + true + end. diff --git a/samples/server/echo_api/erlang-server/src/openapi_auth.erl b/samples/server/echo_api/erlang-server/src/openapi_auth.erl new file mode 100644 index 000000000000..0e7beb1132c4 --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_auth.erl @@ -0,0 +1,45 @@ +-module(openapi_auth). + +-export([authorize_api_key/5]). + +-spec authorize_api_key(openapi_logic_handler:api_key_callback(), + openapi_api:operation_id(), + header | qs_val, + iodata() | atom(), + cowboy_req:req()) -> + {true, openapi_logic_handler:context(), cowboy_req:req()} | + {false, binary(), cowboy_req:req()}. +authorize_api_key(Handler, OperationID, From, KeyParam, Req0) -> + {ApiKey, Req} = get_api_key(From, KeyParam, Req0), + case ApiKey of + undefined -> + AuthHeader = <<>>, + {false, AuthHeader, Req}; + _ -> + case Handler(OperationID, ApiKey) of + {true, Context} -> + {true, Context, Req}; + {false, AuthHeader} -> + {false, AuthHeader, Req} + end + end. + +get_api_key(header, KeyParam, Req) -> + Headers = cowboy_req:headers(Req), + {maps:get(KeyParam, Headers, undefined), Req}; +get_api_key(qs_val, KeyParam, Req) -> + QS = cowboy_req:parse_qs(Req), + {get_opt(KeyParam, QS), Req}. + +-spec get_opt(any(), []) -> any(). +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> + Value; + false -> + Default + end. diff --git a/samples/server/echo_api/erlang-server/src/openapi_auth_handler.erl b/samples/server/echo_api/erlang-server/src/openapi_auth_handler.erl new file mode 100644 index 000000000000..d0d456a7f2bf --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_auth_handler.erl @@ -0,0 +1,126 @@ +%% basic handler +-module(openapi_auth_handler). + +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + +%% Cowboy REST callbacks +-export([init/2]). +-export([allowed_methods/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([valid_content_headers/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). + +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). + +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). + +-type state() :: #state{}. + +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> + Method = cowboy_req:method(Req), + OperationID = maps:get(Method, Operations, undefined), + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, + {cowboy_rest, Req, State}. + +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'TestAuthHttpBasic'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestAuthHttpBearer'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req0, + #state{operation_id = 'TestAuthHttpBasic' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} + end; +is_authorized(Req0, + #state{operation_id = 'TestAuthHttpBearer' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} + end; +is_authorized(Req, State) -> + {true, Req, State}. + +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'TestAuthHttpBasic'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestAuthHttpBearer'} = State) -> + {[], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. + +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'TestAuthHttpBasic'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestAuthHttpBearer'} = State) -> + {true, Req, State}; +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'TestAuthHttpBasic'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestAuthHttpBearer'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. + +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +delete_resource(Req, State) -> + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(auth, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(auth, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_body_handler.erl b/samples/server/echo_api/erlang-server/src/openapi_body_handler.erl new file mode 100644 index 000000000000..72e5a3685932 --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_body_handler.erl @@ -0,0 +1,206 @@ +%% basic handler +-module(openapi_body_handler). + +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + +%% Cowboy REST callbacks +-export([init/2]). +-export([allowed_methods/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([valid_content_headers/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). + +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). + +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). + +-type state() :: #state{}. + +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> + Method = cowboy_req:method(Req), + OperationID = maps:get(Method, Operations, undefined), + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, + {cowboy_rest, Req, State}. + +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'TestBinaryGif'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestBodyApplicationOctetstreamBinary'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestBodyMultipartFormdataArrayOfBinary'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestBodyMultipartFormdataSingleBinary'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestEchoBodyAllOfPet'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestEchoBodyFreeFormObjectResponseString'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestEchoBodyPet'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestEchoBodyPetResponseString'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestEchoBodyStringEnum'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestEchoBodyTagResponseString'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req, State) -> + {true, Req, State}. + +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'TestBinaryGif'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestBodyApplicationOctetstreamBinary'} = State) -> + {[ + {<<"application/octet-stream">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestBodyMultipartFormdataArrayOfBinary'} = State) -> + {[ + {<<"multipart/form-data">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestBodyMultipartFormdataSingleBinary'} = State) -> + {[ + {<<"multipart/form-data">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestEchoBodyAllOfPet'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestEchoBodyFreeFormObjectResponseString'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestEchoBodyPet'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestEchoBodyPetResponseString'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestEchoBodyStringEnum'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestEchoBodyTagResponseString'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. + +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'TestBinaryGif'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestBodyApplicationOctetstreamBinary'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestBodyMultipartFormdataArrayOfBinary'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestBodyMultipartFormdataSingleBinary'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestEchoBodyAllOfPet'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestEchoBodyFreeFormObjectResponseString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestEchoBodyPet'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestEchoBodyPetResponseString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestEchoBodyStringEnum'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestEchoBodyTagResponseString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'TestBinaryGif'} = State) -> + {[ + {<<"image/gif">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestBodyApplicationOctetstreamBinary'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestBodyMultipartFormdataArrayOfBinary'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestBodyMultipartFormdataSingleBinary'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestEchoBodyAllOfPet'} = State) -> + {[ + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestEchoBodyFreeFormObjectResponseString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestEchoBodyPet'} = State) -> + {[ + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestEchoBodyPetResponseString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestEchoBodyStringEnum'} = State) -> + {[ + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestEchoBodyTagResponseString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. + +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +delete_resource(Req, State) -> + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(body, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(body, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_form_handler.erl b/samples/server/echo_api/erlang-server/src/openapi_form_handler.erl new file mode 100644 index 000000000000..721ae35d798c --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_form_handler.erl @@ -0,0 +1,124 @@ +%% basic handler +-module(openapi_form_handler). + +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + +%% Cowboy REST callbacks +-export([init/2]). +-export([allowed_methods/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([valid_content_headers/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). + +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). + +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). + +-type state() :: #state{}. + +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> + Method = cowboy_req:method(Req), + OperationID = maps:get(Method, Operations, undefined), + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, + {cowboy_rest, Req, State}. + +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'TestFormIntegerBooleanString'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestFormObjectMultipart'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestFormOneof'} = State) -> + {[<<"POST">>], Req, State}; +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req, State) -> + {true, Req, State}. + +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'TestFormIntegerBooleanString'} = State) -> + {[ + {<<"application/x-www-form-urlencoded">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestFormObjectMultipart'} = State) -> + {[ + {<<"multipart/form-data">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestFormOneof'} = State) -> + {[ + {<<"application/x-www-form-urlencoded">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. + +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'TestFormIntegerBooleanString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestFormObjectMultipart'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestFormOneof'} = State) -> + {true, Req, State}; +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'TestFormIntegerBooleanString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestFormObjectMultipart'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestFormOneof'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. + +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +delete_resource(Req, State) -> + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(form, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(form, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_header_handler.erl b/samples/server/echo_api/erlang-server/src/openapi_header_handler.erl new file mode 100644 index 000000000000..0508e765aea8 --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_header_handler.erl @@ -0,0 +1,98 @@ +%% basic handler +-module(openapi_header_handler). + +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + +%% Cowboy REST callbacks +-export([init/2]). +-export([allowed_methods/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([valid_content_headers/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). + +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). + +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). + +-type state() :: #state{}. + +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> + Method = cowboy_req:method(Req), + OperationID = maps:get(Method, Operations, undefined), + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, + {cowboy_rest, Req, State}. + +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'TestHeaderIntegerBooleanStringEnums'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req, State) -> + {true, Req, State}. + +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'TestHeaderIntegerBooleanStringEnums'} = State) -> + {[], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. + +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'TestHeaderIntegerBooleanStringEnums'} = State) -> + {true, Req, State}; +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'TestHeaderIntegerBooleanStringEnums'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. + +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +delete_resource(Req, State) -> + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(header, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(header, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_logic_handler.erl b/samples/server/echo_api/erlang-server/src/openapi_logic_handler.erl new file mode 100644 index 000000000000..d90faf6ae3b8 --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_logic_handler.erl @@ -0,0 +1,63 @@ +-module(openapi_logic_handler). + +-include_lib("kernel/include/logger.hrl"). + +-type accept_callback_return() :: + stop + | boolean() + | {true, iodata()} + | {created, iodata()} + | {see_other, iodata()}. +-type api_key_callback() :: + fun((openapi_api:operation_id(), binary()) -> {true, context()} | {false, iodata()}). +-type accept_callback() :: + fun((atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}). +-type provide_callback() :: + fun((atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}). +-type context() :: #{_ := _}. + +-export_type([context/0, api_key_callback/0, + accept_callback_return/0, accept_callback/0, provide_callback/0]). + +-optional_callbacks([api_key_callback/2]). + +-callback api_key_callback(openapi_api:operation_id(), binary()) -> + {true, context()} | {false, iodata()}. + +-callback accept_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}. + +-callback provide_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}. + +-export([api_key_callback/2, accept_callback/4, provide_callback/4]). +-ignore_xref([api_key_callback/2, accept_callback/4, provide_callback/4]). + +-spec api_key_callback(openapi_api:operation_id(), binary()) -> {true, #{}}. +api_key_callback(OperationID, ApiKey) -> + ?LOG_ERROR(#{what => "Got not implemented api_key_callback request", + operation_id => OperationID, + api_key => ApiKey}), + {true, #{}}. + +-spec accept_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}. +accept_callback(Class, OperationID, Req, Context) -> + ?LOG_ERROR(#{what => "Got not implemented request to process", + class => Class, + operation_id => OperationID, + request => Req, + context => Context}), + {false, Req, Context}. + +-spec provide_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}. +provide_callback(Class, OperationID, Req, Context) -> + ?LOG_ERROR(#{what => "Got not implemented request to process", + class => Class, + operation_id => OperationID, + request => Req, + context => Context}), + {<<>>, Req, Context}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_path_handler.erl b/samples/server/echo_api/erlang-server/src/openapi_path_handler.erl new file mode 100644 index 000000000000..c80fbd508ac9 --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_path_handler.erl @@ -0,0 +1,98 @@ +%% basic handler +-module(openapi_path_handler). + +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + +%% Cowboy REST callbacks +-export([init/2]). +-export([allowed_methods/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([valid_content_headers/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). + +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). + +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). + +-type state() :: #state{}. + +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> + Method = cowboy_req:method(Req), + OperationID = maps:get(Method, Operations, undefined), + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, + {cowboy_rest, Req, State}. + +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req, State) -> + {true, Req, State}. + +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}'} = State) -> + {[], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. + +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}'} = State) -> + {true, Req, State}; +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. + +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +delete_resource(Req, State) -> + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(path, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(path, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_query_handler.erl b/samples/server/echo_api/erlang-server/src/openapi_query_handler.erl new file mode 100644 index 000000000000..fd298dc1ee8b --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_query_handler.erl @@ -0,0 +1,188 @@ +%% basic handler +-module(openapi_query_handler). + +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + +%% Cowboy REST callbacks +-export([init/2]). +-export([allowed_methods/2]). +-export([content_types_accepted/2]). +-export([content_types_provided/2]). +-export([delete_resource/2]). +-export([is_authorized/2]). +-export([valid_content_headers/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). + +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). + +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). + +-type state() :: #state{}. + +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> + Method = cowboy_req:method(Req), + OperationID = maps:get(Method, Operations, undefined), + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, + {cowboy_rest, Req, State}. + +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'TestEnumRefString'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryDatetimeDateString'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryIntegerBooleanString'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObject'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObjectAllOf'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayInteger'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayString'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueArrayString'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObject'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObjectAllOf'} = State) -> + {[<<"GET">>], Req, State}; +allowed_methods(Req, State) -> + {[], Req, State}. + +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req, State) -> + {true, Req, State}. + +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'TestEnumRefString'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryDatetimeDateString'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryIntegerBooleanString'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObject'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObjectAllOf'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayInteger'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayString'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueArrayString'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObject'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObjectAllOf'} = State) -> + {[], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. + +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'TestEnumRefString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryDatetimeDateString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryIntegerBooleanString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObject'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObjectAllOf'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayInteger'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueArrayString'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObject'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObjectAllOf'} = State) -> + {true, Req, State}; +valid_content_headers(Req, State) -> + {false, Req, State}. + +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'TestEnumRefString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryDatetimeDateString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryIntegerBooleanString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObject'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryStyleDeepObjectExplodeTrueObjectAllOf'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayInteger'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryStyleFormExplodeFalseArrayString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueArrayString'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObject'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'TestQueryStyleFormExplodeTrueObjectAllOf'} = State) -> + {[ + {<<"text/plain">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. + +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +delete_resource(Req, State) -> + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(query, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(query, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/echo_api/erlang-server/src/openapi_router.erl b/samples/server/echo_api/erlang-server/src/openapi_router.erl new file mode 100644 index 000000000000..84cee5a6256d --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_router.erl @@ -0,0 +1,172 @@ +-module(openapi_router). + +-export([get_paths/1]). + +-type method() :: binary(). +-type operations() :: #{method() => openapi_api:operation_id()}. +-type init_opts() :: {operations(), module()}. + +-export_type([init_opts/0]). + +-spec get_paths(LogicHandler :: module()) -> cowboy_router:routes(). +get_paths(LogicHandler) -> + PreparedPaths = maps:fold( + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, [], group_paths() + ), + [{'_', [{P, H, {O, LogicHandler}} || {P, H, O} <- PreparedPaths]}]. + +group_paths() -> + maps:fold( + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, #{}, get_operations()). + +get_operations() -> + #{ + 'TestAuthHttpBasic' => #{ + path => "/auth/http/basic", + method => <<"POST">>, + handler => 'openapi_auth_handler' + }, + 'TestAuthHttpBearer' => #{ + path => "/auth/http/bearer", + method => <<"POST">>, + handler => 'openapi_auth_handler' + }, + 'TestBinaryGif' => #{ + path => "/binary/gif", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestBodyApplicationOctetstreamBinary' => #{ + path => "/body/application/octetstream/binary", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestBodyMultipartFormdataArrayOfBinary' => #{ + path => "/body/application/octetstream/array_of_binary", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestBodyMultipartFormdataSingleBinary' => #{ + path => "/body/application/octetstream/single_binary", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestEchoBodyAllOfPet' => #{ + path => "/echo/body/allOf/Pet", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestEchoBodyFreeFormObjectResponseString' => #{ + path => "/echo/body/FreeFormObject/response_string", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestEchoBodyPet' => #{ + path => "/echo/body/Pet", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestEchoBodyPetResponseString' => #{ + path => "/echo/body/Pet/response_string", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestEchoBodyStringEnum' => #{ + path => "/echo/body/string_enum", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestEchoBodyTagResponseString' => #{ + path => "/echo/body/Tag/response_string", + method => <<"POST">>, + handler => 'openapi_body_handler' + }, + 'TestFormIntegerBooleanString' => #{ + path => "/form/integer/boolean/string", + method => <<"POST">>, + handler => 'openapi_form_handler' + }, + 'TestFormObjectMultipart' => #{ + path => "/form/object/multipart", + method => <<"POST">>, + handler => 'openapi_form_handler' + }, + 'TestFormOneof' => #{ + path => "/form/oneof", + method => <<"POST">>, + handler => 'openapi_form_handler' + }, + 'TestHeaderIntegerBooleanStringEnums' => #{ + path => "/header/integer/boolean/string/enums", + method => <<"GET">>, + handler => 'openapi_header_handler' + }, + 'TestsPathString{pathString}Integer{pathInteger}{enumNonrefStringPath}{enumRefStringPath}' => #{ + path => "/path/string/:path_string/integer/:path_integer/:enum_nonref_string_path/:enum_ref_string_path", + method => <<"GET">>, + handler => 'openapi_path_handler' + }, + 'TestEnumRefString' => #{ + path => "/query/enum_ref_string", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryDatetimeDateString' => #{ + path => "/query/datetime/date/string", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryIntegerBooleanString' => #{ + path => "/query/integer/boolean/string", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryStyleDeepObjectExplodeTrueObject' => #{ + path => "/query/style_deepObject/explode_true/object", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryStyleDeepObjectExplodeTrueObjectAllOf' => #{ + path => "/query/style_deepObject/explode_true/object/allOf", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryStyleFormExplodeFalseArrayInteger' => #{ + path => "/query/style_form/explode_false/array_integer", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryStyleFormExplodeFalseArrayString' => #{ + path => "/query/style_form/explode_false/array_string", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryStyleFormExplodeTrueArrayString' => #{ + path => "/query/style_form/explode_true/array_string", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryStyleFormExplodeTrueObject' => #{ + path => "/query/style_form/explode_true/object", + method => <<"GET">>, + handler => 'openapi_query_handler' + }, + 'TestQueryStyleFormExplodeTrueObjectAllOf' => #{ + path => "/query/style_form/explode_true/object/allOf", + method => <<"GET">>, + handler => 'openapi_query_handler' + } + }. diff --git a/samples/server/echo_api/erlang-server/src/openapi_server.erl b/samples/server/echo_api/erlang-server/src/openapi_server.erl new file mode 100644 index 000000000000..0cd992fe69d2 --- /dev/null +++ b/samples/server/echo_api/erlang-server/src/openapi_server.erl @@ -0,0 +1,43 @@ +-module(openapi_server). + +-define(DEFAULT_LOGIC_HANDLER, openapi_logic_handler). + +-export([start/2]). +-ignore_xref([start/2]). + +-spec start(term(), #{transport => tcp | ssl, + transport_opts => ranch:opts(), + protocol_opts => cowboy:opts(), + logic_handler => module()}) -> + {ok, pid()} | {error, any()}. +start(ID, Params) -> + Transport = maps:get(transport, Params, tcp), + TransportOpts = maps:get(transport_opts, Params, #{}), + ProtocolOpts = maps:get(procotol_opts, Params, #{}), + LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), + CowboyOpts = get_cowboy_config(LogicHandler, ProtocolOpts), + case Transport of + ssl -> + cowboy:start_tls(ID, TransportOpts, CowboyOpts); + tcp -> + cowboy:start_clear(ID, TransportOpts, CowboyOpts) + end. + +get_cowboy_config(LogicHandler, ExtraOpts) -> + DefaultOpts = get_default_opts(LogicHandler), + maps:fold(fun get_cowboy_config/3, DefaultOpts, ExtraOpts). + +get_cowboy_config(env, #{dispatch := _Dispatch} = Env, AccIn) -> + maps:put(env, Env, AccIn); +get_cowboy_config(env, NewEnv, #{env := OldEnv} = AccIn) -> + Env = maps:merge(OldEnv, NewEnv), + maps:put(env, Env, AccIn); +get_cowboy_config(Key, Value, AccIn) -> + maps:put(Key, Value, AccIn). + +get_default_dispatch(LogicHandler) -> + Paths = openapi_router:get_paths(LogicHandler), + #{dispatch => cowboy_router:compile(Paths)}. + +get_default_opts(LogicHandler) -> + #{env => get_default_dispatch(LogicHandler)}. diff --git a/samples/server/petstore/erlang-server/.openapi-generator/FILES b/samples/server/petstore/erlang-server/.openapi-generator/FILES index 9c50202b9359..ac7922db6682 100644 --- a/samples/server/petstore/erlang-server/.openapi-generator/FILES +++ b/samples/server/petstore/erlang-server/.openapi-generator/FILES @@ -4,11 +4,9 @@ rebar.config src/openapi.app.src src/openapi_api.erl src/openapi_auth.erl -src/openapi_default_logic_handler.erl src/openapi_logic_handler.erl src/openapi_pet_handler.erl src/openapi_router.erl src/openapi_server.erl src/openapi_store_handler.erl src/openapi_user_handler.erl -src/openapi_utils.erl diff --git a/samples/server/petstore/erlang-server/README.md b/samples/server/petstore/erlang-server/README.md index 5d36ca07576b..887f730062fe 100644 --- a/samples/server/petstore/erlang-server/README.md +++ b/samples/server/petstore/erlang-server/README.md @@ -4,54 +4,33 @@ An Erlang server stub generated by [OpenAPI Generator](https://openapi-generator.tech) given an OpenAPI spec. -Dependency: [Cowboy](https://github.com/ninenines/cowboy) +Dependencies: Erlang OTP/27 and rebar3. Also: +- [Cowboy](https://hex.pm/packages/cowboy) +- [Ranch](https://hex.pm/packages/ranch) +- [Jesse](https://hex.pm/packages/jesse) ## Prerequisites -TODO - ## Getting started -Use erlang-server with erlang.mk - - 1, Create an application by using erlang.mk - $ mkdir http_server - $ cd http_server - $ wget https://erlang.mk/erlang.mk - $ make -f erlang.mk bootstrap bootstrap-rel - $ make run - - 2, Modify the Makefile in the http_server directory to the following to introduce the dependency library: - PROJECT = http_server - PROJECT_DESCRIPTION = New project - PROJECT_VERSION = 0.1.0 - - DEPS = cowboy jesse jsx - dep_cowboy_commit = 2.5.0 - dep_jesse_commit = 1.5.2 - dep_jsx_commit = 2.9.0 - DEP_PLUGINS = cowboy jesse jsx - - PACKAGES += rfc3339 - pkg_rfc3339_name = rfc3339 - pkg_rfc3339_description = an erlang/elixir rfc3339 lib - pkg_rfc3339_homepage = https://github.com/talentdeficit/rfc3339 - pkg_rfc3339_fetch = git - pkg_rfc3339_repo = https://github.com/talentdeficit/rfc3339 - pkg_rfc3339_commit = master - - include erlang.mk - - 3, Generate erlang-server project using openapi-generator +Use erlang-server with rebar3 + + 1, Create an application by using rebar3 + $ rebar3 new app http_server + + 2, Generate erlang-server project using openapi-generator https://github.com/OpenAPITools/openapi-generator#2---getting-started - 4, Copy erlang-server file to http_server project,Don't forget the 'priv' folder. + 3, Copy erlang-server file to http_server project, and don't forget the 'priv' folder. - 5, Start in the http_server project: + 4, Start in the http_server project: 1, Introduce the following line in the http_server_app:start(_Type, _Args) function - openapi_server:start(http_server, #{ip=>{127,0,0,1}, port=>8080, net_opts=>[]}) - 2, Compilation http_server project - $ make + openapi_server:start(http_server, #{ip => {127,0,0,1}, port => 8080}) + 2, Compile your http_server project + $ rebar3 compile 3, Start erlang virtual machine - $erl -pa ./deps/cowboy/ebin -pa ./deps/cowlib/ebin -pa ./deps/ranch/ebin -pa ./deps/jsx/ebin -pa ./deps/jesse/ebin -pa ./deps/rfc3339/ebin -pa ./ebin + $ rebar3 shell 4, Start project application:ensure_all_started(http_server). + +To implement your own business logic, create a module called `http_server_logic` that implements the +behaviour `openapi_logic_handler`. Refer to `openapi_logic_handler` documentation for details. diff --git a/samples/server/petstore/erlang-server/rebar.config b/samples/server/petstore/erlang-server/rebar.config index 743b108f384a..50cd482ca39b 100644 --- a/samples/server/petstore/erlang-server/rebar.config +++ b/samples/server/petstore/erlang-server/rebar.config @@ -1,6 +1,15 @@ +{minimum_otp_vsn, "27"}. + {deps, [ - {cowboy, {git, "https://github.com/ninenines/cowboy.git", {tag, "2.8.0"}}}, - {rfc3339, {git, "https://github.com/talentdeficit/rfc3339.git", {tag, "master"}}}, - {jsx, {git, "https://github.com/talentdeficit/jsx.git", {tag, "v3.1.0"}}}, - {jesse, {git, "https://github.com/for-GET/jesse.git", {tag, "1.5.6"}}} + {cowboy, "2.12.0"}, + {ranch, "2.1.0"}, + {jesse, "1.8.1"} ]}. + +{dialyzer, + [{plt_extra_apps, [cowboy, cowlib, ranch, jesse]}, + {warnings, [missing_return, unknown]} +]}. + +{xref_checks, + [undefined_function_calls, deprecated_function_calls, deprecated_functions]}. diff --git a/samples/server/petstore/erlang-server/src/openapi.app.src b/samples/server/petstore/erlang-server/src/openapi.app.src index 99859823b68e..0172627719b7 100644 --- a/samples/server/petstore/erlang-server/src/openapi.app.src +++ b/samples/server/petstore/erlang-server/src/openapi.app.src @@ -1,19 +1,11 @@ -{application, openapi, [ - {description, "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters."}, - {vsn, "1.0.0"}, - {registered, []}, - {applications, [ - kernel, - stdlib, - ssl, - inets, - jsx, - jesse, - cowboy - ]}, - {env, [ - ]}, - {modules, []}, - {licenses, ["Apache-2.0"]}, - {links, []} -]}. +{application, + openapi, + [{description, + "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters."}, + {vsn, "1.0.0"}, + {registered, []}, + {applications, [kernel, stdlib, public_key, ssl, inets, ranch, cowboy]}, + {env, []}, + {modules, []}, + {licenses, ["Apache-2.0"]}, + {links, []}]}. diff --git a/samples/server/petstore/erlang-server/src/openapi_api.erl b/samples/server/petstore/erlang-server/src/openapi_api.erl index 8b9cb84eaa49..16ad18e97823 100644 --- a/samples/server/petstore/erlang-server/src/openapi_api.erl +++ b/samples/server/petstore/erlang-server/src/openapi_api.erl @@ -1,404 +1,491 @@ -module(openapi_api). +-moduledoc """ +This module offers an API for JSON schema validation, using `jesse` under the hood. + +If validation is desired, a jesse state can be loaded using `prepare_validator/1`, +and request and response can be validated using `populate_request/3` +and `validate_response/4` respectively. + +For example, the user-defined `Module:accept_callback/4` can be implemented as follows: +``` +-spec accept_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy:http_status(), cowboy:http_headers(), json:encode_value()}. +accept_callback(Class, OperationID, Req, Context) -> + ValidatorState = openapi_api:prepare_validator(), + case openapi_api:populate_request(OperationID, Req0, ValidatorState) of + {ok, Populated, Req1} -> + {Code, Headers, Body} = openapi_logic_handler:handle_request( + LogicHandler, + OperationID, + Req1, + maps:merge(State#state.context, Populated) + ), + _ = openapi_api:validate_response( + OperationID, + Code, + Body, + ValidatorState + ), + PreparedBody = prepare_body(Code, Body), + Response = {ok, {Code, Headers, PreparedBody}}, + process_response(Response, Req1, State); + {error, Reason, Req1} -> + process_response({error, Reason}, Req1, State) + end. +``` +""". + +-export([prepare_validator/0, prepare_validator/1, prepare_validator/2]). +-export([populate_request/3, validate_response/4]). --export([request_params/1]). --export([request_param_info/2]). --export([populate_request/3]). --export([validate_response/4]). -%% exported to silence openapi complains --export([get_value/3, validate_response_body/4]). +-ignore_xref([populate_request/3, validate_response/4]). +-ignore_xref([prepare_validator/0, prepare_validator/1, prepare_validator/2]). -type operation_id() :: atom(). -type request_param() :: atom(). -export_type([operation_id/0]). --spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. +-dialyzer({nowarn_function, [to_binary/1, to_list/1, validate_response_body/4]}). + +-type rule() :: + {type, binary} | + {type, integer} | + {type, float} | + {type, boolean} | + {type, date} | + {type, datetime} | + {enum, [atom()]} | + {max, Max :: number()} | + {exclusive_max, Max :: number()} | + {min, Min :: number()} | + {exclusive_min, Min :: number()} | + {max_length, MaxLength :: integer()} | + {min_length, MaxLength :: integer()} | + {pattern, Pattern :: string()} | + schema | + required | + not_required. +-doc #{equiv => prepare_validator/2}. +-spec prepare_validator() -> jesse_state:state(). +prepare_validator() -> + prepare_validator(<<"http://json-schema.org/draft-06/schema#">>). + +-doc #{equiv => prepare_validator/2}. +-spec prepare_validator(binary()) -> jesse_state:state(). +prepare_validator(SchemaVer) -> + prepare_validator(get_openapi_path(), SchemaVer). + +-doc """ +Loads the JSON schema and the desired validation draft into a `t:jesse_state:state()`. +""". +-spec prepare_validator(file:name_all(), binary()) -> jesse_state:state(). +prepare_validator(OpenApiPath, SchemaVer) -> + {ok, FileContents} = file:read_file(OpenApiPath), + R = json:decode(FileContents), + jesse_state:new(R, [{default_schema_ver, SchemaVer}]). + +-doc """ +Automatically loads the entire body from the cowboy req +and validates the JSON body against the schema. +""". +-spec populate_request( + OperationID :: operation_id(), + Req :: cowboy_req:req(), + ValidatorState :: jesse_state:state()) -> + {ok, Model :: #{}, Req :: cowboy_req:req()} | + {error, Reason :: any(), Req :: cowboy_req:req()}. +populate_request(OperationID, Req, ValidatorState) -> + Params = request_params(OperationID), + populate_request_params(OperationID, Params, Req, ValidatorState, #{}). +-doc """ +Validates that the provided `Code` and `Body` comply with the `ValidatorState` schema +for the `OperationID` operation. +""". +-spec validate_response( + OperationID :: operation_id(), + Code :: 200..599, + Body :: jesse:json_term(), + ValidatorState :: jesse_state:state()) -> + ok | {ok, term()} | [ok | {ok, term()}] | no_return(). +validate_response('AddPet', 200, Body, ValidatorState) -> + validate_response_body('Pet', 'Pet', Body, ValidatorState); +validate_response('AddPet', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeletePet', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('FindPetsByStatus', 200, Body, ValidatorState) -> + validate_response_body('list', 'Pet', Body, ValidatorState); +validate_response('FindPetsByStatus', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('FindPetsByTags', 200, Body, ValidatorState) -> + validate_response_body('list', 'Pet', Body, ValidatorState); +validate_response('FindPetsByTags', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetPetById', 200, Body, ValidatorState) -> + validate_response_body('Pet', 'Pet', Body, ValidatorState); +validate_response('GetPetById', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetPetById', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePet', 200, Body, ValidatorState) -> + validate_response_body('Pet', 'Pet', Body, ValidatorState); +validate_response('UpdatePet', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePet', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePet', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdatePetWithForm', 405, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UploadFile', 200, Body, ValidatorState) -> + validate_response_body('ApiResponse', 'ApiResponse', Body, ValidatorState); +validate_response('DeleteOrder', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeleteOrder', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetInventory', 200, Body, ValidatorState) -> + validate_response_body('map', 'integer', Body, ValidatorState); +validate_response('GetOrderById', 200, Body, ValidatorState) -> + validate_response_body('Order', 'Order', Body, ValidatorState); +validate_response('GetOrderById', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetOrderById', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('PlaceOrder', 200, Body, ValidatorState) -> + validate_response_body('Order', 'Order', Body, ValidatorState); +validate_response('PlaceOrder', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('CreateUser', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('CreateUsersWithArrayInput', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('CreateUsersWithListInput', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeleteUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('DeleteUser', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetUserByName', 200, Body, ValidatorState) -> + validate_response_body('User', 'User', Body, ValidatorState); +validate_response('GetUserByName', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('GetUserByName', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('LoginUser', 200, Body, ValidatorState) -> + validate_response_body('binary', 'string', Body, ValidatorState); +validate_response('LoginUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('LogoutUser', 0, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdateUser', 400, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response('UpdateUser', 404, Body, ValidatorState) -> + validate_response_body('', '', Body, ValidatorState); +validate_response(_OperationID, _Code, _Body, _ValidatorState) -> + ok. + +%%% +-spec request_params(OperationID :: operation_id()) -> [Param :: request_param()]. request_params('AddPet') -> [ 'Pet' ]; - request_params('DeletePet') -> [ 'petId', 'api_key' ]; - request_params('FindPetsByStatus') -> [ 'status' ]; - request_params('FindPetsByTags') -> [ 'tags' ]; - request_params('GetPetById') -> [ 'petId' ]; - request_params('UpdatePet') -> [ 'Pet' ]; - request_params('UpdatePetWithForm') -> [ 'petId', 'name', 'status' ]; - request_params('UploadFile') -> [ 'petId', 'additionalMetadata', 'file' ]; - - request_params('DeleteOrder') -> [ 'orderId' ]; - request_params('GetInventory') -> [ ]; - request_params('GetOrderById') -> [ 'orderId' ]; - request_params('PlaceOrder') -> [ 'Order' ]; - - request_params('CreateUser') -> [ 'User' ]; - request_params('CreateUsersWithArrayInput') -> [ 'list' ]; - request_params('CreateUsersWithListInput') -> [ 'list' ]; - request_params('DeleteUser') -> [ 'username' ]; - request_params('GetUserByName') -> [ 'username' ]; - request_params('LoginUser') -> [ 'username', 'password' ]; - request_params('LogoutUser') -> [ ]; - request_params('UpdateUser') -> [ 'username', 'User' ]; - request_params(_) -> error(unknown_operation). --type rule() :: - {type, 'binary'} | - {type, 'integer'} | - {type, 'float'} | - {type, 'binary'} | - {type, 'boolean'} | - {type, 'date'} | - {type, 'datetime'} | - {enum, [atom()]} | - {max, Max :: number()} | - {exclusive_max, Max :: number()} | - {min, Min :: number()} | - {exclusive_min, Min :: number()} | - {max_length, MaxLength :: integer()} | - {min_length, MaxLength :: integer()} | - {pattern, Pattern :: string()} | - schema | - required | - not_required. - --spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> #{ - source => qs_val | binding | header | body, - rules => [rule()] -}. - - - +-spec request_param_info(OperationID :: operation_id(), Name :: request_param()) -> + #{source => qs_val | binding | header | body, rules => [rule()]}. request_param_info('AddPet', 'Pet') -> #{ - source => body, + source => body, rules => [ schema, required ] }; - request_param_info('DeletePet', 'petId') -> #{ - source => binding , + source => binding, rules => [ - {type, 'integer'}, + {type, integer}, required ] }; - request_param_info('DeletePet', 'api_key') -> #{ - source => header, + source => header, rules => [ - {type, 'binary'}, + {type, binary}, not_required ] }; - request_param_info('FindPetsByStatus', 'status') -> #{ - source => qs_val , + source => qs_val, rules => [ {enum, ['available', 'pending', 'sold'] }, required ] }; - request_param_info('FindPetsByTags', 'tags') -> #{ - source => qs_val , + source => qs_val, rules => [ required ] }; - request_param_info('GetPetById', 'petId') -> #{ - source => binding , + source => binding, rules => [ - {type, 'integer'}, + {type, integer}, required ] }; - request_param_info('UpdatePet', 'Pet') -> #{ - source => body, + source => body, rules => [ schema, required ] }; - request_param_info('UpdatePetWithForm', 'petId') -> #{ - source => binding , + source => binding, rules => [ - {type, 'integer'}, + {type, integer}, required ] }; - request_param_info('UpdatePetWithForm', 'name') -> #{ - source => body, + source => body, rules => [ - {type, 'binary'}, + {type, binary}, not_required ] }; - request_param_info('UpdatePetWithForm', 'status') -> #{ - source => body, + source => body, rules => [ - {type, 'binary'}, + {type, binary}, not_required ] }; - request_param_info('UploadFile', 'petId') -> #{ - source => binding , + source => binding, rules => [ - {type, 'integer'}, + {type, integer}, required ] }; - request_param_info('UploadFile', 'additionalMetadata') -> #{ - source => body, + source => body, rules => [ - {type, 'binary'}, + {type, binary}, not_required ] }; - request_param_info('UploadFile', 'file') -> #{ - source => body, + source => body, rules => [ - {type, 'binary'}, + {type, binary}, not_required ] }; - - request_param_info('DeleteOrder', 'orderId') -> #{ - source => binding , + source => binding, rules => [ - {type, 'binary'}, + {type, binary}, required ] }; - request_param_info('GetOrderById', 'orderId') -> #{ - source => binding , + source => binding, rules => [ - {type, 'integer'}, - {max, 5 }, - {min, 1 }, + {type, integer}, + {max, 5}, + {min, 1}, required ] }; - request_param_info('PlaceOrder', 'Order') -> #{ - source => body, + source => body, rules => [ schema, required ] }; - - request_param_info('CreateUser', 'User') -> #{ - source => body, + source => body, rules => [ schema, required ] }; - request_param_info('CreateUsersWithArrayInput', 'list') -> #{ - source => body, + source => body, rules => [ schema, required ] }; - request_param_info('CreateUsersWithListInput', 'list') -> #{ - source => body, + source => body, rules => [ schema, required ] }; - request_param_info('DeleteUser', 'username') -> #{ - source => binding , + source => binding, rules => [ - {type, 'binary'}, + {type, binary}, required ] }; - request_param_info('GetUserByName', 'username') -> #{ - source => binding , + source => binding, rules => [ - {type, 'binary'}, + {type, binary}, required ] }; - request_param_info('LoginUser', 'username') -> #{ - source => qs_val , + source => qs_val, rules => [ - {type, 'binary'}, - {pattern, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" }, + {type, binary}, + {pattern, "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$"}, required ] }; - request_param_info('LoginUser', 'password') -> #{ - source => qs_val , + source => qs_val, rules => [ - {type, 'binary'}, + {type, binary}, required ] }; - request_param_info('UpdateUser', 'username') -> #{ - source => binding , + source => binding, rules => [ - {type, 'binary'}, + {type, binary}, required ] }; - request_param_info('UpdateUser', 'User') -> #{ - source => body, + source => body, rules => [ schema, required ] }; - request_param_info(OperationID, Name) -> error({unknown_param, OperationID, Name}). --spec populate_request( - OperationID :: operation_id(), - Req :: cowboy_req:req(), - ValidatorState :: jesse_state:state() -) -> - {ok, Model :: #{}, Req :: cowboy_req:req()} | - {error, Reason :: any(), Req :: cowboy_req:req()}. - -populate_request(OperationID, Req, ValidatorState) -> - Params = request_params(OperationID), - populate_request_params(OperationID, Params, Req, ValidatorState, #{}). - populate_request_params(_, [], Req, _, Model) -> {ok, Model, Req}; - populate_request_params(OperationID, [FieldParams | T], Req0, ValidatorState, Model) -> case populate_request_param(OperationID, FieldParams, Req0, ValidatorState) of {ok, K, V, Req} -> @@ -420,115 +507,9 @@ populate_request_param(OperationID, Name, Req0, ValidatorState) -> end end. --spec validate_response( - OperationID :: operation_id(), - Code :: 200..599, - Body :: jesse:json_term(), - ValidatorState :: jesse_state:state() -) -> ok | no_return(). - - -validate_response('AddPet', 200, Body, ValidatorState) -> - validate_response_body('Pet', 'Pet', Body, ValidatorState); -validate_response('AddPet', 405, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('DeletePet', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('FindPetsByStatus', 200, Body, ValidatorState) -> - validate_response_body('list', 'Pet', Body, ValidatorState); -validate_response('FindPetsByStatus', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('FindPetsByTags', 200, Body, ValidatorState) -> - validate_response_body('list', 'Pet', Body, ValidatorState); -validate_response('FindPetsByTags', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); +-include_lib("kernel/include/logger.hrl"). -validate_response('GetPetById', 200, Body, ValidatorState) -> - validate_response_body('Pet', 'Pet', Body, ValidatorState); -validate_response('GetPetById', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('GetPetById', 404, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('UpdatePet', 200, Body, ValidatorState) -> - validate_response_body('Pet', 'Pet', Body, ValidatorState); -validate_response('UpdatePet', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('UpdatePet', 404, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('UpdatePet', 405, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('UpdatePetWithForm', 405, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('UploadFile', 200, Body, ValidatorState) -> - validate_response_body('ApiResponse', 'ApiResponse', Body, ValidatorState); - - -validate_response('DeleteOrder', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('DeleteOrder', 404, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('GetInventory', 200, Body, ValidatorState) -> - validate_response_body('map', 'integer', Body, ValidatorState); - -validate_response('GetOrderById', 200, Body, ValidatorState) -> - validate_response_body('Order', 'Order', Body, ValidatorState); -validate_response('GetOrderById', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('GetOrderById', 404, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('PlaceOrder', 200, Body, ValidatorState) -> - validate_response_body('Order', 'Order', Body, ValidatorState); -validate_response('PlaceOrder', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - - -validate_response('CreateUser', 0, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('CreateUsersWithArrayInput', 0, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('CreateUsersWithListInput', 0, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('DeleteUser', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('DeleteUser', 404, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('GetUserByName', 200, Body, ValidatorState) -> - validate_response_body('User', 'User', Body, ValidatorState); -validate_response('GetUserByName', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('GetUserByName', 404, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('LoginUser', 200, Body, ValidatorState) -> - validate_response_body('binary', 'string', Body, ValidatorState); -validate_response('LoginUser', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('LogoutUser', 0, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - -validate_response('UpdateUser', 400, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); -validate_response('UpdateUser', 404, Body, ValidatorState) -> - validate_response_body('', '', Body, ValidatorState); - - -validate_response(_OperationID, _Code, _Body, _ValidatorState) -> - ok. - -validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> +validate_response_body(list, ReturnBaseType, Body, ValidatorState) -> [ validate(schema, ReturnBaseType, Item, ValidatorState) || Item <- Body]; @@ -536,45 +517,37 @@ validate_response_body('list', ReturnBaseType, Body, ValidatorState) -> validate_response_body(_, ReturnBaseType, Body, ValidatorState) -> validate(schema, ReturnBaseType, Body, ValidatorState). -%%% validate(Rule = required, Name, Value, _ValidatorState) -> case Value of undefined -> validation_error(Rule, Name); _ -> ok end; - validate(not_required, _Name, _Value, _ValidatorState) -> ok; - validate(_, _Name, undefined, _ValidatorState) -> ok; - -validate(Rule = {type, 'integer'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, integer}, Name, Value, _ValidatorState) -> try - {ok, openapi_utils:to_int(Value)} + {ok, to_int(Value)} catch error:badarg -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'float'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, float}, Name, Value, _ValidatorState) -> try - {ok, openapi_utils:to_float(Value)} + {ok, to_float(Value)} catch error:badarg -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'binary'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, binary}, Name, Value, _ValidatorState) -> case is_binary(Value) of true -> ok; false -> validation_error(Rule, Name) end; - -validate(_Rule = {type, 'boolean'}, _Name, Value, _ValidatorState) when is_boolean(Value) -> +validate(_Rule = {type, boolean}, _Name, Value, _ValidatorState) when is_boolean(Value) -> {ok, Value}; - -validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, boolean}, Name, Value, _ValidatorState) -> V = binary_to_lower(Value), try case binary_to_existing_atom(V, utf8) of @@ -585,19 +558,16 @@ validate(Rule = {type, 'boolean'}, Name, Value, _ValidatorState) -> error:badarg -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'date'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, date}, Name, Value, _ValidatorState) -> case is_binary(Value) of true -> ok; false -> validation_error(Rule, Name) end; - -validate(Rule = {type, 'datetime'}, Name, Value, _ValidatorState) -> +validate(Rule = {type, datetime}, Name, Value, _ValidatorState) -> case is_binary(Value) of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> try FormattedValue = erlang:binary_to_existing_atom(Value, utf8), @@ -609,52 +579,44 @@ validate(Rule = {enum, Values}, Name, Value, _ValidatorState) -> error:badarg -> validation_error(Rule, Name) end; - validate(Rule = {max, Max}, Name, Value, _ValidatorState) -> case Value =< Max of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {exclusive_max, ExclusiveMax}, Name, Value, _ValidatorState) -> case Value > ExclusiveMax of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {min, Min}, Name, Value, _ValidatorState) -> case Value >= Min of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {exclusive_min, ExclusiveMin}, Name, Value, _ValidatorState) -> case Value =< ExclusiveMin of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {max_length, MaxLength}, Name, Value, _ValidatorState) -> case size(Value) =< MaxLength of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {min_length, MinLength}, Name, Value, _ValidatorState) -> case size(Value) >= MinLength of true -> ok; false -> validation_error(Rule, Name) end; - validate(Rule = {pattern, Pattern}, Name, Value, _ValidatorState) -> {ok, MP} = re:compile(Pattern), case re:run(Value, MP) of {match, _} -> ok; _ -> validation_error(Rule, Name) end; - validate(Rule = schema, Name, Value, ValidatorState) -> - Definition = list_to_binary("#/components/schemas/" ++ openapi_utils:to_list(Name)), + Definition = list_to_binary("#/components/schemas/" ++ to_list(Name)), try _ = validate_with_schema(Value, Definition, ValidatorState), ok @@ -674,18 +636,15 @@ validate(Rule = schema, Name, Value, ValidatorState) -> }, validation_error(Rule, Name, Info) end; - validate(Rule, Name, _Value, _ValidatorState) -> - error_logger:info_msg("Can't validate ~p with ~p", [Name, Rule]), + ?LOG_INFO(#{what => "Cannot validate rule", name => Name, rule => Rule}), error({unknown_validation_rule, Rule}). -spec validation_error(Rule :: any(), Name :: any()) -> no_return(). - validation_error(ViolatedRule, Name) -> validation_error(ViolatedRule, Name, #{}). --spec validation_error(Rule :: any(), Name :: any(), Info :: #{}) -> no_return(). - +-spec validation_error(Rule :: any(), Name :: any(), Info :: #{_ := _}) -> no_return(). validation_error(ViolatedRule, Name, Info) -> throw({wrong_param, Name, ViolatedRule, Info}). @@ -700,31 +659,26 @@ get_value(body, _Name, Req0) -> Value -> {Value, Req} end; - get_value(qs_val, Name, Req) -> QS = cowboy_req:parse_qs(Req), - Value = openapi_utils:get_opt(openapi_utils:to_qs(Name), QS), + Value = get_opt(to_qs(Name), QS), {Value, Req}; - get_value(header, Name, Req) -> Headers = cowboy_req:headers(Req), - Value = maps:get(openapi_utils:to_header(Name), Headers, undefined), + Value = maps:get(to_header(Name), Headers, undefined), {Value, Req}; - get_value(binding, Name, Req) -> - Value = cowboy_req:binding(openapi_utils:to_binding(Name), Req), + Value = cowboy_req:binding(to_binding(Name), Req), {Value, Req}. +prepare_body(<<>>) -> + <<>>; prepare_body(Body) -> - case Body of - <<"">> -> <<"">>; - _ -> - try - jsx:decode(Body, [return_maps]) - catch - error:_ -> - {error, {invalid_body, not_json, Body}} - end + try + json:decode(Body) + catch + error:_ -> + {error, {invalid_body, not_json, Body}} end. validate_with_schema(Body, Definition, ValidatorState) -> @@ -752,5 +706,84 @@ prepare_param(Rules, Name, Value, ValidatorState) -> {error, Reason} end. +-spec to_binary(iodata() | atom() | number()) -> binary(). +to_binary(V) when is_binary(V) -> V; +to_binary(V) when is_list(V) -> iolist_to_binary(V); +to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); +to_binary(V) when is_integer(V) -> integer_to_binary(V); +to_binary(V) when is_float(V) -> float_to_binary(V). + +-spec to_list(iodata() | atom() | number()) -> binary(). +to_list(V) when is_list(V) -> V; +to_list(V) when is_binary(V) -> binary_to_list(V); +to_list(V) when is_atom(V) -> atom_to_list(V); +to_list(V) when is_integer(V) -> integer_to_list(V); +to_list(V) when is_float(V) -> float_to_list(V). + +-spec to_float(iodata()) -> float(). +to_float(V) -> + binary_to_float(iolist_to_binary([V])). + +-spec to_int(integer() | binary() | list()) -> integer(). +to_int(Data) when is_integer(Data) -> + Data; +to_int(Data) when is_binary(Data) -> + binary_to_integer(Data); +to_int(Data) when is_list(Data) -> + list_to_integer(Data). + +-spec to_header(iodata() | atom() | number()) -> binary(). +to_header(Name) -> + to_binary(string:lowercase(to_binary(Name))). + binary_to_lower(V) when is_binary(V) -> - list_to_binary(string:to_lower(openapi_utils:to_list(V))). + string:lowercase(V). + +-spec to_qs(iodata() | atom() | number()) -> binary(). +to_qs(Name) -> + to_binary(Name). + +-spec to_binding(iodata() | atom() | number()) -> atom(). +to_binding(Name) -> + Prepared = to_binary(Name), + binary_to_existing_atom(Prepared, utf8). + +-spec get_opt(any(), []) -> any(). +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> Value; + false -> Default + end. + +get_openapi_path() -> + {ok, AppName} = application:get_application(?MODULE), + filename:join(priv_dir(AppName), "openapi.json"). + +-include_lib("kernel/include/file.hrl"). + +-spec priv_dir(Application :: atom()) -> file:name_all(). +priv_dir(AppName) -> + case code:priv_dir(AppName) of + Value when is_list(Value) -> + Value ++ "/"; + _Error -> + select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) + end. + +select_priv_dir(Paths) -> + case lists:dropwhile(fun test_priv_dir/1, Paths) of + [Path | _] -> Path; + _ -> exit(no_priv_dir) + end. + +test_priv_dir(Path) -> + case file:read_file_info(Path) of + {ok, #file_info{type = directory}} -> + false; + _ -> + true + end. diff --git a/samples/server/petstore/erlang-server/src/openapi_auth.erl b/samples/server/petstore/erlang-server/src/openapi_auth.erl index b84a4f98dc89..0e7beb1132c4 100644 --- a/samples/server/petstore/erlang-server/src/openapi_auth.erl +++ b/samples/server/petstore/erlang-server/src/openapi_auth.erl @@ -2,47 +2,44 @@ -export([authorize_api_key/5]). --spec authorize_api_key( - LogicHandler :: atom(), - OperationID :: openapi_api:operation_id(), - From :: header | qs_val, - KeyParam :: iodata() | atom(), - Req ::cowboy_req:req() -)-> {true, Context :: #{binary() => any()}, Req ::cowboy_req:req()} | - {false, AuthHeader :: binary(), Req ::cowboy_req:req()}. - -authorize_api_key(LogicHandler, OperationID, From, KeyParam, Req0) -> +-spec authorize_api_key(openapi_logic_handler:api_key_callback(), + openapi_api:operation_id(), + header | qs_val, + iodata() | atom(), + cowboy_req:req()) -> + {true, openapi_logic_handler:context(), cowboy_req:req()} | + {false, binary(), cowboy_req:req()}. +authorize_api_key(Handler, OperationID, From, KeyParam, Req0) -> {ApiKey, Req} = get_api_key(From, KeyParam, Req0), case ApiKey of undefined -> - AuthHeader = <<"">>, + AuthHeader = <<>>, {false, AuthHeader, Req}; _ -> - Result = openapi_logic_handler:authorize_api_key( - LogicHandler, - OperationID, - ApiKey - ), - case Result of - {true, Context} -> + case Handler(OperationID, ApiKey) of + {true, Context} -> {true, Context, Req}; - false -> - AuthHeader = <<"">>, + {false, AuthHeader} -> {false, AuthHeader, Req} end end. get_api_key(header, KeyParam, Req) -> Headers = cowboy_req:headers(Req), - { - maps:get( - openapi_utils:to_header(KeyParam), - Headers, - undefined - ), - Req - }; - + {maps:get(KeyParam, Headers, undefined), Req}; get_api_key(qs_val, KeyParam, Req) -> QS = cowboy_req:parse_qs(Req), - { openapi_utils:get_opt(KeyParam, QS), Req}. + {get_opt(KeyParam, QS), Req}. + +-spec get_opt(any(), []) -> any(). +get_opt(Key, Opts) -> + get_opt(Key, Opts, undefined). + +-spec get_opt(any(), [], any()) -> any(). +get_opt(Key, Opts, Default) -> + case lists:keyfind(Key, 1, Opts) of + {_, Value} -> + Value; + false -> + Default + end. diff --git a/samples/server/petstore/erlang-server/src/openapi_default_logic_handler.erl b/samples/server/petstore/erlang-server/src/openapi_default_logic_handler.erl deleted file mode 100644 index da6e79a74ebd..000000000000 --- a/samples/server/petstore/erlang-server/src/openapi_default_logic_handler.erl +++ /dev/null @@ -1,24 +0,0 @@ --module(openapi_default_logic_handler). - --behaviour(openapi_logic_handler). - --export([handle_request/3]). --export([authorize_api_key/2]). - --spec authorize_api_key(OperationID :: openapi_api:operation_id(), ApiKey :: binary()) -> {true, #{}}. - -authorize_api_key(_, _) -> {true, #{}}. - --spec handle_request( - OperationID :: openapi_api:operation_id(), - Req :: cowboy_req:req(), - Context :: #{} -) -> - {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: jsx:json_term()}. - -handle_request(OperationID, Req, Context) -> - error_logger:error_msg( - "Got not implemented request to process: ~p~n", - [{OperationID, Req, Context}] - ), - {501, #{}, #{}}. diff --git a/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl b/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl index 817c1a49a830..d90faf6ae3b8 100644 --- a/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_logic_handler.erl @@ -1,36 +1,63 @@ -module(openapi_logic_handler). --export([handle_request/4]). --type context() :: #{binary() => any()}. --type handler_response() ::{ - Status :: cowboy:http_status(), - Headers :: cowboy:http_headers(), - Body :: jsx:json_term()}. - --export_type([handler_response/0]). - --callback authorize_api_key( - OperationID :: openapi_api:operation_id(), - ApiKey :: binary() -) -> - Result :: boolean() | {boolean(), context()}. - - --callback handle_request(OperationID :: openapi_api:operation_id(), cowboy_req:req(), Context :: context()) -> - handler_response(). - --spec handle_request( - Handler :: atom(), - OperationID :: openapi_api:operation_id(), - Request :: cowboy_req:req(), - Context :: context() -) -> - handler_response(). - -handle_request(Handler, OperationID, Req, Context) -> - Handler:handle_request(OperationID, Req, Context). - --spec authorize_api_key(Handler :: atom(), OperationID :: openapi_api:operation_id(), ApiKey :: binary()) -> - Result :: false | {true, context()}. -authorize_api_key(Handler, OperationID, ApiKey) -> - Handler:authorize_api_key(OperationID, ApiKey). +-include_lib("kernel/include/logger.hrl"). + +-type accept_callback_return() :: + stop + | boolean() + | {true, iodata()} + | {created, iodata()} + | {see_other, iodata()}. +-type api_key_callback() :: + fun((openapi_api:operation_id(), binary()) -> {true, context()} | {false, iodata()}). +-type accept_callback() :: + fun((atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}). +-type provide_callback() :: + fun((atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}). +-type context() :: #{_ := _}. + +-export_type([context/0, api_key_callback/0, + accept_callback_return/0, accept_callback/0, provide_callback/0]). + +-optional_callbacks([api_key_callback/2]). + +-callback api_key_callback(openapi_api:operation_id(), binary()) -> + {true, context()} | {false, iodata()}. + +-callback accept_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}. + +-callback provide_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}. + +-export([api_key_callback/2, accept_callback/4, provide_callback/4]). +-ignore_xref([api_key_callback/2, accept_callback/4, provide_callback/4]). + +-spec api_key_callback(openapi_api:operation_id(), binary()) -> {true, #{}}. +api_key_callback(OperationID, ApiKey) -> + ?LOG_ERROR(#{what => "Got not implemented api_key_callback request", + operation_id => OperationID, + api_key => ApiKey}), + {true, #{}}. + +-spec accept_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {accept_callback_return(), cowboy_req:req(), context()}. +accept_callback(Class, OperationID, Req, Context) -> + ?LOG_ERROR(#{what => "Got not implemented request to process", + class => Class, + operation_id => OperationID, + request => Req, + context => Context}), + {false, Req, Context}. + +-spec provide_callback(atom(), openapi_api:operation_id(), cowboy_req:req(), context()) -> + {cowboy_req:resp_body(), cowboy_req:req(), context()}. +provide_callback(Class, OperationID, Req, Context) -> + ?LOG_ERROR(#{what => "Got not implemented request to process", + class => Class, + operation_id => OperationID, + request => Req, + context => Context}), + {<<>>, Req, Context}. diff --git a/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl b/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl index dc72a63c5d26..837ea11d1447 100644 --- a/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_pet_handler.erl @@ -1,485 +1,251 @@ %% basic handler -module(openapi_pet_handler). +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + %% Cowboy REST callbacks --export([allowed_methods/2]). -export([init/2]). --export([allow_missing_post/2]). +-export([allowed_methods/2]). -export([content_types_accepted/2]). -export([content_types_provided/2]). -export([delete_resource/2]). -export([is_authorized/2]). --export([known_content_type/2]). --export([malformed_request/2]). -export([valid_content_headers/2]). --export([valid_entity_length/2]). - -%% Handlers --export([handle_request_json/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). --record(state, { - operation_id :: openapi_api:operation_id(), - logic_handler :: atom(), - validator_state :: jesse_state:state(), - context=#{} :: #{} -}). +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). --type state() :: state(). +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). --spec init(Req :: cowboy_req:req(), Opts :: openapi_router:init_opts()) -> - {cowboy_rest, Req :: cowboy_req:req(), State :: state()}. +-type state() :: #state{}. -init(Req, {Operations, LogicHandler, ValidatorMod}) -> +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> Method = cowboy_req:method(Req), OperationID = maps:get(Method, Operations, undefined), - - ValidatorState = ValidatorMod:get_validator_state(), - - error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), - - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - }, + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, {cowboy_rest, Req, State}. --spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> - {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. - - -allowed_methods( - Req, - State = #state{ - operation_id = 'AddPet' - } -) -> +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'AddPet'} = State) -> {[<<"POST">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'DeletePet' - } -) -> +allowed_methods(Req, #state{operation_id = 'DeletePet'} = State) -> {[<<"DELETE">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'FindPetsByStatus' - } -) -> +allowed_methods(Req, #state{operation_id = 'FindPetsByStatus'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'FindPetsByTags' - } -) -> +allowed_methods(Req, #state{operation_id = 'FindPetsByTags'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'GetPetById' - } -) -> +allowed_methods(Req, #state{operation_id = 'GetPetById'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'UpdatePet' - } -) -> +allowed_methods(Req, #state{operation_id = 'UpdatePet'} = State) -> {[<<"PUT">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'UpdatePetWithForm' - } -) -> +allowed_methods(Req, #state{operation_id = 'UpdatePetWithForm'} = State) -> {[<<"POST">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'UploadFile' - } -) -> +allowed_methods(Req, #state{operation_id = 'UploadFile'} = State) -> {[<<"POST">>], Req, State}; - allowed_methods(Req, State) -> {[], Req, State}. --spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: true | {false, AuthHeader :: iodata()}, - Req :: cowboy_req:req(), - State :: state() - }. -is_authorized( - Req0, - State = #state{ - operation_id = 'AddPet' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req0, + #state{operation_id = 'AddPet' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'DeletePet' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'DeletePet' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'FindPetsByStatus' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'FindPetsByStatus' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'FindPetsByTags' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'FindPetsByTags' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'GetPetById' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'GetPetById' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'UpdatePet' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'UpdatePet' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'UpdatePetWithForm' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'UpdatePetWithForm' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'UploadFile' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "Authorization", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'UploadFile' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. -is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. - --spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), AcceptResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. + {true, Req, State}. -content_types_accepted(Req, State) -> +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'AddPet'} = State) -> {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. - --spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> - {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'AddPet' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'DeletePet' - } -) -> - Headers = ["api_key"], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'FindPetsByStatus' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'FindPetsByTags' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'GetPetById' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'UpdatePet' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'UpdatePetWithForm' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'UploadFile' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; + {<<"application/json">>, handle_type_accepted}, + {<<"application/xml">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'DeletePet'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'FindPetsByStatus'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'FindPetsByTags'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'GetPetById'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'UpdatePet'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted}, + {<<"application/xml">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'UpdatePetWithForm'} = State) -> + {[ + {<<"application/x-www-form-urlencoded">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'UploadFile'} = State) -> + {[ + {<<"multipart/form-data">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'AddPet'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'DeletePet'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'FindPetsByStatus'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'FindPetsByTags'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'GetPetById'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'UpdatePet'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'UpdatePetWithForm'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'UploadFile'} = State) -> + {true, Req, State}; valid_content_headers(Req, State) -> {false, Req, State}. --spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), ProvideResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. - -content_types_provided(Req, State) -> +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'AddPet'} = State) -> {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. - --spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -malformed_request(Req, State) -> - {false, Req, State}. - --spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -allow_missing_post(Req, State) -> - {false, Req, State}. - --spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> - processed_response(). + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'DeletePet'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'FindPetsByStatus'} = State) -> + {[ + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'FindPetsByTags'} = State) -> + {[ + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'GetPetById'} = State) -> + {[ + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'UpdatePet'} = State) -> + {[ + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'UpdatePetWithForm'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'UploadFile'} = State) -> + {[ + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. delete_resource(Req, State) -> - handle_request_json(Req, State). - --spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -known_content_type(Req, State) -> - {true, Req, State}. - --spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -valid_entity_length(Req, State) -> - %% @TODO check the length - {true, Req, State}. - -%%%% --type result_ok() :: { - ok, - {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} -}. - --type result_error() :: {error, Reason :: any()}. - --type processed_response() :: {stop, cowboy_req:req(), state()}. - --spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> - processed_response(). - -process_response(Response, Req0, State = #state{operation_id = OperationID}) -> - case Response of - {ok, {Code, Headers, Body}} -> - Req = cowboy_req:reply(Code, Headers, Body, Req0), - {stop, Req, State}; - {error, Message} -> - error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), - - Req = cowboy_req:reply(400, Req0), - {stop, Req, State} - end. - --spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). - -handle_request_json( - Req0, - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - } -) -> - case openapi_api:populate_request(OperationID, Req0, ValidatorState) of - {ok, Populated, Req1} -> - {Code, Headers, Body} = openapi_logic_handler:handle_request( - LogicHandler, - OperationID, - Req1, - maps:merge(State#state.context, Populated) - ), - _ = openapi_api:validate_response( - OperationID, - Code, - Body, - ValidatorState - ), - PreparedBody = prepare_body(Code, Body), - Response = {ok, {Code, Headers, PreparedBody}}, - process_response(Response, Req1, State); - {error, Reason, Req1} -> - process_response({error, Reason}, Req1, State) - end. - -validate_headers(_, Req) -> {true, Req}. - -prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(_Code, Body) -> - jsx:encode(Body). + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(pet, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(pet, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/petstore/erlang-server/src/openapi_router.erl b/samples/server/petstore/erlang-server/src/openapi_router.erl index c32f2e5ba1d6..618d2024794b 100644 --- a/samples/server/petstore/erlang-server/src/openapi_router.erl +++ b/samples/server/petstore/erlang-server/src/openapi_router.erl @@ -1,57 +1,36 @@ -module(openapi_router). --export([get_paths/1, get_validator_state/0]). +-export([get_paths/1]). --type operations() :: #{ - Method :: binary() => openapi_api:operation_id() -}. - --type init_opts() :: { - Operations :: operations(), - LogicHandler :: atom(), - ValidatorMod :: module() -}. +-type method() :: binary(). +-type operations() :: #{method() => openapi_api:operation_id()}. +-type init_opts() :: {operations(), module()}. -export_type([init_opts/0]). --spec get_paths(LogicHandler :: atom()) -> [{'_',[{ - Path :: string(), - Handler :: atom(), - InitOpts :: init_opts() -}]}]. - +-spec get_paths(LogicHandler :: module()) -> cowboy_router:routes(). get_paths(LogicHandler) -> - ValidatorState = prepare_validator(), PreparedPaths = maps:fold( - fun(Path, #{operations := Operations, handler := Handler}, Acc) -> - [{Path, Handler, Operations} | Acc] - end, - [], - group_paths() - ), - [ - {'_', - [{P, H, {O, LogicHandler, ValidatorState}} || {P, H, O} <- PreparedPaths] - } - ]. + fun(Path, #{operations := Operations, handler := Handler}, Acc) -> + [{Path, Handler, Operations} | Acc] + end, [], group_paths() + ), + [{'_', [{P, H, {O, LogicHandler}} || {P, H, O} <- PreparedPaths]}]. group_paths() -> maps:fold( - fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> - case maps:find(Path, Acc) of - {ok, PathInfo0 = #{operations := Operations0}} -> - Operations = Operations0#{Method => OperationID}, - PathInfo = PathInfo0#{operations => Operations}, - Acc#{Path => PathInfo}; - error -> - Operations = #{Method => OperationID}, - PathInfo = #{handler => Handler, operations => Operations}, - Acc#{Path => PathInfo} - end - end, - #{}, - get_operations() - ). + fun(OperationID, #{path := Path, method := Method, handler := Handler}, Acc) -> + case maps:find(Path, Acc) of + {ok, PathInfo0 = #{operations := Operations0}} -> + Operations = Operations0#{Method => OperationID}, + PathInfo = PathInfo0#{operations => Operations}, + Acc#{Path => PathInfo}; + error -> + Operations = #{Method => OperationID}, + PathInfo = #{handler => Handler, operations => Operations}, + Acc#{Path => PathInfo} + end + end, #{}, get_operations()). get_operations() -> #{ @@ -156,18 +135,3 @@ get_operations() -> handler => 'openapi_user_handler' } }. - -get_validator_state() -> - persistent_term:get({?MODULE, validator_state}). - - -prepare_validator() -> - R = jsx:decode(element(2, file:read_file(get_openapi_path()))), - JesseState = jesse_state:new(R, [{default_schema_ver, <<"http://json-schema.org/draft-04/schema#">>}]), - persistent_term:put({?MODULE, validator_state}, JesseState), - ?MODULE. - - -get_openapi_path() -> - {ok, AppName} = application:get_application(?MODULE), - filename:join(openapi_utils:priv_dir(AppName), "openapi.json"). diff --git a/samples/server/petstore/erlang-server/src/openapi_server.erl b/samples/server/petstore/erlang-server/src/openapi_server.erl index 02500173821f..0cd992fe69d2 100644 --- a/samples/server/petstore/erlang-server/src/openapi_server.erl +++ b/samples/server/petstore/erlang-server/src/openapi_server.erl @@ -1,26 +1,21 @@ -module(openapi_server). - --define(DEFAULT_LOGIC_HANDLER, openapi_default_logic_handler). +-define(DEFAULT_LOGIC_HANDLER, openapi_logic_handler). -export([start/2]). - --spec start( ID :: any(), #{ - ip => inet:ip_address(), - port => inet:port_number(), - logic_handler => module(), - net_opts => [] -}) -> {ok, pid()} | {error, any()}. - -start(ID, #{ - ip := IP , - port := Port, - net_opts := NetOpts -} = Params) -> - {Transport, TransportOpts} = get_socket_transport(IP, Port, NetOpts), +-ignore_xref([start/2]). + +-spec start(term(), #{transport => tcp | ssl, + transport_opts => ranch:opts(), + protocol_opts => cowboy:opts(), + logic_handler => module()}) -> + {ok, pid()} | {error, any()}. +start(ID, Params) -> + Transport = maps:get(transport, Params, tcp), + TransportOpts = maps:get(transport_opts, Params, #{}), + ProtocolOpts = maps:get(procotol_opts, Params, #{}), LogicHandler = maps:get(logic_handler, Params, ?DEFAULT_LOGIC_HANDLER), - ExtraOpts = maps:get(cowboy_extra_opts, Params, []), - CowboyOpts = get_cowboy_config(LogicHandler, ExtraOpts), + CowboyOpts = get_cowboy_config(LogicHandler, ProtocolOpts), case Transport of ssl -> cowboy:start_tls(ID, TransportOpts, CowboyOpts); @@ -28,33 +23,17 @@ start(ID, #{ cowboy:start_clear(ID, TransportOpts, CowboyOpts) end. -get_socket_transport(IP, Port, Options) -> - Opts = [ - {ip, IP}, - {port, Port} - ], - case openapi_utils:get_opt(ssl, Options) of - SslOpts = [_|_] -> - {ssl, Opts ++ SslOpts}; - undefined -> - {tcp, Opts} - end. - get_cowboy_config(LogicHandler, ExtraOpts) -> - get_cowboy_config(LogicHandler, ExtraOpts, get_default_opts(LogicHandler)). - -get_cowboy_config(_LogicHandler, [], Opts) -> - Opts; + DefaultOpts = get_default_opts(LogicHandler), + maps:fold(fun get_cowboy_config/3, DefaultOpts, ExtraOpts). -get_cowboy_config(LogicHandler, [{env, Env} | Rest], Opts) -> - NewEnv = case proplists:get_value(dispatch, Env) of - undefined -> [get_default_dispatch(LogicHandler) | Env]; - _ -> Env - end, - get_cowboy_config(LogicHandler, Rest, store_key(env, NewEnv, Opts)); - -get_cowboy_config(LogicHandler, [{Key, Value}| Rest], Opts) -> - get_cowboy_config(LogicHandler, Rest, store_key(Key, Value, Opts)). +get_cowboy_config(env, #{dispatch := _Dispatch} = Env, AccIn) -> + maps:put(env, Env, AccIn); +get_cowboy_config(env, NewEnv, #{env := OldEnv} = AccIn) -> + Env = maps:merge(OldEnv, NewEnv), + maps:put(env, Env, AccIn); +get_cowboy_config(Key, Value, AccIn) -> + maps:put(Key, Value, AccIn). get_default_dispatch(LogicHandler) -> Paths = openapi_router:get_paths(LogicHandler), @@ -62,6 +41,3 @@ get_default_dispatch(LogicHandler) -> get_default_opts(LogicHandler) -> #{env => get_default_dispatch(LogicHandler)}. - -store_key(Key, Value, Opts) -> - maps:put(Key, Value, Opts). diff --git a/samples/server/petstore/erlang-server/src/openapi_store_handler.erl b/samples/server/petstore/erlang-server/src/openapi_store_handler.erl index 09245deb509b..d98988d8d6e3 100644 --- a/samples/server/petstore/erlang-server/src/openapi_store_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_store_handler.erl @@ -1,280 +1,139 @@ %% basic handler -module(openapi_store_handler). +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + %% Cowboy REST callbacks --export([allowed_methods/2]). -export([init/2]). --export([allow_missing_post/2]). +-export([allowed_methods/2]). -export([content_types_accepted/2]). -export([content_types_provided/2]). -export([delete_resource/2]). -export([is_authorized/2]). --export([known_content_type/2]). --export([malformed_request/2]). -export([valid_content_headers/2]). --export([valid_entity_length/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). -%% Handlers --export([handle_request_json/2]). +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). --record(state, { - operation_id :: openapi_api:operation_id(), - logic_handler :: atom(), - validator_state :: jesse_state:state(), - context=#{} :: #{} -}). +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). --type state() :: state(). +-type state() :: #state{}. --spec init(Req :: cowboy_req:req(), Opts :: openapi_router:init_opts()) -> - {cowboy_rest, Req :: cowboy_req:req(), State :: state()}. - -init(Req, {Operations, LogicHandler, ValidatorMod}) -> +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> Method = cowboy_req:method(Req), OperationID = maps:get(Method, Operations, undefined), - - ValidatorState = ValidatorMod:get_validator_state(), - - error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), - - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - }, + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, {cowboy_rest, Req, State}. --spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> - {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. - - -allowed_methods( - Req, - State = #state{ - operation_id = 'DeleteOrder' - } -) -> +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'DeleteOrder'} = State) -> {[<<"DELETE">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'GetInventory' - } -) -> +allowed_methods(Req, #state{operation_id = 'GetInventory'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'GetOrderById' - } -) -> +allowed_methods(Req, #state{operation_id = 'GetOrderById'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'PlaceOrder' - } -) -> +allowed_methods(Req, #state{operation_id = 'PlaceOrder'} = State) -> {[<<"POST">>], Req, State}; - allowed_methods(Req, State) -> {[], Req, State}. --spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: true | {false, AuthHeader :: iodata()}, - Req :: cowboy_req:req(), - State :: state() - }. -is_authorized( - Req0, - State = #state{ - operation_id = 'GetInventory' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req0, + #state{operation_id = 'GetInventory' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. -is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. - --spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), AcceptResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. + {true, Req, State}. -content_types_accepted(Req, State) -> +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'DeleteOrder'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'GetInventory'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'GetOrderById'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'PlaceOrder'} = State) -> {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. - --spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> - {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'DeleteOrder' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'GetInventory' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'GetOrderById' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'PlaceOrder' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'DeleteOrder'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'GetInventory'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'GetOrderById'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'PlaceOrder'} = State) -> + {true, Req, State}; valid_content_headers(Req, State) -> {false, Req, State}. --spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), ProvideResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. - -content_types_provided(Req, State) -> +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'DeleteOrder'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'GetInventory'} = State) -> {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. - --spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -malformed_request(Req, State) -> - {false, Req, State}. - --spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -allow_missing_post(Req, State) -> - {false, Req, State}. - --spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> - processed_response(). + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'GetOrderById'} = State) -> + {[ + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'PlaceOrder'} = State) -> + {[ + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. delete_resource(Req, State) -> - handle_request_json(Req, State). - --spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -known_content_type(Req, State) -> - {true, Req, State}. - --spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -valid_entity_length(Req, State) -> - %% @TODO check the length - {true, Req, State}. - -%%%% --type result_ok() :: { - ok, - {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} -}. - --type result_error() :: {error, Reason :: any()}. - --type processed_response() :: {stop, cowboy_req:req(), state()}. - --spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> - processed_response(). - -process_response(Response, Req0, State = #state{operation_id = OperationID}) -> - case Response of - {ok, {Code, Headers, Body}} -> - Req = cowboy_req:reply(Code, Headers, Body, Req0), - {stop, Req, State}; - {error, Message} -> - error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), - - Req = cowboy_req:reply(400, Req0), - {stop, Req, State} - end. - --spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). - -handle_request_json( - Req0, - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - } -) -> - case openapi_api:populate_request(OperationID, Req0, ValidatorState) of - {ok, Populated, Req1} -> - {Code, Headers, Body} = openapi_logic_handler:handle_request( - LogicHandler, - OperationID, - Req1, - maps:merge(State#state.context, Populated) - ), - _ = openapi_api:validate_response( - OperationID, - Code, - Body, - ValidatorState - ), - PreparedBody = prepare_body(Code, Body), - Response = {ok, {Code, Headers, PreparedBody}}, - process_response(Response, Req1, State); - {error, Reason, Req1} -> - process_response({error, Reason}, Req1, State) - end. - -validate_headers(_, Req) -> {true, Req}. - -prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(_Code, Body) -> - jsx:encode(Body). + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(store, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(store, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/petstore/erlang-server/src/openapi_user_handler.erl b/samples/server/petstore/erlang-server/src/openapi_user_handler.erl index aad43103ac66..b1db5d7bb513 100644 --- a/samples/server/petstore/erlang-server/src/openapi_user_handler.erl +++ b/samples/server/petstore/erlang-server/src/openapi_user_handler.erl @@ -1,447 +1,220 @@ %% basic handler -module(openapi_user_handler). +-behaviour(cowboy_rest). + +-include_lib("kernel/include/logger.hrl"). + %% Cowboy REST callbacks --export([allowed_methods/2]). -export([init/2]). --export([allow_missing_post/2]). +-export([allowed_methods/2]). -export([content_types_accepted/2]). -export([content_types_provided/2]). -export([delete_resource/2]). -export([is_authorized/2]). --export([known_content_type/2]). --export([malformed_request/2]). -export([valid_content_headers/2]). --export([valid_entity_length/2]). +-export([handle_type_accepted/2, handle_type_provided/2]). -%% Handlers --export([handle_request_json/2]). +-ignore_xref([handle_type_accepted/2, handle_type_provided/2]). --record(state, { - operation_id :: openapi_api:operation_id(), - logic_handler :: atom(), - validator_state :: jesse_state:state(), - context=#{} :: #{} -}). +-record(state, + {operation_id :: openapi_api:operation_id(), + accept_callback :: openapi_logic_handler:accept_callback(), + provide_callback :: openapi_logic_handler:provide_callback(), + api_key_handler :: openapi_logic_handler:api_key_callback(), + context = #{} :: openapi_logic_handler:context()}). --type state() :: state(). +-type state() :: #state{}. --spec init(Req :: cowboy_req:req(), Opts :: openapi_router:init_opts()) -> - {cowboy_rest, Req :: cowboy_req:req(), State :: state()}. - -init(Req, {Operations, LogicHandler, ValidatorMod}) -> +-spec init(cowboy_req:req(), openapi_router:init_opts()) -> + {cowboy_rest, cowboy_req:req(), state()}. +init(Req, {Operations, Module}) -> Method = cowboy_req:method(Req), OperationID = maps:get(Method, Operations, undefined), - - ValidatorState = ValidatorMod:get_validator_state(), - - error_logger:info_msg("Attempt to process operation: ~p", [OperationID]), - - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - }, + ?LOG_INFO(#{what => "Attempt to process operation", + method => Method, + operation_id => OperationID}), + State = #state{operation_id = OperationID, + accept_callback = fun Module:accept_callback/4, + provide_callback = fun Module:provide_callback/4, + api_key_handler = fun Module:authorize_api_key/2}, {cowboy_rest, Req, State}. --spec allowed_methods(Req :: cowboy_req:req(), State :: state()) -> - {Value :: [binary()], Req :: cowboy_req:req(), State :: state()}. - - -allowed_methods( - Req, - State = #state{ - operation_id = 'CreateUser' - } -) -> +-spec allowed_methods(cowboy_req:req(), state()) -> + {[binary()], cowboy_req:req(), state()}. +allowed_methods(Req, #state{operation_id = 'CreateUser'} = State) -> {[<<"POST">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'CreateUsersWithArrayInput' - } -) -> +allowed_methods(Req, #state{operation_id = 'CreateUsersWithArrayInput'} = State) -> {[<<"POST">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'CreateUsersWithListInput' - } -) -> +allowed_methods(Req, #state{operation_id = 'CreateUsersWithListInput'} = State) -> {[<<"POST">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'DeleteUser' - } -) -> +allowed_methods(Req, #state{operation_id = 'DeleteUser'} = State) -> {[<<"DELETE">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'GetUserByName' - } -) -> +allowed_methods(Req, #state{operation_id = 'GetUserByName'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'LoginUser' - } -) -> +allowed_methods(Req, #state{operation_id = 'LoginUser'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'LogoutUser' - } -) -> +allowed_methods(Req, #state{operation_id = 'LogoutUser'} = State) -> {[<<"GET">>], Req, State}; - -allowed_methods( - Req, - State = #state{ - operation_id = 'UpdateUser' - } -) -> +allowed_methods(Req, #state{operation_id = 'UpdateUser'} = State) -> {[<<"PUT">>], Req, State}; - allowed_methods(Req, State) -> {[], Req, State}. --spec is_authorized(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: true | {false, AuthHeader :: iodata()}, - Req :: cowboy_req:req(), - State :: state() - }. -is_authorized( - Req0, - State = #state{ - operation_id = 'CreateUser' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +-spec is_authorized(cowboy_req:req(), state()) -> + {true | {false, iodata()}, cowboy_req:req(), state()}. +is_authorized(Req0, + #state{operation_id = 'CreateUser' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'CreateUsersWithArrayInput' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'CreateUsersWithArrayInput' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'CreateUsersWithListInput' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'CreateUsersWithListInput' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'DeleteUser' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'DeleteUser' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'LogoutUser' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'LogoutUser' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; -is_authorized( - Req0, - State = #state{ - operation_id = 'UpdateUser' = OperationID, - logic_handler = LogicHandler - } -) -> - From = header, - Result = openapi_auth:authorize_api_key( - LogicHandler, - OperationID, - From, - "api_key", - Req0 - ), - case Result of - {true, Context, Req} -> {true, Req, State#state{context = Context}}; - {false, AuthHeader, Req} -> {{false, AuthHeader}, Req, State} +is_authorized(Req0, + #state{operation_id = 'UpdateUser' = OperationID, + api_key_handler = Handler} = State) -> + case openapi_auth:authorize_api_key(Handler, OperationID, header, "authorization", Req0) of + {true, Context, Req} -> + {true, Req, State#state{context = Context}}; + {false, AuthHeader, Req} -> + {{false, AuthHeader}, Req, State} end; is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. -is_authorized(Req, State) -> - {{false, <<"">>}, Req, State}. - --spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), AcceptResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. + {true, Req, State}. -content_types_accepted(Req, State) -> +-spec content_types_accepted(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_accepted(Req, #state{operation_id = 'CreateUser'} = State) -> {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. - --spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) -> - {Value :: boolean(), Req :: cowboy_req:req(), State :: state()}. - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'CreateUser' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'CreateUsersWithArrayInput' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'CreateUsersWithListInput' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'DeleteUser' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'GetUserByName' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'LoginUser' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'LogoutUser' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; - -valid_content_headers( - Req0, - State = #state{ - operation_id = 'UpdateUser' - } -) -> - Headers = [], - {Result, Req} = validate_headers(Headers, Req0), - {Result, Req, State}; + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'CreateUsersWithArrayInput'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'CreateUsersWithListInput'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, #state{operation_id = 'DeleteUser'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'GetUserByName'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'LoginUser'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'LogoutUser'} = State) -> + {[], Req, State}; +content_types_accepted(Req, #state{operation_id = 'UpdateUser'} = State) -> + {[ + {<<"application/json">>, handle_type_accepted} + ], Req, State}; +content_types_accepted(Req, State) -> + {[], Req, State}. +-spec valid_content_headers(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. +valid_content_headers(Req, #state{operation_id = 'CreateUser'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'CreateUsersWithArrayInput'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'CreateUsersWithListInput'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'DeleteUser'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'GetUserByName'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'LoginUser'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'LogoutUser'} = State) -> + {true, Req, State}; +valid_content_headers(Req, #state{operation_id = 'UpdateUser'} = State) -> + {true, Req, State}; valid_content_headers(Req, State) -> {false, Req, State}. --spec content_types_provided(Req :: cowboy_req:req(), State :: state()) -> - { - Value :: [{binary(), ProvideResource :: atom()}], - Req :: cowboy_req:req(), - State :: state() - }. - -content_types_provided(Req, State) -> +-spec content_types_provided(cowboy_req:req(), state()) -> + {[{binary(), atom()}], cowboy_req:req(), state()}. +content_types_provided(Req, #state{operation_id = 'CreateUser'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'CreateUsersWithArrayInput'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'CreateUsersWithListInput'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'DeleteUser'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'GetUserByName'} = State) -> {[ - {<<"application/json">>, handle_request_json} - ], Req, State}. - --spec malformed_request(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -malformed_request(Req, State) -> - {false, Req, State}. - --spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) -> - {Value :: false, Req :: cowboy_req:req(), State :: state()}. - -allow_missing_post(Req, State) -> - {false, Req, State}. - --spec delete_resource(Req :: cowboy_req:req(), State :: state()) -> - processed_response(). + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'LoginUser'} = State) -> + {[ + {<<"application/xml">>, handle_type_provided}, + {<<"application/json">>, handle_type_provided} + ], Req, State}; +content_types_provided(Req, #state{operation_id = 'LogoutUser'} = State) -> + {[], Req, State}; +content_types_provided(Req, #state{operation_id = 'UpdateUser'} = State) -> + {[], Req, State}; +content_types_provided(Req, State) -> + {[], Req, State}. +-spec delete_resource(cowboy_req:req(), state()) -> + {boolean(), cowboy_req:req(), state()}. delete_resource(Req, State) -> - handle_request_json(Req, State). - --spec known_content_type(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -known_content_type(Req, State) -> - {true, Req, State}. - --spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) -> - {Value :: true, Req :: cowboy_req:req(), State :: state()}. - -valid_entity_length(Req, State) -> - %% @TODO check the length - {true, Req, State}. - -%%%% --type result_ok() :: { - ok, - {Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()} -}. - --type result_error() :: {error, Reason :: any()}. - --type processed_response() :: {stop, cowboy_req:req(), state()}. - --spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) -> - processed_response(). - -process_response(Response, Req0, State = #state{operation_id = OperationID}) -> - case Response of - {ok, {Code, Headers, Body}} -> - Req = cowboy_req:reply(Code, Headers, Body, Req0), - {stop, Req, State}; - {error, Message} -> - error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]), - - Req = cowboy_req:reply(400, Req0), - {stop, Req, State} - end. - --spec handle_request_json(cowboy_req:req(), state()) -> processed_response(). - -handle_request_json( - Req0, - State = #state{ - operation_id = OperationID, - logic_handler = LogicHandler, - validator_state = ValidatorState - } -) -> - case openapi_api:populate_request(OperationID, Req0, ValidatorState) of - {ok, Populated, Req1} -> - {Code, Headers, Body} = openapi_logic_handler:handle_request( - LogicHandler, - OperationID, - Req1, - maps:merge(State#state.context, Populated) - ), - _ = openapi_api:validate_response( - OperationID, - Code, - Body, - ValidatorState - ), - PreparedBody = prepare_body(Code, Body), - Response = {ok, {Code, Headers, PreparedBody}}, - process_response(Response, Req1, State); - {error, Reason, Req1} -> - process_response({error, Reason}, Req1, State) - end. - -validate_headers(_, Req) -> {true, Req}. - -prepare_body(204, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(304, Body) when map_size(Body) == 0; length(Body) == 0 -> - <<>>; -prepare_body(_Code, Body) -> - jsx:encode(Body). + {Res, Req1, State} = handle_type_accepted(Req, State), + {true =:= Res, Req1, State}. + +-spec handle_type_accepted(cowboy_req:req(), state()) -> + { openapi_logic_handler:accept_callback_return(), cowboy_req:req(), state()}. +handle_type_accepted(Req, #state{operation_id = OperationID, + accept_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(user, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. + +-spec handle_type_provided(cowboy_req:req(), state()) -> + {cowboy_req:resp_body(), cowboy_req:req(), state()}. +handle_type_provided(Req, #state{operation_id = OperationID, + provide_callback = Handler, + context = Context} = State) -> + {Res, Req1, Context1} = Handler(user, OperationID, Req, Context), + {Res, Req1, State#state{context = Context1}}. diff --git a/samples/server/petstore/erlang-server/src/openapi_utils.erl b/samples/server/petstore/erlang-server/src/openapi_utils.erl deleted file mode 100644 index 58eee3a48e0f..000000000000 --- a/samples/server/petstore/erlang-server/src/openapi_utils.erl +++ /dev/null @@ -1,173 +0,0 @@ --module(openapi_utils). - --export([to_binary/1]). --export([to_list/1]). --export([to_float/1]). --export([to_int/1]). --export([to_lower/1]). --export([to_upper/1]). --export([set_resp_headers/2]). --export([to_header/1]). --export([to_qs/1]). --export([to_binding/1]). --export([get_opt/2]). --export([get_opt/3]). --export([priv_dir/0]). --export([priv_dir/1]). --export([priv_path/1]). - - --spec to_binary(iodata() | atom() | number()) -> binary(). - -to_binary(V) when is_binary(V) -> V; -to_binary(V) when is_list(V) -> iolist_to_binary(V); -to_binary(V) when is_atom(V) -> atom_to_binary(V, utf8); -to_binary(V) when is_integer(V) -> integer_to_binary(V); -to_binary(V) when is_float(V) -> float_to_binary(V). - --spec to_list(iodata() | atom() | number()) -> string(). - -to_list(V) when is_list(V) -> V; -to_list(V) -> binary_to_list(to_binary(V)). - --spec to_float(iodata()) -> number(). - -to_float(V) -> - Data = iolist_to_binary([V]), - case binary:split(Data, <<$.>>) of - [Data] -> - binary_to_integer(Data); - [<<>>, _] -> - binary_to_float(<<$0, Data/binary>>); - _ -> - binary_to_float(Data) - end. - -%% - --spec to_int(integer() | binary() | list()) -> integer(). - -to_int(Data) when is_integer(Data) -> - Data; -to_int(Data) when is_binary(Data) -> - binary_to_integer(Data); -to_int(Data) when is_list(Data) -> - list_to_integer(Data). - --spec set_resp_headers([{binary(), iodata()}], cowboy_req:req()) -> cowboy_req:req(). - -set_resp_headers([], Req) -> - Req; -set_resp_headers([{K, V} | T], Req0) -> - Req = cowboy_req:set_resp_header(K, V, Req0), - set_resp_headers(T, Req). - --spec to_header(iodata() | atom() | number()) -> binary(). - -to_header(Name) -> - Prepared = to_binary(Name), - to_lower(Prepared). - --spec to_qs(iodata() | atom() | number()) -> binary(). - -to_qs(Name) -> - to_binary(Name). - --spec to_binding(iodata() | atom() | number()) -> atom(). - -to_binding(Name) -> - Prepared = to_binary(Name), - binary_to_atom(Prepared, utf8). - --spec get_opt(any(), []) -> any(). - -get_opt(Key, Opts) -> - get_opt(Key, Opts, undefined). - --spec get_opt(any(), [], any()) -> any(). - -get_opt(Key, Opts, Default) -> - case lists:keyfind(Key, 1, Opts) of - {_, Value} -> Value; - false -> Default - end. - --spec priv_dir() -> file:filename(). - -priv_dir() -> - {ok, AppName} = application:get_application(), - priv_dir(AppName). - --spec priv_dir(Application :: atom()) -> file:filename(). - -priv_dir(AppName) -> - case code:priv_dir(AppName) of - Value when is_list(Value) -> - Value ++ "/"; - _Error -> - select_priv_dir([filename:join(["apps", atom_to_list(AppName), "priv"]), "priv"]) - end. - --spec priv_path(Relative :: file:filename()) -> file:filename(). - -priv_path(Relative) -> - filename:join(priv_dir(), Relative). - --include_lib("kernel/include/file.hrl"). - -select_priv_dir(Paths) -> - case lists:dropwhile(fun test_priv_dir/1, Paths) of - [Path | _] -> Path; - _ -> exit(no_priv_dir) - end. - -test_priv_dir(Path) -> - case file:read_file_info(Path) of - {ok, #file_info{type = directory}} -> - false; - _ -> - true - end. - - -%% - --spec to_lower(binary()) -> binary(). - -to_lower(S) -> - to_case(lower, S, <<>>). - --spec to_upper(binary()) -> binary(). - -to_upper(S) -> - to_case(upper, S, <<>>). - -to_case(_Case, <<>>, Acc) -> - Acc; - -to_case(_Case, <>, _Acc) when C > 127 -> - error(badarg); - -to_case(Case = lower, <>, Acc) -> - to_case(Case, Rest, <>); - -to_case(Case = upper, <>, Acc) -> - to_case(Case, Rest, <>). - -to_lower_char(C) when is_integer(C), $A =< C, C =< $Z -> - C + 32; -to_lower_char(C) when is_integer(C), 16#C0 =< C, C =< 16#D6 -> - C + 32; -to_lower_char(C) when is_integer(C), 16#D8 =< C, C =< 16#DE -> - C + 32; -to_lower_char(C) -> - C. - -to_upper_char(C) when is_integer(C), $a =< C, C =< $z -> - C - 32; -to_upper_char(C) when is_integer(C), 16#E0 =< C, C =< 16#F6 -> - C - 32; -to_upper_char(C) when is_integer(C), 16#F8 =< C, C =< 16#FE -> - C - 32; -to_upper_char(C) -> - C. diff --git a/samples/server/petstore/go-api-server/go/api.go b/samples/server/petstore/go-api-server/go/api.go index 23d5213c5a63..b6f9945682d4 100644 --- a/samples/server/petstore/go-api-server/go/api.go +++ b/samples/server/petstore/go-api-server/go/api.go @@ -23,30 +23,30 @@ import ( // The PetAPIRouter implementation should parse necessary information from the http request, // pass the data to a PetAPIServicer to perform the required actions, then write the service results to the http response. type PetAPIRouter interface { + UpdatePet(http.ResponseWriter, *http.Request) AddPet(http.ResponseWriter, *http.Request) - DeletePet(http.ResponseWriter, *http.Request) - FilterPetsByCategory(http.ResponseWriter, *http.Request) FindPetsByStatus(http.ResponseWriter, *http.Request) + SearchPet(http.ResponseWriter, *http.Request) // Deprecated FindPetsByTags(http.ResponseWriter, *http.Request) + FilterPetsByCategory(http.ResponseWriter, *http.Request) GetPetById(http.ResponseWriter, *http.Request) - GetPetImageById(http.ResponseWriter, *http.Request) - GetPetsByTime(http.ResponseWriter, *http.Request) - GetPetsUsingBooleanQueryParameters(http.ResponseWriter, *http.Request) - SearchPet(http.ResponseWriter, *http.Request) - UpdatePet(http.ResponseWriter, *http.Request) UpdatePetWithForm(http.ResponseWriter, *http.Request) + DeletePet(http.ResponseWriter, *http.Request) + GetPetImageById(http.ResponseWriter, *http.Request) UploadFile(http.ResponseWriter, *http.Request) UploadFileArrayOfFiles(http.ResponseWriter, *http.Request) + GetPetsUsingBooleanQueryParameters(http.ResponseWriter, *http.Request) + GetPetsByTime(http.ResponseWriter, *http.Request) } // StoreAPIRouter defines the required methods for binding the api requests to a responses for the StoreAPI // The StoreAPIRouter implementation should parse necessary information from the http request, // pass the data to a StoreAPIServicer to perform the required actions, then write the service results to the http response. type StoreAPIRouter interface { - DeleteOrder(http.ResponseWriter, *http.Request) GetInventory(http.ResponseWriter, *http.Request) - GetOrderById(http.ResponseWriter, *http.Request) PlaceOrder(http.ResponseWriter, *http.Request) + GetOrderById(http.ResponseWriter, *http.Request) + DeleteOrder(http.ResponseWriter, *http.Request) } // UserAPIRouter defines the required methods for binding the api requests to a responses for the UserAPI // The UserAPIRouter implementation should parse necessary information from the http request, @@ -55,11 +55,11 @@ type UserAPIRouter interface { CreateUser(http.ResponseWriter, *http.Request) CreateUsersWithArrayInput(http.ResponseWriter, *http.Request) CreateUsersWithListInput(http.ResponseWriter, *http.Request) - DeleteUser(http.ResponseWriter, *http.Request) - GetUserByName(http.ResponseWriter, *http.Request) LoginUser(http.ResponseWriter, *http.Request) LogoutUser(http.ResponseWriter, *http.Request) + GetUserByName(http.ResponseWriter, *http.Request) UpdateUser(http.ResponseWriter, *http.Request) + DeleteUser(http.ResponseWriter, *http.Request) } @@ -68,21 +68,21 @@ type UserAPIRouter interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type PetAPIServicer interface { + UpdatePet(context.Context, Pet) (ImplResponse, error) AddPet(context.Context, Pet) (ImplResponse, error) - DeletePet(context.Context, int64, string) (ImplResponse, error) - FilterPetsByCategory(context.Context, Gender, Species, []Species) (ImplResponse, error) FindPetsByStatus(context.Context, []string, string, string, int32, float32, string) (ImplResponse, error) + SearchPet(context.Context, *int64, *float32, *time.Time, *bool) (ImplResponse, error) // Deprecated FindPetsByTags(context.Context, []string, time.Time, time.Time, Colour) (ImplResponse, error) + FilterPetsByCategory(context.Context, Gender, Species, []Species) (ImplResponse, error) GetPetById(context.Context, int64) (ImplResponse, error) - GetPetImageById(context.Context, int64) (ImplResponse, error) - GetPetsByTime(context.Context, time.Time) (ImplResponse, error) - GetPetsUsingBooleanQueryParameters(context.Context, bool, bool, bool) (ImplResponse, error) - SearchPet(context.Context, *int64, *float32, *time.Time, *bool) (ImplResponse, error) - UpdatePet(context.Context, Pet) (ImplResponse, error) UpdatePetWithForm(context.Context, int64, string, string) (ImplResponse, error) + DeletePet(context.Context, int64, string) (ImplResponse, error) + GetPetImageById(context.Context, int64) (ImplResponse, error) UploadFile(context.Context, int64, string, []string, *os.File) (ImplResponse, error) UploadFileArrayOfFiles(context.Context, int64, string, []*os.File) (ImplResponse, error) + GetPetsUsingBooleanQueryParameters(context.Context, bool, bool, bool) (ImplResponse, error) + GetPetsByTime(context.Context, time.Time) (ImplResponse, error) } @@ -91,10 +91,10 @@ type PetAPIServicer interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type StoreAPIServicer interface { - DeleteOrder(context.Context, string) (ImplResponse, error) GetInventory(context.Context) (ImplResponse, error) - GetOrderById(context.Context, int64) (ImplResponse, error) PlaceOrder(context.Context, Order) (ImplResponse, error) + GetOrderById(context.Context, int64) (ImplResponse, error) + DeleteOrder(context.Context, string) (ImplResponse, error) } @@ -106,9 +106,9 @@ type UserAPIServicer interface { CreateUser(context.Context, User) (ImplResponse, error) CreateUsersWithArrayInput(context.Context, []User) (ImplResponse, error) CreateUsersWithListInput(context.Context, []User) (ImplResponse, error) - DeleteUser(context.Context, string, bool) (ImplResponse, error) - GetUserByName(context.Context, string) (ImplResponse, error) LoginUser(context.Context, string, string, bool) (ImplResponse, error) LogoutUser(context.Context) (ImplResponse, error) + GetUserByName(context.Context, string) (ImplResponse, error) UpdateUser(context.Context, string, User) (ImplResponse, error) + DeleteUser(context.Context, string, bool) (ImplResponse, error) } diff --git a/samples/server/petstore/go-api-server/go/api_pet.go b/samples/server/petstore/go-api-server/go/api_pet.go index 8451d4cf8922..68f4fd031de0 100644 --- a/samples/server/petstore/go-api-server/go/api_pet.go +++ b/samples/server/petstore/go-api-server/go/api_pet.go @@ -53,66 +53,56 @@ func NewPetAPIController(s PetAPIServicer, opts ...PetAPIOption) *PetAPIControll // Routes returns all the api routes for the PetAPIController func (c *PetAPIController) Routes() Routes { return Routes{ + "UpdatePet": Route{ + strings.ToUpper("Put"), + "/v2/pet", + c.UpdatePet, + }, "AddPet": Route{ strings.ToUpper("Post"), "/v2/pet", c.AddPet, }, - "DeletePet": Route{ - strings.ToUpper("Delete"), - "/v2/pet/{petId}", - c.DeletePet, - }, - "FilterPetsByCategory": Route{ - strings.ToUpper("Get"), - "/v2/pet/filterPets/{gender}", - c.FilterPetsByCategory, - }, "FindPetsByStatus": Route{ strings.ToUpper("Get"), "/v2/pet/findByStatus", c.FindPetsByStatus, }, + "SearchPet": Route{ + strings.ToUpper("Get"), + "/v2/pet/searchPetWithManyFilters", + c.SearchPet, + }, "FindPetsByTags": Route{ strings.ToUpper("Get"), "/v2/pet/findByTags", c.FindPetsByTags, }, + "FilterPetsByCategory": Route{ + strings.ToUpper("Get"), + "/v2/pet/filterPets/{gender}", + c.FilterPetsByCategory, + }, "GetPetById": Route{ strings.ToUpper("Get"), "/v2/pet/{petId}", c.GetPetById, }, - "GetPetImageById": Route{ - strings.ToUpper("Get"), - "/v2/pet/{petId}/uploadImage", - c.GetPetImageById, - }, - "GetPetsByTime": Route{ - strings.ToUpper("Get"), - "/v2/pets/byTime/{createdTime}", - c.GetPetsByTime, - }, - "GetPetsUsingBooleanQueryParameters": Route{ - strings.ToUpper("Get"), - "/v2/pets/boolean/parsing", - c.GetPetsUsingBooleanQueryParameters, - }, - "SearchPet": Route{ - strings.ToUpper("Get"), - "/v2/pet/searchPetWithManyFilters", - c.SearchPet, - }, - "UpdatePet": Route{ - strings.ToUpper("Put"), - "/v2/pet", - c.UpdatePet, - }, "UpdatePetWithForm": Route{ strings.ToUpper("Post"), "/v2/pet/{petId}", c.UpdatePetWithForm, }, + "DeletePet": Route{ + strings.ToUpper("Delete"), + "/v2/pet/{petId}", + c.DeletePet, + }, + "GetPetImageById": Route{ + strings.ToUpper("Get"), + "/v2/pet/{petId}/uploadImage", + c.GetPetImageById, + }, "UploadFile": Route{ strings.ToUpper("Post"), "/v2/pet/{petId}/uploadImage", @@ -123,11 +113,21 @@ func (c *PetAPIController) Routes() Routes { "/v2/fake/uploadImage/array of_file", c.UploadFileArrayOfFiles, }, + "GetPetsUsingBooleanQueryParameters": Route{ + strings.ToUpper("Get"), + "/v2/pets/boolean/parsing", + c.GetPetsUsingBooleanQueryParameters, + }, + "GetPetsByTime": Route{ + strings.ToUpper("Get"), + "/v2/pets/byTime/{createdTime}", + c.GetPetsByTime, + }, } } -// AddPet - Add a new pet to the store -func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { +// UpdatePet - Update an existing pet +func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { petParam := Pet{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() @@ -143,29 +143,7 @@ func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { c.errorHandler(w, r, err, nil) return } - result, err := c.service.AddPet(r.Context(), petParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// DeletePet - Deletes a pet -func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - petIdParam, err := parseNumericParameter[int64]( - params["petId"], - WithRequire[int64](parseInt64), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) - return - } - apiKeyParam := r.Header.Get("api_key") - result, err := c.service.DeletePet(r.Context(), petIdParam, apiKeyParam) + result, err := c.service.UpdatePet(r.Context(), petParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -175,42 +153,24 @@ func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// FilterPetsByCategory - Finds Pets -func (c *PetAPIController) FilterPetsByCategory(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - query, err := parseQuery(r.URL.RawQuery) - if err != nil { +// AddPet - Add a new pet to the store +func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { + petParam := Pet{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&petParam); err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - genderParam, err := NewGenderFromValue(params["gender"]) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "gender", Err: err}, nil) + if err := AssertPetRequired(petParam); err != nil { + c.errorHandler(w, r, err, nil) return } - var speciesParam Species - if query.Has("species") { - param := Species(query.Get("species")) - - speciesParam = param - } else { - c.errorHandler(w, r, &RequiredError{Field: "species"}, nil) + if err := AssertPetConstraints(petParam); err != nil { + c.errorHandler(w, r, err, nil) return } - var notSpeciesParam []Species - if query.Has("notSpecies") { - paramSplits := strings.Split(query.Get("notSpecies"), ",") - notSpeciesParam = make([]Species, 0, len(paramSplits)) - for _, param := range paramSplits { - paramEnum, err := NewSpeciesFromValue(param) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "notSpecies", Err: err}, nil) - return - } - notSpeciesParam = append(notSpeciesParam, paramEnum) - } - } - result, err := c.service.FilterPetsByCategory(r.Context(), genderParam, speciesParam, notSpeciesParam) + result, err := c.service.AddPet(r.Context(), petParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -295,6 +255,76 @@ func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Reque _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// SearchPet - Search Pets by filters +func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { + query, err := parseQuery(r.URL.RawQuery) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + var ageParam *int64 + if query.Has("age") { + param, err := parseNumericParameter[int64]( + query.Get("age"), + WithParse[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "age", Err: err}, nil) + return + } + + ageParam = ¶m + } else { + } + var priceParam *float32 + if query.Has("price") { + param, err := parseNumericParameter[float32]( + query.Get("price"), + WithParse[float32](parseFloat32), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "price", Err: err}, nil) + return + } + + priceParam = ¶m + } else { + } + var bornAfterParam *time.Time + if query.Has("bornAfter"){ + param, err := parseTime(query.Get("bornAfter")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "bornAfter", Err: err}, nil) + return + } + + bornAfterParam = ¶m + } else { + } + var oldParam *bool + if query.Has("old") { + param, err := parseBoolParameter( + query.Get("old"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "old", Err: err}, nil) + return + } + + oldParam = ¶m + } else { + } + result, err := c.service.SearchPet(r.Context(), ageParam, priceParam, bornAfterParam, oldParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // FindPetsByTags - Finds Pets by tags // Deprecated func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request) { @@ -348,18 +378,42 @@ func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetPetById - Find pet by ID -func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { +// FilterPetsByCategory - Finds Pets +func (c *PetAPIController) FilterPetsByCategory(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - petIdParam, err := parseNumericParameter[int64]( - params["petId"], - WithRequire[int64](parseInt64), - ) + query, err := parseQuery(r.URL.RawQuery) if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) + c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - result, err := c.service.GetPetById(r.Context(), petIdParam) + genderParam, err := NewGenderFromValue(params["gender"]) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "gender", Err: err}, nil) + return + } + var speciesParam Species + if query.Has("species") { + param := Species(query.Get("species")) + + speciesParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "species"}, nil) + return + } + var notSpeciesParam []Species + if query.Has("notSpecies") { + paramSplits := strings.Split(query.Get("notSpecies"), ",") + notSpeciesParam = make([]Species, 0, len(paramSplits)) + for _, param := range paramSplits { + paramEnum, err := NewSpeciesFromValue(param) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "notSpecies", Err: err}, nil) + return + } + notSpeciesParam = append(notSpeciesParam, paramEnum) + } + } + result, err := c.service.FilterPetsByCategory(r.Context(), genderParam, speciesParam, notSpeciesParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -369,8 +423,8 @@ func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetPetImageById - Returns the image for the Pet that has been previously uploaded -func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Request) { +// GetPetById - Find pet by ID +func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) petIdParam, err := parseNumericParameter[int64]( params["petId"], @@ -380,7 +434,7 @@ func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Reques c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - result, err := c.service.GetPetImageById(r.Context(), petIdParam) + result, err := c.service.GetPetById(r.Context(), petIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -390,148 +444,28 @@ func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Reques _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetPetsByTime - Get the pets by time -func (c *PetAPIController) GetPetsByTime(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - createdTimeParam, err := parseTime(params["createdTime"]) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "createdTime", Err: err}, nil) - return - } - result, err := c.service.GetPetsByTime(r.Context(), createdTimeParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters -func (c *PetAPIController) GetPetsUsingBooleanQueryParameters(w http.ResponseWriter, r *http.Request) { - query, err := parseQuery(r.URL.RawQuery) - if err != nil { +// UpdatePetWithForm - Updates a pet in the store with form data +func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - var exprParam bool - if query.Has("expr") { - param, err := parseBoolParameter( - query.Get("expr"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "expr", Err: err}, nil) - return - } - - exprParam = param - } else { - c.errorHandler(w, r, &RequiredError{Field: "expr"}, nil) - return - } - var groupingParam bool - if query.Has("grouping") { - param, err := parseBoolParameter( - query.Get("grouping"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "grouping", Err: err}, nil) - return - } - - groupingParam = param - } else { - } - var inactiveParam bool - if query.Has("inactive") { - param, err := parseBoolParameter( - query.Get("inactive"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "inactive", Err: err}, nil) - return - } - - inactiveParam = param - } else { - var param bool = false - inactiveParam = param - } - result, err := c.service.GetPetsUsingBooleanQueryParameters(r.Context(), exprParam, groupingParam, inactiveParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// SearchPet - Search Pets by filters -func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { - query, err := parseQuery(r.URL.RawQuery) + params := mux.Vars(r) + petIdParam, err := parseNumericParameter[int64]( + params["petId"], + WithRequire[int64](parseInt64), + ) if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - var ageParam *int64 - if query.Has("age") { - param, err := parseNumericParameter[int64]( - query.Get("age"), - WithParse[int64](parseInt64), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "age", Err: err}, nil) - return - } - - ageParam = ¶m - } else { - } - var priceParam *float32 - if query.Has("price") { - param, err := parseNumericParameter[float32]( - query.Get("price"), - WithParse[float32](parseFloat32), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "price", Err: err}, nil) - return - } - - priceParam = ¶m - } else { - } - var bornAfterParam *time.Time - if query.Has("bornAfter"){ - param, err := parseTime(query.Get("bornAfter")) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "bornAfter", Err: err}, nil) - return - } - - bornAfterParam = ¶m - } else { - } - var oldParam *bool - if query.Has("old") { - param, err := parseBoolParameter( - query.Get("old"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "old", Err: err}, nil) - return - } - - oldParam = ¶m - } else { - } - result, err := c.service.SearchPet(r.Context(), ageParam, priceParam, bornAfterParam, oldParam) + + + nameParam := r.FormValue("name") + + + statusParam := r.FormValue("status") + result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -541,24 +475,19 @@ func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// UpdatePet - Update an existing pet -func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { - petParam := Pet{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&petParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertPetRequired(petParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - if err := AssertPetConstraints(petParam); err != nil { - c.errorHandler(w, r, err, nil) +// DeletePet - Deletes a pet +func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + petIdParam, err := parseNumericParameter[int64]( + params["petId"], + WithRequire[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - result, err := c.service.UpdatePet(r.Context(), petParam) + apiKeyParam := r.Header.Get("api_key") + result, err := c.service.DeletePet(r.Context(), petIdParam, apiKeyParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -568,12 +497,8 @@ func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// UpdatePetWithForm - Updates a pet in the store with form data -func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) { - if err := r.ParseForm(); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } +// GetPetImageById - Returns the image for the Pet that has been previously uploaded +func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) petIdParam, err := parseNumericParameter[int64]( params["petId"], @@ -583,13 +508,7 @@ func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Requ c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - - - nameParam := r.FormValue("name") - - - statusParam := r.FormValue("status") - result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) + result, err := c.service.GetPetImageById(r.Context(), petIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -681,3 +600,84 @@ func (c *PetAPIController) UploadFileArrayOfFiles(w http.ResponseWriter, r *http // If no error, encode the body and the result code _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } + +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (c *PetAPIController) GetPetsUsingBooleanQueryParameters(w http.ResponseWriter, r *http.Request) { + query, err := parseQuery(r.URL.RawQuery) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + var exprParam bool + if query.Has("expr") { + param, err := parseBoolParameter( + query.Get("expr"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "expr", Err: err}, nil) + return + } + + exprParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "expr"}, nil) + return + } + var groupingParam bool + if query.Has("grouping") { + param, err := parseBoolParameter( + query.Get("grouping"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "grouping", Err: err}, nil) + return + } + + groupingParam = param + } else { + } + var inactiveParam bool + if query.Has("inactive") { + param, err := parseBoolParameter( + query.Get("inactive"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "inactive", Err: err}, nil) + return + } + + inactiveParam = param + } else { + var param bool = false + inactiveParam = param + } + result, err := c.service.GetPetsUsingBooleanQueryParameters(r.Context(), exprParam, groupingParam, inactiveParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// GetPetsByTime - Get the pets by time +func (c *PetAPIController) GetPetsByTime(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + createdTimeParam, err := parseTime(params["createdTime"]) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "createdTime", Err: err}, nil) + return + } + result, err := c.service.GetPetsByTime(r.Context(), createdTimeParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} diff --git a/samples/server/petstore/go-api-server/go/api_pet_service.go b/samples/server/petstore/go-api-server/go/api_pet_service.go index 9786bd5f71ab..4c6abe83dec7 100644 --- a/samples/server/petstore/go-api-server/go/api_pet_service.go +++ b/samples/server/petstore/go-api-server/go/api_pet_service.go @@ -29,6 +29,26 @@ func NewPetAPIService() *PetAPIService { return &PetAPIService{} } +// UpdatePet - Update an existing pet +func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { + // TODO - update UpdatePet with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ... + // return Response(200, Pet{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + + // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... + // return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented") +} + // AddPet - Add a new pet to the store func (s *PetAPIService) AddPet(ctx context.Context, pet Pet) (ImplResponse, error) { // TODO - update AddPet with the required logic for this service method. @@ -43,34 +63,35 @@ func (s *PetAPIService) AddPet(ctx context.Context, pet Pet) (ImplResponse, erro return Response(http.StatusNotImplemented, nil), errors.New("AddPet method not implemented") } -// DeletePet - Deletes a pet -func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) { - // TODO - update DeletePet with the required logic for this service method. +// FindPetsByStatus - Finds Pets by status +func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, inlineEnumPath string, inlineEnum string, defaultInt int32, defaultNum float32, defaultStr string) (ImplResponse, error) { + // TODO - update FindPetsByStatus with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... + // return Response(200, []Pet{}), nil + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByStatus method not implemented") } -// FilterPetsByCategory - Finds Pets -func (s *PetAPIService) FilterPetsByCategory(ctx context.Context, gender Gender, species Species, notSpecies []Species) (ImplResponse, error) { - // TODO - update FilterPetsByCategory with the required logic for this service method. +// SearchPet - Search Pets by filters +func (s *PetAPIService) SearchPet(ctx context.Context, age *int64, price *float32, bornAfter *time.Time, old *bool) (ImplResponse, error) { + // TODO - update SearchPet with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... // return Response(200, []Pet{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("FilterPetsByCategory method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("SearchPet method not implemented") } -// FindPetsByStatus - Finds Pets by status -func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, inlineEnumPath string, inlineEnum string, defaultInt int32, defaultNum float32, defaultStr string) (ImplResponse, error) { - // TODO - update FindPetsByStatus with the required logic for this service method. +// FindPetsByTags - Finds Pets by tags +// Deprecated +func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornAfter time.Time, bornBefore time.Time, colour Colour) (ImplResponse, error) { + // TODO - update FindPetsByTags with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... @@ -79,13 +100,12 @@ func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, i // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByStatus method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByTags method not implemented") } -// FindPetsByTags - Finds Pets by tags -// Deprecated -func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornAfter time.Time, bornBefore time.Time, colour Colour) (ImplResponse, error) { - // TODO - update FindPetsByTags with the required logic for this service method. +// FilterPetsByCategory - Finds Pets +func (s *PetAPIService) FilterPetsByCategory(ctx context.Context, gender Gender, species Species, notSpecies []Species) (ImplResponse, error) { + // TODO - update FilterPetsByCategory with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... @@ -94,7 +114,7 @@ func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornA // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByTags method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("FilterPetsByCategory method not implemented") } // GetPetById - Find pet by ID @@ -114,6 +134,28 @@ func (s *PetAPIService) GetPetById(ctx context.Context, petId int64) (ImplRespon return Response(http.StatusNotImplemented, nil), errors.New("GetPetById method not implemented") } +// UpdatePetWithForm - Updates a pet in the store with form data +func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) { + // TODO - update UpdatePetWithForm with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... + // return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented") +} + +// DeletePet - Deletes a pet +func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) { + // TODO - update DeletePet with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") +} + // GetPetImageById - Returns the image for the Pet that has been previously uploaded func (s *PetAPIService) GetPetImageById(ctx context.Context, petId int64) (ImplResponse, error) { // TODO - update GetPetImageById with the required logic for this service method. @@ -131,88 +173,46 @@ func (s *PetAPIService) GetPetImageById(ctx context.Context, petId int64) (ImplR return Response(http.StatusNotImplemented, nil), errors.New("GetPetImageById method not implemented") } -// GetPetsByTime - Get the pets by time -func (s *PetAPIService) GetPetsByTime(ctx context.Context, createdTime time.Time) (ImplResponse, error) { - // TODO - update GetPetsByTime with the required logic for this service method. +// UploadFile - uploads an image +func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, extraOptionalMetadata []string, file *os.File) (ImplResponse, error) { + // TODO - update UploadFile with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("GetPetsByTime method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UploadFile method not implemented") } -// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters -func (s *PetAPIService) GetPetsUsingBooleanQueryParameters(ctx context.Context, expr bool, grouping bool, inactive bool) (ImplResponse, error) { - // TODO - update GetPetsUsingBooleanQueryParameters with the required logic for this service method. +// UploadFileArrayOfFiles - uploads images (array of files) +func (s *PetAPIService) UploadFileArrayOfFiles(ctx context.Context, petId int64, additionalMetadata string, files []*os.File) (ImplResponse, error) { + // TODO - update UploadFileArrayOfFiles with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("GetPetsUsingBooleanQueryParameters method not implemented") -} - -// SearchPet - Search Pets by filters -func (s *PetAPIService) SearchPet(ctx context.Context, age *int64, price *float32, bornAfter *time.Time, old *bool) (ImplResponse, error) { - // TODO - update SearchPet with the required logic for this service method. - // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... - // return Response(200, []Pet{}), nil - - return Response(http.StatusNotImplemented, nil), errors.New("SearchPet method not implemented") -} - -// UpdatePet - Update an existing pet -func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { - // TODO - update UpdatePet with the required logic for this service method. - // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ... - // return Response(200, Pet{}), nil - - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil - - // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... - // return Response(405, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented") -} - -// UpdatePetWithForm - Updates a pet in the store with form data -func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) { - // TODO - update UpdatePetWithForm with the required logic for this service method. - // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... - // return Response(405, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UploadFileArrayOfFiles method not implemented") } -// UploadFile - uploads an image -func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, extraOptionalMetadata []string, file *os.File) (ImplResponse, error) { - // TODO - update UploadFile with the required logic for this service method. +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (s *PetAPIService) GetPetsUsingBooleanQueryParameters(ctx context.Context, expr bool, grouping bool, inactive bool) (ImplResponse, error) { + // TODO - update GetPetsUsingBooleanQueryParameters with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("UploadFile method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsUsingBooleanQueryParameters method not implemented") } -// UploadFileArrayOfFiles - uploads images (array of files) -func (s *PetAPIService) UploadFileArrayOfFiles(ctx context.Context, petId int64, additionalMetadata string, files []*os.File) (ImplResponse, error) { - // TODO - update UploadFileArrayOfFiles with the required logic for this service method. +// GetPetsByTime - Get the pets by time +func (s *PetAPIService) GetPetsByTime(ctx context.Context, createdTime time.Time) (ImplResponse, error) { + // TODO - update GetPetsByTime with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("UploadFileArrayOfFiles method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsByTime method not implemented") } diff --git a/samples/server/petstore/go-api-server/go/api_store.go b/samples/server/petstore/go-api-server/go/api_store.go index cc1caead0e8d..d8b75d9ec99b 100644 --- a/samples/server/petstore/go-api-server/go/api_store.go +++ b/samples/server/petstore/go-api-server/go/api_store.go @@ -51,38 +51,32 @@ func NewStoreAPIController(s StoreAPIServicer, opts ...StoreAPIOption) *StoreAPI // Routes returns all the api routes for the StoreAPIController func (c *StoreAPIController) Routes() Routes { return Routes{ - "DeleteOrder": Route{ - strings.ToUpper("Delete"), - "/v2/store/order/{orderId}", - c.DeleteOrder, - }, "GetInventory": Route{ strings.ToUpper("Get"), "/v2/store/inventory", c.GetInventory, }, + "PlaceOrder": Route{ + strings.ToUpper("Post"), + "/v2/store/order", + c.PlaceOrder, + }, "GetOrderById": Route{ strings.ToUpper("Get"), "/v2/store/order/{orderId}", c.GetOrderById, }, - "PlaceOrder": Route{ - strings.ToUpper("Post"), - "/v2/store/order", - c.PlaceOrder, + "DeleteOrder": Route{ + strings.ToUpper("Delete"), + "/v2/store/order/{orderId}", + c.DeleteOrder, }, } } -// DeleteOrder - Delete purchase order by ID -func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - orderIdParam := params["orderId"] - if orderIdParam == "" { - c.errorHandler(w, r, &RequiredError{"orderId"}, nil) - return - } - result, err := c.service.DeleteOrder(r.Context(), orderIdParam) +// GetInventory - Returns pet inventories by status +func (c *StoreAPIController) GetInventory(w http.ResponseWriter, r *http.Request) { + result, err := c.service.GetInventory(r.Context()) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -92,9 +86,24 @@ func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetInventory - Returns pet inventories by status -func (c *StoreAPIController) GetInventory(w http.ResponseWriter, r *http.Request) { - result, err := c.service.GetInventory(r.Context()) +// PlaceOrder - Place an order for a pet +func (c *StoreAPIController) PlaceOrder(w http.ResponseWriter, r *http.Request) { + orderParam := Order{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&orderParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + if err := AssertOrderRequired(orderParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + if err := AssertOrderConstraints(orderParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.PlaceOrder(r.Context(), orderParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -127,24 +136,15 @@ func (c *StoreAPIController) GetOrderById(w http.ResponseWriter, r *http.Request _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// PlaceOrder - Place an order for a pet -func (c *StoreAPIController) PlaceOrder(w http.ResponseWriter, r *http.Request) { - orderParam := Order{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&orderParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertOrderRequired(orderParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - if err := AssertOrderConstraints(orderParam); err != nil { - c.errorHandler(w, r, err, nil) +// DeleteOrder - Delete purchase order by ID +func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + orderIdParam := params["orderId"] + if orderIdParam == "" { + c.errorHandler(w, r, &RequiredError{"orderId"}, nil) return } - result, err := c.service.PlaceOrder(r.Context(), orderParam) + result, err := c.service.DeleteOrder(r.Context(), orderIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/samples/server/petstore/go-api-server/go/api_store_service.go b/samples/server/petstore/go-api-server/go/api_store_service.go index 46671f7a9fd9..b42eb74efb91 100644 --- a/samples/server/petstore/go-api-server/go/api_store_service.go +++ b/samples/server/petstore/go-api-server/go/api_store_service.go @@ -27,20 +27,6 @@ func NewStoreAPIService() *StoreAPIService { return &StoreAPIService{} } -// DeleteOrder - Delete purchase order by ID -func (s *StoreAPIService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) { - // TODO - update DeleteOrder with the required logic for this service method. - // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("DeleteOrder method not implemented") -} - // GetInventory - Returns pet inventories by status func (s *StoreAPIService) GetInventory(ctx context.Context) (ImplResponse, error) { // TODO - update GetInventory with the required logic for this service method. @@ -52,6 +38,20 @@ func (s *StoreAPIService) GetInventory(ctx context.Context) (ImplResponse, error return Response(http.StatusNotImplemented, nil), errors.New("GetInventory method not implemented") } +// PlaceOrder - Place an order for a pet +func (s *StoreAPIService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) { + // TODO - update PlaceOrder with the required logic for this service method. + // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ... + // return Response(200, Order{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("PlaceOrder method not implemented") +} + // GetOrderById - Find purchase order by ID func (s *StoreAPIService) GetOrderById(ctx context.Context, orderId int64) (ImplResponse, error) { // TODO - update GetOrderById with the required logic for this service method. @@ -69,16 +69,16 @@ func (s *StoreAPIService) GetOrderById(ctx context.Context, orderId int64) (Impl return Response(http.StatusNotImplemented, nil), errors.New("GetOrderById method not implemented") } -// PlaceOrder - Place an order for a pet -func (s *StoreAPIService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) { - // TODO - update PlaceOrder with the required logic for this service method. +// DeleteOrder - Delete purchase order by ID +func (s *StoreAPIService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) { + // TODO - update DeleteOrder with the required logic for this service method. // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ... - // return Response(200, Order{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("PlaceOrder method not implemented") + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeleteOrder method not implemented") } diff --git a/samples/server/petstore/go-api-server/go/api_user.go b/samples/server/petstore/go-api-server/go/api_user.go index f1917fa9b785..6486c8b720f9 100644 --- a/samples/server/petstore/go-api-server/go/api_user.go +++ b/samples/server/petstore/go-api-server/go/api_user.go @@ -66,16 +66,6 @@ func (c *UserAPIController) Routes() Routes { "/v2/user/createWithList", c.CreateUsersWithListInput, }, - "DeleteUser": Route{ - strings.ToUpper("Delete"), - "/v2/user/{username}", - c.DeleteUser, - }, - "GetUserByName": Route{ - strings.ToUpper("Get"), - "/v2/user/{username}", - c.GetUserByName, - }, "LoginUser": Route{ strings.ToUpper("Get"), "/v2/user/login", @@ -86,11 +76,21 @@ func (c *UserAPIController) Routes() Routes { "/v2/user/logout", c.LogoutUser, }, + "GetUserByName": Route{ + strings.ToUpper("Get"), + "/v2/user/{username}", + c.GetUserByName, + }, "UpdateUser": Route{ strings.ToUpper("Put"), "/v2/user/{username}", c.UpdateUser, }, + "DeleteUser": Route{ + strings.ToUpper("Delete"), + "/v2/user/{username}", + c.DeleteUser, + }, } } @@ -171,61 +171,6 @@ func (c *UserAPIController) CreateUsersWithListInput(w http.ResponseWriter, r *h _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// DeleteUser - Delete user -func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - query, err := parseQuery(r.URL.RawQuery) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - usernameParam := params["username"] - if usernameParam == "" { - c.errorHandler(w, r, &RequiredError{"username"}, nil) - return - } - var confirmationParam bool - if query.Has("confirmation") { - param, err := parseBoolParameter( - query.Get("confirmation"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "confirmation", Err: err}, nil) - return - } - - confirmationParam = param - } else { - } - result, err := c.service.DeleteUser(r.Context(), usernameParam, confirmationParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// GetUserByName - Get user by user name -func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - usernameParam := params["username"] - if usernameParam == "" { - c.errorHandler(w, r, &RequiredError{"username"}, nil) - return - } - result, err := c.service.GetUserByName(r.Context(), usernameParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - // LoginUser - Logs user into the system func (c *UserAPIController) LoginUser(w http.ResponseWriter, r *http.Request) { query, err := parseQuery(r.URL.RawQuery) @@ -287,6 +232,24 @@ func (c *UserAPIController) LogoutUser(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// GetUserByName - Get user by user name +func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + usernameParam := params["username"] + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } + result, err := c.service.GetUserByName(r.Context(), usernameParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // UpdateUser - Updated user func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) @@ -319,3 +282,40 @@ func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { // If no error, encode the body and the result code _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } + +// DeleteUser - Delete user +func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + query, err := parseQuery(r.URL.RawQuery) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + usernameParam := params["username"] + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } + var confirmationParam bool + if query.Has("confirmation") { + param, err := parseBoolParameter( + query.Get("confirmation"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "confirmation", Err: err}, nil) + return + } + + confirmationParam = param + } else { + } + result, err := c.service.DeleteUser(r.Context(), usernameParam, confirmationParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} diff --git a/samples/server/petstore/go-api-server/go/api_user_service.go b/samples/server/petstore/go-api-server/go/api_user_service.go index 62332a09da48..f117afb35ef9 100644 --- a/samples/server/petstore/go-api-server/go/api_user_service.go +++ b/samples/server/petstore/go-api-server/go/api_user_service.go @@ -60,18 +60,29 @@ func (s *UserAPIService) CreateUsersWithListInput(ctx context.Context, user []Us return Response(http.StatusNotImplemented, nil), errors.New("CreateUsersWithListInput method not implemented") } -// DeleteUser - Delete user -func (s *UserAPIService) DeleteUser(ctx context.Context, username string, confirmation bool) (ImplResponse, error) { - // TODO - update DeleteUser with the required logic for this service method. +// LoginUser - Logs user into the system +func (s *UserAPIService) LoginUser(ctx context.Context, username string, password string, rememberMe bool) (ImplResponse, error) { + // TODO - update LoginUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + // TODO: Uncomment the next line to return response Response(200, string{}) or use other options such as http.Ok ... + // return Response(200, string{}), nil + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil + return Response(http.StatusNotImplemented, nil), errors.New("LoginUser method not implemented") +} - return Response(http.StatusNotImplemented, nil), errors.New("DeleteUser method not implemented") +// LogoutUser - Logs out current logged in user session +func (s *UserAPIService) LogoutUser(ctx context.Context) (ImplResponse, error) { + // TODO - update LogoutUser with the required logic for this service method. + // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ... + // return Response(0, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented") } // GetUserByName - Get user by user name @@ -91,34 +102,23 @@ func (s *UserAPIService) GetUserByName(ctx context.Context, username string) (Im return Response(http.StatusNotImplemented, nil), errors.New("GetUserByName method not implemented") } -// LoginUser - Logs user into the system -func (s *UserAPIService) LoginUser(ctx context.Context, username string, password string, rememberMe bool) (ImplResponse, error) { - // TODO - update LoginUser with the required logic for this service method. +// UpdateUser - Updated user +func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) { + // TODO - update UpdateUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(200, string{}) or use other options such as http.Ok ... - // return Response(200, string{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("LoginUser method not implemented") -} - -// LogoutUser - Logs out current logged in user session -func (s *UserAPIService) LogoutUser(ctx context.Context) (ImplResponse, error) { - // TODO - update LogoutUser with the required logic for this service method. - // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ... - // return Response(0, nil),nil + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UpdateUser method not implemented") } -// UpdateUser - Updated user -func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) { - // TODO - update UpdateUser with the required logic for this service method. +// DeleteUser - Delete user +func (s *UserAPIService) DeleteUser(ctx context.Context, username string, confirmation bool) (ImplResponse, error) { + // TODO - update DeleteUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... @@ -127,5 +127,5 @@ func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user U // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... // return Response(404, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("UpdateUser method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("DeleteUser method not implemented") } diff --git a/samples/server/petstore/go-api-server/samples_tests/README.md b/samples/server/petstore/go-api-server/samples_tests/README.md new file mode 100644 index 000000000000..ebddd9165828 --- /dev/null +++ b/samples/server/petstore/go-api-server/samples_tests/README.md @@ -0,0 +1,3 @@ +This folder contains the tests to verify the correctness of the generate samples + +Those tests are not generated by the OpenAPI Generator \ No newline at end of file diff --git a/samples/server/petstore/go-api-server/samples_tests/api_pet_test.go b/samples/server/petstore/go-api-server/samples_tests/api_pet_test.go new file mode 100644 index 000000000000..c66ba7531d15 --- /dev/null +++ b/samples/server/petstore/go-api-server/samples_tests/api_pet_test.go @@ -0,0 +1,26 @@ +package main + +import ( + "strings" + "testing" + + "github.com/GIT_USER_ID/GIT_REPO_ID/samples_tests/utils" +) + +func Test_API_Pet(t *testing.T) { + + t.Run("Check DeletePet route exists", func(t *testing.T) { + + filepath := "../go/api_pet.go" + + expected := ("\t\t\"DeletePet\": Route{\n" + + "\t\t\tstrings.ToUpper(\"Delete\"),\n" + + "\t\t\t\"/v2/pet/{petId}\",\n" + + "\t\t\tc.DeletePet,\n" + + "\t\t}") + + if !strings.Contains(utils.ReadContent(filepath), expected) { + t.Errorf("Route was not found in the file") + } + }) +} diff --git a/samples/server/petstore/go-api-server/samples_tests/go_mod_test.go b/samples/server/petstore/go-api-server/samples_tests/go_mod_test.go new file mode 100644 index 000000000000..75c769eb2bce --- /dev/null +++ b/samples/server/petstore/go-api-server/samples_tests/go_mod_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "testing" + + "github.com/GIT_USER_ID/GIT_REPO_ID/samples_tests/utils" +) + +func Test_Go_Mod(t *testing.T) { + + t.Run("Check module", func(t *testing.T) { + + filepath := "../go.mod" + + lines := utils.ReadLines(filepath) + expected := "module github.com/GIT_USER_ID/GIT_REPO_ID" + + if lines[0] != expected { + t.Errorf("Expected '%s', but got '%s'", expected, lines[0]) + } + }) + + t.Run("Check Go version", func(t *testing.T) { + + filepath := "../go.mod" + + lines := utils.ReadLines(filepath) + expected := "go 1.18" + + if lines[2] != expected { + t.Errorf("Expected '%s', but got '%s'", expected, lines[2]) + } + }) + +} diff --git a/samples/server/petstore/go-api-server/samples_tests/model_pet_test.go b/samples/server/petstore/go-api-server/samples_tests/model_pet_test.go new file mode 100644 index 000000000000..5835268b81de --- /dev/null +++ b/samples/server/petstore/go-api-server/samples_tests/model_pet_test.go @@ -0,0 +1,22 @@ +package main + +import ( + "testing" + + "github.com/GIT_USER_ID/GIT_REPO_ID/samples_tests/utils" +) + +func Test_Model_Pet(t *testing.T) { + + t.Run("Check Pet model exists", func(t *testing.T) { + + filepath := "../go/model_pet.go" + + lines := utils.ReadLines(filepath) + expected := "\tId int64 `json:\"id,omitempty\"`" + + if lines[18] != expected { + t.Errorf("Expected '%s', but got '%s'", expected, lines[18]) + } + }) +} diff --git a/samples/server/petstore/go-api-server/samples_tests/routers_test.go b/samples/server/petstore/go-api-server/samples_tests/routers_test.go new file mode 100644 index 000000000000..6c2686fb86d9 --- /dev/null +++ b/samples/server/petstore/go-api-server/samples_tests/routers_test.go @@ -0,0 +1,38 @@ +package main + +import ( + "testing" + "strings" + + "github.com/GIT_USER_ID/GIT_REPO_ID/samples_tests/utils" +) + +func Test_Routers(t *testing.T) { + + t.Run("Check struct Route exists", func(t *testing.T) { + + filepath := "../go/routers.go" + + expected := ("type Route struct {\n" + + "\tMethod\t string\n" + + "\tPattern\t string\n" + + "\tHandlerFunc http.HandlerFunc\n" + + "}") + + if !strings.Contains(utils.ReadContent(filepath), expected) { + t.Errorf("Type Route was not found in the file") + } + }) + + t.Run("Check map Routes exists", func(t *testing.T) { + + filepath := "../go/routers.go" + + lines := utils.ReadLines(filepath) + expected := "type Routes map[string]Route" + + if lines[34] != expected { + t.Errorf("Expected '%s', but got '%s'", expected, lines[34]) + } + }) +} diff --git a/samples/server/petstore/go-api-server/samples_tests/utils/fileutils.go b/samples/server/petstore/go-api-server/samples_tests/utils/fileutils.go new file mode 100644 index 000000000000..6253ed8da28f --- /dev/null +++ b/samples/server/petstore/go-api-server/samples_tests/utils/fileutils.go @@ -0,0 +1,51 @@ +package utils + +import ( + "bufio" + "os" + "strings" +) + +// Load file content as array of lines +func ReadLines(filePath string) ([]string) { + var lines []string + + file, err := os.Open(filePath) + if err != nil { + panic("Cannot open file " + filePath); + } + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + + if err := scanner.Err(); err != nil { + panic("Cannot scan file " + filePath); + } + + return lines +} + +// Load file content as string +func ReadContent(filePath string) (string) { + file, err := os.Open(filePath) + if err != nil { + panic("Cannot open file " + filePath); + } + defer file.Close() + + var contentBuilder strings.Builder + scanner := bufio.NewScanner(file) + + for scanner.Scan() { + contentBuilder.WriteString(scanner.Text() + "\n") + } + + if err := scanner.Err(); err != nil { + panic("Cannot scan file " + filePath); + } + + return contentBuilder.String() +} \ No newline at end of file diff --git a/samples/server/petstore/go-chi-server/go/api.go b/samples/server/petstore/go-chi-server/go/api.go index 23d5213c5a63..b6f9945682d4 100644 --- a/samples/server/petstore/go-chi-server/go/api.go +++ b/samples/server/petstore/go-chi-server/go/api.go @@ -23,30 +23,30 @@ import ( // The PetAPIRouter implementation should parse necessary information from the http request, // pass the data to a PetAPIServicer to perform the required actions, then write the service results to the http response. type PetAPIRouter interface { + UpdatePet(http.ResponseWriter, *http.Request) AddPet(http.ResponseWriter, *http.Request) - DeletePet(http.ResponseWriter, *http.Request) - FilterPetsByCategory(http.ResponseWriter, *http.Request) FindPetsByStatus(http.ResponseWriter, *http.Request) + SearchPet(http.ResponseWriter, *http.Request) // Deprecated FindPetsByTags(http.ResponseWriter, *http.Request) + FilterPetsByCategory(http.ResponseWriter, *http.Request) GetPetById(http.ResponseWriter, *http.Request) - GetPetImageById(http.ResponseWriter, *http.Request) - GetPetsByTime(http.ResponseWriter, *http.Request) - GetPetsUsingBooleanQueryParameters(http.ResponseWriter, *http.Request) - SearchPet(http.ResponseWriter, *http.Request) - UpdatePet(http.ResponseWriter, *http.Request) UpdatePetWithForm(http.ResponseWriter, *http.Request) + DeletePet(http.ResponseWriter, *http.Request) + GetPetImageById(http.ResponseWriter, *http.Request) UploadFile(http.ResponseWriter, *http.Request) UploadFileArrayOfFiles(http.ResponseWriter, *http.Request) + GetPetsUsingBooleanQueryParameters(http.ResponseWriter, *http.Request) + GetPetsByTime(http.ResponseWriter, *http.Request) } // StoreAPIRouter defines the required methods for binding the api requests to a responses for the StoreAPI // The StoreAPIRouter implementation should parse necessary information from the http request, // pass the data to a StoreAPIServicer to perform the required actions, then write the service results to the http response. type StoreAPIRouter interface { - DeleteOrder(http.ResponseWriter, *http.Request) GetInventory(http.ResponseWriter, *http.Request) - GetOrderById(http.ResponseWriter, *http.Request) PlaceOrder(http.ResponseWriter, *http.Request) + GetOrderById(http.ResponseWriter, *http.Request) + DeleteOrder(http.ResponseWriter, *http.Request) } // UserAPIRouter defines the required methods for binding the api requests to a responses for the UserAPI // The UserAPIRouter implementation should parse necessary information from the http request, @@ -55,11 +55,11 @@ type UserAPIRouter interface { CreateUser(http.ResponseWriter, *http.Request) CreateUsersWithArrayInput(http.ResponseWriter, *http.Request) CreateUsersWithListInput(http.ResponseWriter, *http.Request) - DeleteUser(http.ResponseWriter, *http.Request) - GetUserByName(http.ResponseWriter, *http.Request) LoginUser(http.ResponseWriter, *http.Request) LogoutUser(http.ResponseWriter, *http.Request) + GetUserByName(http.ResponseWriter, *http.Request) UpdateUser(http.ResponseWriter, *http.Request) + DeleteUser(http.ResponseWriter, *http.Request) } @@ -68,21 +68,21 @@ type UserAPIRouter interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type PetAPIServicer interface { + UpdatePet(context.Context, Pet) (ImplResponse, error) AddPet(context.Context, Pet) (ImplResponse, error) - DeletePet(context.Context, int64, string) (ImplResponse, error) - FilterPetsByCategory(context.Context, Gender, Species, []Species) (ImplResponse, error) FindPetsByStatus(context.Context, []string, string, string, int32, float32, string) (ImplResponse, error) + SearchPet(context.Context, *int64, *float32, *time.Time, *bool) (ImplResponse, error) // Deprecated FindPetsByTags(context.Context, []string, time.Time, time.Time, Colour) (ImplResponse, error) + FilterPetsByCategory(context.Context, Gender, Species, []Species) (ImplResponse, error) GetPetById(context.Context, int64) (ImplResponse, error) - GetPetImageById(context.Context, int64) (ImplResponse, error) - GetPetsByTime(context.Context, time.Time) (ImplResponse, error) - GetPetsUsingBooleanQueryParameters(context.Context, bool, bool, bool) (ImplResponse, error) - SearchPet(context.Context, *int64, *float32, *time.Time, *bool) (ImplResponse, error) - UpdatePet(context.Context, Pet) (ImplResponse, error) UpdatePetWithForm(context.Context, int64, string, string) (ImplResponse, error) + DeletePet(context.Context, int64, string) (ImplResponse, error) + GetPetImageById(context.Context, int64) (ImplResponse, error) UploadFile(context.Context, int64, string, []string, *os.File) (ImplResponse, error) UploadFileArrayOfFiles(context.Context, int64, string, []*os.File) (ImplResponse, error) + GetPetsUsingBooleanQueryParameters(context.Context, bool, bool, bool) (ImplResponse, error) + GetPetsByTime(context.Context, time.Time) (ImplResponse, error) } @@ -91,10 +91,10 @@ type PetAPIServicer interface { // while the service implementation can be ignored with the .openapi-generator-ignore file // and updated with the logic required for the API. type StoreAPIServicer interface { - DeleteOrder(context.Context, string) (ImplResponse, error) GetInventory(context.Context) (ImplResponse, error) - GetOrderById(context.Context, int64) (ImplResponse, error) PlaceOrder(context.Context, Order) (ImplResponse, error) + GetOrderById(context.Context, int64) (ImplResponse, error) + DeleteOrder(context.Context, string) (ImplResponse, error) } @@ -106,9 +106,9 @@ type UserAPIServicer interface { CreateUser(context.Context, User) (ImplResponse, error) CreateUsersWithArrayInput(context.Context, []User) (ImplResponse, error) CreateUsersWithListInput(context.Context, []User) (ImplResponse, error) - DeleteUser(context.Context, string, bool) (ImplResponse, error) - GetUserByName(context.Context, string) (ImplResponse, error) LoginUser(context.Context, string, string, bool) (ImplResponse, error) LogoutUser(context.Context) (ImplResponse, error) + GetUserByName(context.Context, string) (ImplResponse, error) UpdateUser(context.Context, string, User) (ImplResponse, error) + DeleteUser(context.Context, string, bool) (ImplResponse, error) } diff --git a/samples/server/petstore/go-chi-server/go/api_pet.go b/samples/server/petstore/go-chi-server/go/api_pet.go index a4b5448a0686..c455813ad35d 100644 --- a/samples/server/petstore/go-chi-server/go/api_pet.go +++ b/samples/server/petstore/go-chi-server/go/api_pet.go @@ -53,66 +53,56 @@ func NewPetAPIController(s PetAPIServicer, opts ...PetAPIOption) *PetAPIControll // Routes returns all the api routes for the PetAPIController func (c *PetAPIController) Routes() Routes { return Routes{ + "UpdatePet": Route{ + strings.ToUpper("Put"), + "/v2/pet", + c.UpdatePet, + }, "AddPet": Route{ strings.ToUpper("Post"), "/v2/pet", c.AddPet, }, - "DeletePet": Route{ - strings.ToUpper("Delete"), - "/v2/pet/{petId}", - c.DeletePet, - }, - "FilterPetsByCategory": Route{ - strings.ToUpper("Get"), - "/v2/pet/filterPets/{gender}", - c.FilterPetsByCategory, - }, "FindPetsByStatus": Route{ strings.ToUpper("Get"), "/v2/pet/findByStatus", c.FindPetsByStatus, }, + "SearchPet": Route{ + strings.ToUpper("Get"), + "/v2/pet/searchPetWithManyFilters", + c.SearchPet, + }, "FindPetsByTags": Route{ strings.ToUpper("Get"), "/v2/pet/findByTags", c.FindPetsByTags, }, + "FilterPetsByCategory": Route{ + strings.ToUpper("Get"), + "/v2/pet/filterPets/{gender}", + c.FilterPetsByCategory, + }, "GetPetById": Route{ strings.ToUpper("Get"), "/v2/pet/{petId}", c.GetPetById, }, - "GetPetImageById": Route{ - strings.ToUpper("Get"), - "/v2/pet/{petId}/uploadImage", - c.GetPetImageById, - }, - "GetPetsByTime": Route{ - strings.ToUpper("Get"), - "/v2/pets/byTime/{createdTime}", - c.GetPetsByTime, - }, - "GetPetsUsingBooleanQueryParameters": Route{ - strings.ToUpper("Get"), - "/v2/pets/boolean/parsing", - c.GetPetsUsingBooleanQueryParameters, - }, - "SearchPet": Route{ - strings.ToUpper("Get"), - "/v2/pet/searchPetWithManyFilters", - c.SearchPet, - }, - "UpdatePet": Route{ - strings.ToUpper("Put"), - "/v2/pet", - c.UpdatePet, - }, "UpdatePetWithForm": Route{ strings.ToUpper("Post"), "/v2/pet/{petId}", c.UpdatePetWithForm, }, + "DeletePet": Route{ + strings.ToUpper("Delete"), + "/v2/pet/{petId}", + c.DeletePet, + }, + "GetPetImageById": Route{ + strings.ToUpper("Get"), + "/v2/pet/{petId}/uploadImage", + c.GetPetImageById, + }, "UploadFile": Route{ strings.ToUpper("Post"), "/v2/pet/{petId}/uploadImage", @@ -123,11 +113,21 @@ func (c *PetAPIController) Routes() Routes { "/v2/fake/uploadImage/array of_file", c.UploadFileArrayOfFiles, }, + "GetPetsUsingBooleanQueryParameters": Route{ + strings.ToUpper("Get"), + "/v2/pets/boolean/parsing", + c.GetPetsUsingBooleanQueryParameters, + }, + "GetPetsByTime": Route{ + strings.ToUpper("Get"), + "/v2/pets/byTime/{createdTime}", + c.GetPetsByTime, + }, } } -// AddPet - Add a new pet to the store -func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { +// UpdatePet - Update an existing pet +func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { petParam := Pet{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() @@ -143,28 +143,7 @@ func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { c.errorHandler(w, r, err, nil) return } - result, err := c.service.AddPet(r.Context(), petParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// DeletePet - Deletes a pet -func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { - petIdParam, err := parseNumericParameter[int64]( - chi.URLParam(r, "petId"), - WithRequire[int64](parseInt64), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) - return - } - apiKeyParam := r.Header.Get("api_key") - result, err := c.service.DeletePet(r.Context(), petIdParam, apiKeyParam) + result, err := c.service.UpdatePet(r.Context(), petParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -174,41 +153,24 @@ func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// FilterPetsByCategory - Finds Pets -func (c *PetAPIController) FilterPetsByCategory(w http.ResponseWriter, r *http.Request) { - query, err := parseQuery(r.URL.RawQuery) - if err != nil { +// AddPet - Add a new pet to the store +func (c *PetAPIController) AddPet(w http.ResponseWriter, r *http.Request) { + petParam := Pet{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&petParam); err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - genderParam, err := NewGenderFromValue(chi.URLParam(r, "gender")) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "gender", Err: err}, nil) + if err := AssertPetRequired(petParam); err != nil { + c.errorHandler(w, r, err, nil) return } - var speciesParam Species - if query.Has("species") { - param := Species(query.Get("species")) - - speciesParam = param - } else { - c.errorHandler(w, r, &RequiredError{Field: "species"}, nil) + if err := AssertPetConstraints(petParam); err != nil { + c.errorHandler(w, r, err, nil) return } - var notSpeciesParam []Species - if query.Has("notSpecies") { - paramSplits := strings.Split(query.Get("notSpecies"), ",") - notSpeciesParam = make([]Species, 0, len(paramSplits)) - for _, param := range paramSplits { - paramEnum, err := NewSpeciesFromValue(param) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "notSpecies", Err: err}, nil) - return - } - notSpeciesParam = append(notSpeciesParam, paramEnum) - } - } - result, err := c.service.FilterPetsByCategory(r.Context(), genderParam, speciesParam, notSpeciesParam) + result, err := c.service.AddPet(r.Context(), petParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -292,6 +254,76 @@ func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Reque _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// SearchPet - Search Pets by filters +func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { + query, err := parseQuery(r.URL.RawQuery) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + var ageParam *int64 + if query.Has("age") { + param, err := parseNumericParameter[int64]( + query.Get("age"), + WithParse[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "age", Err: err}, nil) + return + } + + ageParam = ¶m + } else { + } + var priceParam *float32 + if query.Has("price") { + param, err := parseNumericParameter[float32]( + query.Get("price"), + WithParse[float32](parseFloat32), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "price", Err: err}, nil) + return + } + + priceParam = ¶m + } else { + } + var bornAfterParam *time.Time + if query.Has("bornAfter"){ + param, err := parseTime(query.Get("bornAfter")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "bornAfter", Err: err}, nil) + return + } + + bornAfterParam = ¶m + } else { + } + var oldParam *bool + if query.Has("old") { + param, err := parseBoolParameter( + query.Get("old"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "old", Err: err}, nil) + return + } + + oldParam = ¶m + } else { + } + result, err := c.service.SearchPet(r.Context(), ageParam, priceParam, bornAfterParam, oldParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // FindPetsByTags - Finds Pets by tags // Deprecated func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request) { @@ -345,17 +377,41 @@ func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetPetById - Find pet by ID -func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { - petIdParam, err := parseNumericParameter[int64]( - chi.URLParam(r, "petId"), - WithRequire[int64](parseInt64), - ) +// FilterPetsByCategory - Finds Pets +func (c *PetAPIController) FilterPetsByCategory(w http.ResponseWriter, r *http.Request) { + query, err := parseQuery(r.URL.RawQuery) if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) + c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - result, err := c.service.GetPetById(r.Context(), petIdParam) + genderParam, err := NewGenderFromValue(chi.URLParam(r, "gender")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "gender", Err: err}, nil) + return + } + var speciesParam Species + if query.Has("species") { + param := Species(query.Get("species")) + + speciesParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "species"}, nil) + return + } + var notSpeciesParam []Species + if query.Has("notSpecies") { + paramSplits := strings.Split(query.Get("notSpecies"), ",") + notSpeciesParam = make([]Species, 0, len(paramSplits)) + for _, param := range paramSplits { + paramEnum, err := NewSpeciesFromValue(param) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "notSpecies", Err: err}, nil) + return + } + notSpeciesParam = append(notSpeciesParam, paramEnum) + } + } + result, err := c.service.FilterPetsByCategory(r.Context(), genderParam, speciesParam, notSpeciesParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -365,8 +421,8 @@ func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetPetImageById - Returns the image for the Pet that has been previously uploaded -func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Request) { +// GetPetById - Find pet by ID +func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { petIdParam, err := parseNumericParameter[int64]( chi.URLParam(r, "petId"), WithRequire[int64](parseInt64), @@ -375,7 +431,7 @@ func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Reques c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - result, err := c.service.GetPetImageById(r.Context(), petIdParam) + result, err := c.service.GetPetById(r.Context(), petIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -385,147 +441,27 @@ func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Reques _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetPetsByTime - Get the pets by time -func (c *PetAPIController) GetPetsByTime(w http.ResponseWriter, r *http.Request) { - createdTimeParam, err := parseTime(chi.URLParam(r, "createdTime")) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "createdTime", Err: err}, nil) - return - } - result, err := c.service.GetPetsByTime(r.Context(), createdTimeParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters -func (c *PetAPIController) GetPetsUsingBooleanQueryParameters(w http.ResponseWriter, r *http.Request) { - query, err := parseQuery(r.URL.RawQuery) - if err != nil { +// UpdatePetWithForm - Updates a pet in the store with form data +func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - var exprParam bool - if query.Has("expr") { - param, err := parseBoolParameter( - query.Get("expr"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "expr", Err: err}, nil) - return - } - - exprParam = param - } else { - c.errorHandler(w, r, &RequiredError{Field: "expr"}, nil) - return - } - var groupingParam bool - if query.Has("grouping") { - param, err := parseBoolParameter( - query.Get("grouping"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "grouping", Err: err}, nil) - return - } - - groupingParam = param - } else { - } - var inactiveParam bool - if query.Has("inactive") { - param, err := parseBoolParameter( - query.Get("inactive"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "inactive", Err: err}, nil) - return - } - - inactiveParam = param - } else { - var param bool = false - inactiveParam = param - } - result, err := c.service.GetPetsUsingBooleanQueryParameters(r.Context(), exprParam, groupingParam, inactiveParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// SearchPet - Search Pets by filters -func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { - query, err := parseQuery(r.URL.RawQuery) + petIdParam, err := parseNumericParameter[int64]( + chi.URLParam(r, "petId"), + WithRequire[int64](parseInt64), + ) if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - var ageParam *int64 - if query.Has("age") { - param, err := parseNumericParameter[int64]( - query.Get("age"), - WithParse[int64](parseInt64), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "age", Err: err}, nil) - return - } - - ageParam = ¶m - } else { - } - var priceParam *float32 - if query.Has("price") { - param, err := parseNumericParameter[float32]( - query.Get("price"), - WithParse[float32](parseFloat32), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "price", Err: err}, nil) - return - } - - priceParam = ¶m - } else { - } - var bornAfterParam *time.Time - if query.Has("bornAfter"){ - param, err := parseTime(query.Get("bornAfter")) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "bornAfter", Err: err}, nil) - return - } - - bornAfterParam = ¶m - } else { - } - var oldParam *bool - if query.Has("old") { - param, err := parseBoolParameter( - query.Get("old"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "old", Err: err}, nil) - return - } - - oldParam = ¶m - } else { - } - result, err := c.service.SearchPet(r.Context(), ageParam, priceParam, bornAfterParam, oldParam) + + + nameParam := r.FormValue("name") + + + statusParam := r.FormValue("status") + result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -535,24 +471,18 @@ func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// UpdatePet - Update an existing pet -func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { - petParam := Pet{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&petParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertPetRequired(petParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - if err := AssertPetConstraints(petParam); err != nil { - c.errorHandler(w, r, err, nil) +// DeletePet - Deletes a pet +func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { + petIdParam, err := parseNumericParameter[int64]( + chi.URLParam(r, "petId"), + WithRequire[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - result, err := c.service.UpdatePet(r.Context(), petParam) + apiKeyParam := r.Header.Get("api_key") + result, err := c.service.DeletePet(r.Context(), petIdParam, apiKeyParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -562,12 +492,8 @@ func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// UpdatePetWithForm - Updates a pet in the store with form data -func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Request) { - if err := r.ParseForm(); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } +// GetPetImageById - Returns the image for the Pet that has been previously uploaded +func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Request) { petIdParam, err := parseNumericParameter[int64]( chi.URLParam(r, "petId"), WithRequire[int64](parseInt64), @@ -576,13 +502,7 @@ func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Requ c.errorHandler(w, r, &ParsingError{Param: "petId", Err: err}, nil) return } - - - nameParam := r.FormValue("name") - - - statusParam := r.FormValue("status") - result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) + result, err := c.service.GetPetImageById(r.Context(), petIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -672,3 +592,83 @@ func (c *PetAPIController) UploadFileArrayOfFiles(w http.ResponseWriter, r *http // If no error, encode the body and the result code _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } + +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (c *PetAPIController) GetPetsUsingBooleanQueryParameters(w http.ResponseWriter, r *http.Request) { + query, err := parseQuery(r.URL.RawQuery) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + var exprParam bool + if query.Has("expr") { + param, err := parseBoolParameter( + query.Get("expr"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "expr", Err: err}, nil) + return + } + + exprParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "expr"}, nil) + return + } + var groupingParam bool + if query.Has("grouping") { + param, err := parseBoolParameter( + query.Get("grouping"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "grouping", Err: err}, nil) + return + } + + groupingParam = param + } else { + } + var inactiveParam bool + if query.Has("inactive") { + param, err := parseBoolParameter( + query.Get("inactive"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "inactive", Err: err}, nil) + return + } + + inactiveParam = param + } else { + var param bool = false + inactiveParam = param + } + result, err := c.service.GetPetsUsingBooleanQueryParameters(r.Context(), exprParam, groupingParam, inactiveParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// GetPetsByTime - Get the pets by time +func (c *PetAPIController) GetPetsByTime(w http.ResponseWriter, r *http.Request) { + createdTimeParam, err := parseTime(chi.URLParam(r, "createdTime")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "createdTime", Err: err}, nil) + return + } + result, err := c.service.GetPetsByTime(r.Context(), createdTimeParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} diff --git a/samples/server/petstore/go-chi-server/go/api_pet_service.go b/samples/server/petstore/go-chi-server/go/api_pet_service.go index 9786bd5f71ab..4c6abe83dec7 100644 --- a/samples/server/petstore/go-chi-server/go/api_pet_service.go +++ b/samples/server/petstore/go-chi-server/go/api_pet_service.go @@ -29,6 +29,26 @@ func NewPetAPIService() *PetAPIService { return &PetAPIService{} } +// UpdatePet - Update an existing pet +func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { + // TODO - update UpdatePet with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ... + // return Response(200, Pet{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + + // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... + // return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented") +} + // AddPet - Add a new pet to the store func (s *PetAPIService) AddPet(ctx context.Context, pet Pet) (ImplResponse, error) { // TODO - update AddPet with the required logic for this service method. @@ -43,34 +63,35 @@ func (s *PetAPIService) AddPet(ctx context.Context, pet Pet) (ImplResponse, erro return Response(http.StatusNotImplemented, nil), errors.New("AddPet method not implemented") } -// DeletePet - Deletes a pet -func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) { - // TODO - update DeletePet with the required logic for this service method. +// FindPetsByStatus - Finds Pets by status +func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, inlineEnumPath string, inlineEnum string, defaultInt int32, defaultNum float32, defaultStr string) (ImplResponse, error) { + // TODO - update FindPetsByStatus with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... + // return Response(200, []Pet{}), nil + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByStatus method not implemented") } -// FilterPetsByCategory - Finds Pets -func (s *PetAPIService) FilterPetsByCategory(ctx context.Context, gender Gender, species Species, notSpecies []Species) (ImplResponse, error) { - // TODO - update FilterPetsByCategory with the required logic for this service method. +// SearchPet - Search Pets by filters +func (s *PetAPIService) SearchPet(ctx context.Context, age *int64, price *float32, bornAfter *time.Time, old *bool) (ImplResponse, error) { + // TODO - update SearchPet with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... // return Response(200, []Pet{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("FilterPetsByCategory method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("SearchPet method not implemented") } -// FindPetsByStatus - Finds Pets by status -func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, inlineEnumPath string, inlineEnum string, defaultInt int32, defaultNum float32, defaultStr string) (ImplResponse, error) { - // TODO - update FindPetsByStatus with the required logic for this service method. +// FindPetsByTags - Finds Pets by tags +// Deprecated +func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornAfter time.Time, bornBefore time.Time, colour Colour) (ImplResponse, error) { + // TODO - update FindPetsByTags with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... @@ -79,13 +100,12 @@ func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, i // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByStatus method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByTags method not implemented") } -// FindPetsByTags - Finds Pets by tags -// Deprecated -func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornAfter time.Time, bornBefore time.Time, colour Colour) (ImplResponse, error) { - // TODO - update FindPetsByTags with the required logic for this service method. +// FilterPetsByCategory - Finds Pets +func (s *PetAPIService) FilterPetsByCategory(ctx context.Context, gender Gender, species Species, notSpecies []Species) (ImplResponse, error) { + // TODO - update FilterPetsByCategory with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... @@ -94,7 +114,7 @@ func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornA // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("FindPetsByTags method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("FilterPetsByCategory method not implemented") } // GetPetById - Find pet by ID @@ -114,6 +134,28 @@ func (s *PetAPIService) GetPetById(ctx context.Context, petId int64) (ImplRespon return Response(http.StatusNotImplemented, nil), errors.New("GetPetById method not implemented") } +// UpdatePetWithForm - Updates a pet in the store with form data +func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) { + // TODO - update UpdatePetWithForm with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... + // return Response(405, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented") +} + +// DeletePet - Deletes a pet +func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey string) (ImplResponse, error) { + // TODO - update DeletePet with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") +} + // GetPetImageById - Returns the image for the Pet that has been previously uploaded func (s *PetAPIService) GetPetImageById(ctx context.Context, petId int64) (ImplResponse, error) { // TODO - update GetPetImageById with the required logic for this service method. @@ -131,88 +173,46 @@ func (s *PetAPIService) GetPetImageById(ctx context.Context, petId int64) (ImplR return Response(http.StatusNotImplemented, nil), errors.New("GetPetImageById method not implemented") } -// GetPetsByTime - Get the pets by time -func (s *PetAPIService) GetPetsByTime(ctx context.Context, createdTime time.Time) (ImplResponse, error) { - // TODO - update GetPetsByTime with the required logic for this service method. +// UploadFile - uploads an image +func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, extraOptionalMetadata []string, file *os.File) (ImplResponse, error) { + // TODO - update UploadFile with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("GetPetsByTime method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UploadFile method not implemented") } -// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters -func (s *PetAPIService) GetPetsUsingBooleanQueryParameters(ctx context.Context, expr bool, grouping bool, inactive bool) (ImplResponse, error) { - // TODO - update GetPetsUsingBooleanQueryParameters with the required logic for this service method. +// UploadFileArrayOfFiles - uploads images (array of files) +func (s *PetAPIService) UploadFileArrayOfFiles(ctx context.Context, petId int64, additionalMetadata string, files []*os.File) (ImplResponse, error) { + // TODO - update UploadFileArrayOfFiles with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("GetPetsUsingBooleanQueryParameters method not implemented") -} - -// SearchPet - Search Pets by filters -func (s *PetAPIService) SearchPet(ctx context.Context, age *int64, price *float32, bornAfter *time.Time, old *bool) (ImplResponse, error) { - // TODO - update SearchPet with the required logic for this service method. - // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... - // return Response(200, []Pet{}), nil - - return Response(http.StatusNotImplemented, nil), errors.New("SearchPet method not implemented") -} - -// UpdatePet - Update an existing pet -func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { - // TODO - update UpdatePet with the required logic for this service method. - // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(200, Pet{}) or use other options such as http.Ok ... - // return Response(200, Pet{}), nil - - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil - - // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... - // return Response(405, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("UpdatePet method not implemented") -} - -// UpdatePetWithForm - Updates a pet in the store with form data -func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name string, status string) (ImplResponse, error) { - // TODO - update UpdatePetWithForm with the required logic for this service method. - // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(405, {}) or use other options such as http.Ok ... - // return Response(405, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("UpdatePetWithForm method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UploadFileArrayOfFiles method not implemented") } -// UploadFile - uploads an image -func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, extraOptionalMetadata []string, file *os.File) (ImplResponse, error) { - // TODO - update UploadFile with the required logic for this service method. +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (s *PetAPIService) GetPetsUsingBooleanQueryParameters(ctx context.Context, expr bool, grouping bool, inactive bool) (ImplResponse, error) { + // TODO - update GetPetsUsingBooleanQueryParameters with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("UploadFile method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsUsingBooleanQueryParameters method not implemented") } -// UploadFileArrayOfFiles - uploads images (array of files) -func (s *PetAPIService) UploadFileArrayOfFiles(ctx context.Context, petId int64, additionalMetadata string, files []*os.File) (ImplResponse, error) { - // TODO - update UploadFileArrayOfFiles with the required logic for this service method. +// GetPetsByTime - Get the pets by time +func (s *PetAPIService) GetPetsByTime(ctx context.Context, createdTime time.Time) (ImplResponse, error) { + // TODO - update GetPetsByTime with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... // return Response(200, ApiResponse{}), nil - return Response(http.StatusNotImplemented, nil), errors.New("UploadFileArrayOfFiles method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsByTime method not implemented") } diff --git a/samples/server/petstore/go-chi-server/go/api_store.go b/samples/server/petstore/go-chi-server/go/api_store.go index e364efe39889..be4a6289e97a 100644 --- a/samples/server/petstore/go-chi-server/go/api_store.go +++ b/samples/server/petstore/go-chi-server/go/api_store.go @@ -51,37 +51,32 @@ func NewStoreAPIController(s StoreAPIServicer, opts ...StoreAPIOption) *StoreAPI // Routes returns all the api routes for the StoreAPIController func (c *StoreAPIController) Routes() Routes { return Routes{ - "DeleteOrder": Route{ - strings.ToUpper("Delete"), - "/v2/store/order/{orderId}", - c.DeleteOrder, - }, "GetInventory": Route{ strings.ToUpper("Get"), "/v2/store/inventory", c.GetInventory, }, + "PlaceOrder": Route{ + strings.ToUpper("Post"), + "/v2/store/order", + c.PlaceOrder, + }, "GetOrderById": Route{ strings.ToUpper("Get"), "/v2/store/order/{orderId}", c.GetOrderById, }, - "PlaceOrder": Route{ - strings.ToUpper("Post"), - "/v2/store/order", - c.PlaceOrder, + "DeleteOrder": Route{ + strings.ToUpper("Delete"), + "/v2/store/order/{orderId}", + c.DeleteOrder, }, } } -// DeleteOrder - Delete purchase order by ID -func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { - orderIdParam := chi.URLParam(r, "orderId") - if orderIdParam == "" { - c.errorHandler(w, r, &RequiredError{"orderId"}, nil) - return - } - result, err := c.service.DeleteOrder(r.Context(), orderIdParam) +// GetInventory - Returns pet inventories by status +func (c *StoreAPIController) GetInventory(w http.ResponseWriter, r *http.Request) { + result, err := c.service.GetInventory(r.Context()) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -91,9 +86,24 @@ func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// GetInventory - Returns pet inventories by status -func (c *StoreAPIController) GetInventory(w http.ResponseWriter, r *http.Request) { - result, err := c.service.GetInventory(r.Context()) +// PlaceOrder - Place an order for a pet +func (c *StoreAPIController) PlaceOrder(w http.ResponseWriter, r *http.Request) { + orderParam := Order{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&orderParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + if err := AssertOrderRequired(orderParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + if err := AssertOrderConstraints(orderParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.PlaceOrder(r.Context(), orderParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -125,24 +135,14 @@ func (c *StoreAPIController) GetOrderById(w http.ResponseWriter, r *http.Request _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// PlaceOrder - Place an order for a pet -func (c *StoreAPIController) PlaceOrder(w http.ResponseWriter, r *http.Request) { - orderParam := Order{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&orderParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertOrderRequired(orderParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - if err := AssertOrderConstraints(orderParam); err != nil { - c.errorHandler(w, r, err, nil) +// DeleteOrder - Delete purchase order by ID +func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { + orderIdParam := chi.URLParam(r, "orderId") + if orderIdParam == "" { + c.errorHandler(w, r, &RequiredError{"orderId"}, nil) return } - result, err := c.service.PlaceOrder(r.Context(), orderParam) + result, err := c.service.DeleteOrder(r.Context(), orderIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/samples/server/petstore/go-chi-server/go/api_store_service.go b/samples/server/petstore/go-chi-server/go/api_store_service.go index 46671f7a9fd9..b42eb74efb91 100644 --- a/samples/server/petstore/go-chi-server/go/api_store_service.go +++ b/samples/server/petstore/go-chi-server/go/api_store_service.go @@ -27,20 +27,6 @@ func NewStoreAPIService() *StoreAPIService { return &StoreAPIService{} } -// DeleteOrder - Delete purchase order by ID -func (s *StoreAPIService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) { - // TODO - update DeleteOrder with the required logic for this service method. - // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - // return Response(400, nil),nil - - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("DeleteOrder method not implemented") -} - // GetInventory - Returns pet inventories by status func (s *StoreAPIService) GetInventory(ctx context.Context) (ImplResponse, error) { // TODO - update GetInventory with the required logic for this service method. @@ -52,6 +38,20 @@ func (s *StoreAPIService) GetInventory(ctx context.Context) (ImplResponse, error return Response(http.StatusNotImplemented, nil), errors.New("GetInventory method not implemented") } +// PlaceOrder - Place an order for a pet +func (s *StoreAPIService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) { + // TODO - update PlaceOrder with the required logic for this service method. + // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ... + // return Response(200, Order{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("PlaceOrder method not implemented") +} + // GetOrderById - Find purchase order by ID func (s *StoreAPIService) GetOrderById(ctx context.Context, orderId int64) (ImplResponse, error) { // TODO - update GetOrderById with the required logic for this service method. @@ -69,16 +69,16 @@ func (s *StoreAPIService) GetOrderById(ctx context.Context, orderId int64) (Impl return Response(http.StatusNotImplemented, nil), errors.New("GetOrderById method not implemented") } -// PlaceOrder - Place an order for a pet -func (s *StoreAPIService) PlaceOrder(ctx context.Context, order Order) (ImplResponse, error) { - // TODO - update PlaceOrder with the required logic for this service method. +// DeleteOrder - Delete purchase order by ID +func (s *StoreAPIService) DeleteOrder(ctx context.Context, orderId string) (ImplResponse, error) { + // TODO - update DeleteOrder with the required logic for this service method. // Add api_store_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(200, Order{}) or use other options such as http.Ok ... - // return Response(200, Order{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("PlaceOrder method not implemented") + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeleteOrder method not implemented") } diff --git a/samples/server/petstore/go-chi-server/go/api_user.go b/samples/server/petstore/go-chi-server/go/api_user.go index 9fd0c1c5fc75..c1ff526edc79 100644 --- a/samples/server/petstore/go-chi-server/go/api_user.go +++ b/samples/server/petstore/go-chi-server/go/api_user.go @@ -66,16 +66,6 @@ func (c *UserAPIController) Routes() Routes { "/v2/user/createWithList", c.CreateUsersWithListInput, }, - "DeleteUser": Route{ - strings.ToUpper("Delete"), - "/v2/user/{username}", - c.DeleteUser, - }, - "GetUserByName": Route{ - strings.ToUpper("Get"), - "/v2/user/{username}", - c.GetUserByName, - }, "LoginUser": Route{ strings.ToUpper("Get"), "/v2/user/login", @@ -86,11 +76,21 @@ func (c *UserAPIController) Routes() Routes { "/v2/user/logout", c.LogoutUser, }, + "GetUserByName": Route{ + strings.ToUpper("Get"), + "/v2/user/{username}", + c.GetUserByName, + }, "UpdateUser": Route{ strings.ToUpper("Put"), "/v2/user/{username}", c.UpdateUser, }, + "DeleteUser": Route{ + strings.ToUpper("Delete"), + "/v2/user/{username}", + c.DeleteUser, + }, } } @@ -171,59 +171,6 @@ func (c *UserAPIController) CreateUsersWithListInput(w http.ResponseWriter, r *h _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } -// DeleteUser - Delete user -func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { - query, err := parseQuery(r.URL.RawQuery) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - usernameParam := chi.URLParam(r, "username") - if usernameParam == "" { - c.errorHandler(w, r, &RequiredError{"username"}, nil) - return - } - var confirmationParam bool - if query.Has("confirmation") { - param, err := parseBoolParameter( - query.Get("confirmation"), - WithParse[bool](parseBool), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Param: "confirmation", Err: err}, nil) - return - } - - confirmationParam = param - } else { - } - result, err := c.service.DeleteUser(r.Context(), usernameParam, confirmationParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - -// GetUserByName - Get user by user name -func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { - usernameParam := chi.URLParam(r, "username") - if usernameParam == "" { - c.errorHandler(w, r, &RequiredError{"username"}, nil) - return - } - result, err := c.service.GetUserByName(r.Context(), usernameParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) -} - // LoginUser - Logs user into the system func (c *UserAPIController) LoginUser(w http.ResponseWriter, r *http.Request) { query, err := parseQuery(r.URL.RawQuery) @@ -285,6 +232,23 @@ func (c *UserAPIController) LogoutUser(w http.ResponseWriter, r *http.Request) { _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// GetUserByName - Get user by user name +func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { + usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } + result, err := c.service.GetUserByName(r.Context(), usernameParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // UpdateUser - Updated user func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { usernameParam := chi.URLParam(r, "username") @@ -316,3 +280,39 @@ func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { // If no error, encode the body and the result code _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } + +// DeleteUser - Delete user +func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { + query, err := parseQuery(r.URL.RawQuery) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } + var confirmationParam bool + if query.Has("confirmation") { + param, err := parseBoolParameter( + query.Get("confirmation"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Param: "confirmation", Err: err}, nil) + return + } + + confirmationParam = param + } else { + } + result, err := c.service.DeleteUser(r.Context(), usernameParam, confirmationParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + _ = EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} diff --git a/samples/server/petstore/go-chi-server/go/api_user_service.go b/samples/server/petstore/go-chi-server/go/api_user_service.go index 62332a09da48..f117afb35ef9 100644 --- a/samples/server/petstore/go-chi-server/go/api_user_service.go +++ b/samples/server/petstore/go-chi-server/go/api_user_service.go @@ -60,18 +60,29 @@ func (s *UserAPIService) CreateUsersWithListInput(ctx context.Context, user []Us return Response(http.StatusNotImplemented, nil), errors.New("CreateUsersWithListInput method not implemented") } -// DeleteUser - Delete user -func (s *UserAPIService) DeleteUser(ctx context.Context, username string, confirmation bool) (ImplResponse, error) { - // TODO - update DeleteUser with the required logic for this service method. +// LoginUser - Logs user into the system +func (s *UserAPIService) LoginUser(ctx context.Context, username string, password string, rememberMe bool) (ImplResponse, error) { + // TODO - update LoginUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + // TODO: Uncomment the next line to return response Response(200, string{}) or use other options such as http.Ok ... + // return Response(200, string{}), nil + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - // return Response(404, nil),nil + return Response(http.StatusNotImplemented, nil), errors.New("LoginUser method not implemented") +} - return Response(http.StatusNotImplemented, nil), errors.New("DeleteUser method not implemented") +// LogoutUser - Logs out current logged in user session +func (s *UserAPIService) LogoutUser(ctx context.Context) (ImplResponse, error) { + // TODO - update LogoutUser with the required logic for this service method. + // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ... + // return Response(0, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented") } // GetUserByName - Get user by user name @@ -91,34 +102,23 @@ func (s *UserAPIService) GetUserByName(ctx context.Context, username string) (Im return Response(http.StatusNotImplemented, nil), errors.New("GetUserByName method not implemented") } -// LoginUser - Logs user into the system -func (s *UserAPIService) LoginUser(ctx context.Context, username string, password string, rememberMe bool) (ImplResponse, error) { - // TODO - update LoginUser with the required logic for this service method. +// UpdateUser - Updated user +func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) { + // TODO - update UpdateUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - // TODO: Uncomment the next line to return response Response(200, string{}) or use other options such as http.Ok ... - // return Response(200, string{}), nil - // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... // return Response(400, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("LoginUser method not implemented") -} - -// LogoutUser - Logs out current logged in user session -func (s *UserAPIService) LogoutUser(ctx context.Context) (ImplResponse, error) { - // TODO - update LogoutUser with the required logic for this service method. - // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - // TODO: Uncomment the next line to return response Response(0, {}) or use other options such as http.Ok ... - // return Response(0, nil),nil + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("LogoutUser method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UpdateUser method not implemented") } -// UpdateUser - Updated user -func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user User) (ImplResponse, error) { - // TODO - update UpdateUser with the required logic for this service method. +// DeleteUser - Delete user +func (s *UserAPIService) DeleteUser(ctx context.Context, username string, confirmation bool) (ImplResponse, error) { + // TODO - update DeleteUser with the required logic for this service method. // Add api_user_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... @@ -127,5 +127,5 @@ func (s *UserAPIService) UpdateUser(ctx context.Context, username string, user U // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... // return Response(404, nil),nil - return Response(http.StatusNotImplemented, nil), errors.New("UpdateUser method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("DeleteUser method not implemented") } diff --git a/samples/server/petstore/kotlin-spring-default/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-spring-default/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-spring-default/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-spring-default/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-3/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-3/src/main/kotlin/org/openapitools/api/Exceptions.kt index 117161bf65b1..1bd78f54576a 100644 --- a/samples/server/petstore/kotlin-springboot-3/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-3/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-bigdecimal-default/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-bigdecimal-default/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot-bigdecimal-default/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-bigdecimal-default/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-delegate-nodefaults/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-delegate-nodefaults/src/main/kotlin/org/openapitools/api/Exceptions.kt index 117161bf65b1..1bd78f54576a 100644 --- a/samples/server/petstore/kotlin-springboot-delegate-nodefaults/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-delegate-nodefaults/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-integer-enum/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-integer-enum/src/main/kotlin/org/openapitools/api/Exceptions.kt index 117161bf65b1..1bd78f54576a 100644 --- a/samples/server/petstore/kotlin-springboot-integer-enum/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-integer-enum/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-modelMutable/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-modelMutable/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot-modelMutable/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-modelMutable/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-multipart-request-model/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-multipart-request-model/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot-multipart-request-model/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-multipart-request-model/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-request-cookie/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-request-cookie/src/main/kotlin/org/openapitools/api/Exceptions.kt index 117161bf65b1..1bd78f54576a 100644 --- a/samples/server/petstore/kotlin-springboot-request-cookie/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-request-cookie/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-source-swagger1/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-source-swagger1/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot-source-swagger1/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-source-swagger1/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-source-swagger2/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-source-swagger2/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot-source-swagger2/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-source-swagger2/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot-springfox/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-springfox/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot-springfox/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot-springfox/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt index 44190af7a019..901db1237ee7 100644 --- a/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt +++ b/samples/server/petstore/kotlin-springboot/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -1,5 +1,6 @@ package org.openapitools.api +import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @@ -11,7 +12,7 @@ sealed class ApiException(msg: String, val code: Int) : Exception(msg) class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) - +@Configuration("org.openapitools.api.DefaultExceptionHandler") @ControllerAdvice class DefaultExceptionHandler { diff --git a/samples/server/petstore/springboot-file-delegate-optional/pom.xml b/samples/server/petstore/springboot-file-delegate-optional/pom.xml index 3afd4785fae9..9ac3410785c2 100644 --- a/samples/server/petstore/springboot-file-delegate-optional/pom.xml +++ b/samples/server/petstore/springboot-file-delegate-optional/pom.xml @@ -10,8 +10,8 @@ ${java.version} ${java.version} UTF-8 - 2.2.0 - 5.3.1 + 2.6.0 + 5.17.14 org.springframework.boot diff --git a/samples/server/petstore/springboot-lombok-tostring/pom.xml b/samples/server/petstore/springboot-lombok-tostring/pom.xml index 9d17fff871da..0b079a60154c 100644 --- a/samples/server/petstore/springboot-lombok-tostring/pom.xml +++ b/samples/server/petstore/springboot-lombok-tostring/pom.xml @@ -10,8 +10,8 @@ ${java.version} ${java.version} UTF-8 - 2.2.0 - 5.3.1 + 2.6.0 + 5.17.14 org.springframework.boot diff --git a/website/src/dynamic/sponsors.yml b/website/src/dynamic/sponsors.yml index 40d639888e5b..be9b99fee4a7 100755 --- a/website/src/dynamic/sponsors.yml +++ b/website/src/dynamic/sponsors.yml @@ -133,3 +133,8 @@ image: "img/companies/route4me.png" infoLink: "https://route4me.com/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship" bronze: true +- + caption: "Dotcom-Monitor" + image: "img/companies/dm.png" + infoLink: "https://www.dotcom-monitor.com/sponsoring-open-source-projects/?utm_source=openapi-generator&utm_medium=sponsorship&utm_campaign=oss-sponsorship" + bronze: true diff --git a/website/static/img/companies/dm.png b/website/static/img/companies/dm.png new file mode 100644 index 000000000000..8d5558a18cd1 Binary files /dev/null and b/website/static/img/companies/dm.png differ