From e49804fd7f0f2fc386a9771354a3f528151f3d7a Mon Sep 17 00:00:00 2001 From: Yuriy Belenko Date: Sun, 21 Jun 2020 17:16:44 +0300 Subject: [PATCH] [php-slim4] Move Data Mocker to external repo (#5930) * Remove package from sources * Add Mocker package * Add BaseModel Beside setters and getters this class implements three methods required for mocking: getOpenApiSchema, createFromData and jsonSerialize. BaseModel keeps all data values in $dataContainer like PHP client does. I don't see other way to support scalar models(enum for instance). That's why I've removed class variables generation. * Update documentation * Update PHPUnit section in readme * Add constant with models namespace This constant will be required for data deserialization when handling refs. * Refresh samples * Add samples generation config --- bin/configs/php-slim4.yaml | 4 + .../languages/PhpSlim4ServerCodegen.java | 42 +- .../php-slim4-server/README.mustache | 16 +- .../php-slim4-server/SlimRouter.mustache | 39 +- .../php-slim4-server/base_model.mustache | 319 +++++ .../php-slim4-server/base_model_test.mustache | 586 ++++++++ .../php-slim4-server/composer.mustache | 2 + .../resources/php-slim4-server/index.mustache | 25 +- .../php-slim4-server/mock_server.mustache | 135 -- .../resources/php-slim4-server/model.mustache | 31 +- .../php-slim4-server/model_interface.mustache | 30 - .../php-slim4-server/model_test.mustache | 10 +- .../model_utils_trait.mustache | 108 -- .../model_utils_trait_test.mustache | 87 -- .../openapi_data_mocker.mustache | 609 -------- .../openapi_data_mocker_interface.mustache | 239 ---- .../openapi_data_mocker_middleware.mustache | 171 --- ...enapi_data_mocker_middleware_test.mustache | 258 ---- .../openapi_data_mocker_test.mustache | 1233 ---------------- .../php-slim4-server/phpunit.xml.mustache | 2 + .../string_utils_trait.mustache | 117 -- .../string_utils_trait_test.mustache | 84 -- .../php-slim4/.openapi-generator/FILES | 74 +- samples/server/petstore/php-slim4/README.md | 89 +- .../server/petstore/php-slim4/composer.json | 2 + .../petstore/php-slim4/docs/MockServer.md | 135 -- samples/server/petstore/php-slim4/index.php | 25 +- .../lib/Api/AbstractAnotherFakeApi.php | 75 - .../php-slim4/lib/Api/AbstractFakeApi.php | 356 ----- .../Api/AbstractFakeClassnameTags123Api.php | 75 - .../php-slim4/lib/Api/AbstractPetApi.php | 26 +- .../php-slim4/lib/Api/AbstractStoreApi.php | 6 +- .../php-slim4/lib/Api/AbstractUserApi.php | 2 +- .../lib/Auth/AbstractAuthenticator.php | 2 +- .../petstore/php-slim4/lib/BaseModel.php | 332 +++++ .../lib/Interfaces/ModelInterface.php | 42 - .../Middleware/JsonBodyParserMiddleware.php | 2 +- .../php-slim4/lib/Mock/OpenApiDataMocker.php | 621 -------- .../lib/Mock/OpenApiDataMockerInterface.php | 251 ---- .../lib/Mock/OpenApiDataMockerMiddleware.php | 183 --- .../lib/Model/AdditionalPropertiesAnyType.php | 64 - .../lib/Model/AdditionalPropertiesArray.php | 67 - .../lib/Model/AdditionalPropertiesBoolean.php | 63 - .../lib/Model/AdditionalPropertiesClass.php | 160 --- .../lib/Model/AdditionalPropertiesInteger.php | 63 - .../lib/Model/AdditionalPropertiesNumber.php | 63 - .../lib/Model/AdditionalPropertiesObject.php | 67 - .../lib/Model/AdditionalPropertiesString.php | 63 - .../petstore/php-slim4/lib/Model/Animal.php | 71 - .../php-slim4/lib/Model/ApiResponse.php | 43 +- .../lib/Model/ArrayOfArrayOfNumberOnly.php | 66 - .../php-slim4/lib/Model/ArrayOfNumberOnly.php | 63 - .../php-slim4/lib/Model/ArrayTest.php | 88 -- .../petstore/php-slim4/lib/Model/BigCat.php | 68 - .../php-slim4/lib/Model/BigCatAllOf.php | 60 - .../php-slim4/lib/Model/Capitalization.php | 91 -- .../petstore/php-slim4/lib/Model/Cat.php | 65 - .../petstore/php-slim4/lib/Model/CatAllOf.php | 59 - .../petstore/php-slim4/lib/Model/Category.php | 43 +- .../php-slim4/lib/Model/ClassModel.php | 61 - .../petstore/php-slim4/lib/Model/Client.php | 60 - .../petstore/php-slim4/lib/Model/Dog.php | 65 - .../petstore/php-slim4/lib/Model/DogAllOf.php | 59 - .../php-slim4/lib/Model/EnumArrays.php | 71 - .../php-slim4/lib/Model/EnumClass.php | 54 - .../petstore/php-slim4/lib/Model/EnumTest.php | 91 -- .../petstore/php-slim4/lib/Model/File.php | 62 - .../lib/Model/FileSchemaTestClass.php | 69 - .../php-slim4/lib/Model/FormatTest.php | 165 --- .../php-slim4/lib/Model/HasOnlyReadOnly.php | 68 - .../php-slim4/lib/Model/InlineObject.php | 60 + .../php-slim4/lib/Model/InlineObject1.php | 61 + .../petstore/php-slim4/lib/Model/MapTest.php | 91 -- ...PropertiesAndAdditionalPropertiesClass.php | 77 - .../php-slim4/lib/Model/Model200Response.php | 71 - .../php-slim4/lib/Model/ModelList.php | 60 - .../php-slim4/lib/Model/ModelReturn.php | 65 - .../petstore/php-slim4/lib/Model/Name.php | 87 -- .../php-slim4/lib/Model/NumberOnly.php | 60 - .../petstore/php-slim4/lib/Model/Order.php | 50 +- .../php-slim4/lib/Model/OuterComposite.php | 72 - .../php-slim4/lib/Model/OuterEnum.php | 53 - .../petstore/php-slim4/lib/Model/Pet.php | 54 +- .../php-slim4/lib/Model/ReadOnlyFirst.php | 67 - .../php-slim4/lib/Model/SpecialModelName.php | 64 - .../petstore/php-slim4/lib/Model/Tag.php | 38 +- .../php-slim4/lib/Model/TypeHolderDefault.php | 90 -- .../php-slim4/lib/Model/TypeHolderExample.php | 101 -- .../petstore/php-slim4/lib/Model/User.php | 59 +- .../petstore/php-slim4/lib/Model/XmlItem.php | 389 ----- .../petstore/php-slim4/lib/SlimRouter.php | 749 ++-------- .../php-slim4/lib/Utils/ModelUtilsTrait.php | 120 -- .../php-slim4/lib/Utils/StringUtilsTrait.php | 129 -- .../petstore/php-slim4/phpunit.xml.dist | 2 + .../php-slim4/test/Api/AnotherFakeApiTest.php | 81 -- .../php-slim4/test/Api/FakeApiTest.php | 263 ---- .../test/Api/FakeClassnameTags123ApiTest.php | 81 -- .../php-slim4/test/Api/PetApiTest.php | 16 +- .../php-slim4/test/Api/StoreApiTest.php | 2 +- .../php-slim4/test/Api/UserApiTest.php | 2 +- .../petstore/php-slim4/test/BaseModelTest.php | 599 ++++++++ .../Mock/OpenApiDataMockerMiddlewareTest.php | 270 ---- .../test/Mock/OpenApiDataMockerTest.php | 1245 ----------------- .../Model/AdditionalPropertiesAnyTypeTest.php | 100 -- .../Model/AdditionalPropertiesArrayTest.php | 100 -- .../Model/AdditionalPropertiesBooleanTest.php | 100 -- .../Model/AdditionalPropertiesClassTest.php | 200 --- .../Model/AdditionalPropertiesIntegerTest.php | 100 -- .../Model/AdditionalPropertiesNumberTest.php | 100 -- .../Model/AdditionalPropertiesObjectTest.php | 100 -- .../Model/AdditionalPropertiesStringTest.php | 100 -- .../php-slim4/test/Model/AnimalTest.php | 110 -- .../php-slim4/test/Model/ApiResponseTest.php | 12 +- .../Model/ArrayOfArrayOfNumberOnlyTest.php | 100 -- .../test/Model/ArrayOfNumberOnlyTest.php | 100 -- .../php-slim4/test/Model/ArrayTestTest.php | 120 -- .../php-slim4/test/Model/BigCatAllOfTest.php | 100 -- .../php-slim4/test/Model/BigCatTest.php | 130 -- .../test/Model/CapitalizationTest.php | 150 -- .../php-slim4/test/Model/CatAllOfTest.php | 100 -- .../petstore/php-slim4/test/Model/CatTest.php | 120 -- .../php-slim4/test/Model/CategoryTest.php | 12 +- .../php-slim4/test/Model/ClassModelTest.php | 100 -- .../php-slim4/test/Model/ClientTest.php | 100 -- .../php-slim4/test/Model/DogAllOfTest.php | 100 -- .../petstore/php-slim4/test/Model/DogTest.php | 120 -- .../php-slim4/test/Model/EnumArraysTest.php | 110 -- .../php-slim4/test/Model/EnumClassTest.php | 90 -- .../php-slim4/test/Model/EnumTestTest.php | 140 -- .../php-slim4/test/Model/FileTest.php | 100 -- .../php-slim4/test/Model/FormatTestTest.php | 230 --- .../test/Model/HasOnlyReadOnlyTest.php | 110 -- ...estClassTest.php => InlineObject1Test.php} | 50 +- ...0ResponseTest.php => InlineObjectTest.php} | 36 +- .../php-slim4/test/Model/MapTestTest.php | 130 -- ...ertiesAndAdditionalPropertiesClassTest.php | 120 -- .../php-slim4/test/Model/ModelListTest.php | 100 -- .../php-slim4/test/Model/ModelReturnTest.php | 100 -- .../php-slim4/test/Model/NameTest.php | 130 -- .../php-slim4/test/Model/NumberOnlyTest.php | 100 -- .../php-slim4/test/Model/OrderTest.php | 12 +- .../test/Model/OuterCompositeTest.php | 120 -- .../php-slim4/test/Model/OuterEnumTest.php | 90 -- .../petstore/php-slim4/test/Model/PetTest.php | 12 +- .../test/Model/ReadOnlyFirstTest.php | 110 -- .../test/Model/SpecialModelNameTest.php | 100 -- .../petstore/php-slim4/test/Model/TagTest.php | 12 +- .../test/Model/TypeHolderDefaultTest.php | 140 -- .../test/Model/TypeHolderExampleTest.php | 150 -- .../php-slim4/test/Model/UserTest.php | 12 +- .../php-slim4/test/Model/XmlItemTest.php | 380 ----- .../test/Utils/ModelUtilsTraitTest.php | 99 -- .../test/Utils/StringUtilsTraitTest.php | 96 -- 153 files changed, 2454 insertions(+), 16624 deletions(-) create mode 100644 bin/configs/php-slim4.yaml create mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/base_model.mustache create mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/base_model_test.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/mock_server.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/model_interface.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait_test.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_interface.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware_test.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_test.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait_test.mustache delete mode 100644 samples/server/petstore/php-slim4/docs/MockServer.md delete mode 100644 samples/server/petstore/php-slim4/lib/Api/AbstractAnotherFakeApi.php delete mode 100644 samples/server/petstore/php-slim4/lib/Api/AbstractFakeApi.php delete mode 100644 samples/server/petstore/php-slim4/lib/Api/AbstractFakeClassnameTags123Api.php create mode 100644 samples/server/petstore/php-slim4/lib/BaseModel.php delete mode 100644 samples/server/petstore/php-slim4/lib/Interfaces/ModelInterface.php delete mode 100644 samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMocker.php delete mode 100644 samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerInterface.php delete mode 100644 samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerMiddleware.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesAnyType.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesArray.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesBoolean.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesClass.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesInteger.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesNumber.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesObject.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesString.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/Animal.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/ArrayOfArrayOfNumberOnly.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/ArrayOfNumberOnly.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/ArrayTest.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/BigCat.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/BigCatAllOf.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/Capitalization.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/Cat.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/CatAllOf.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/ClassModel.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/Client.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/Dog.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/DogAllOf.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/EnumArrays.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/EnumClass.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/EnumTest.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/File.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/FileSchemaTestClass.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/FormatTest.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/HasOnlyReadOnly.php create mode 100644 samples/server/petstore/php-slim4/lib/Model/InlineObject.php create mode 100644 samples/server/petstore/php-slim4/lib/Model/InlineObject1.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/MapTest.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/Model200Response.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/ModelList.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/ModelReturn.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/Name.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/NumberOnly.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/OuterComposite.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/OuterEnum.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/ReadOnlyFirst.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/SpecialModelName.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/TypeHolderDefault.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/TypeHolderExample.php delete mode 100644 samples/server/petstore/php-slim4/lib/Model/XmlItem.php delete mode 100644 samples/server/petstore/php-slim4/lib/Utils/ModelUtilsTrait.php delete mode 100644 samples/server/petstore/php-slim4/lib/Utils/StringUtilsTrait.php delete mode 100644 samples/server/petstore/php-slim4/test/Api/AnotherFakeApiTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Api/FakeApiTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Api/FakeClassnameTags123ApiTest.php create mode 100644 samples/server/petstore/php-slim4/test/BaseModelTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerMiddlewareTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesAnyTypeTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesArrayTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesBooleanTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesClassTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesIntegerTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesNumberTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesObjectTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesStringTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/AnimalTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ArrayOfArrayOfNumberOnlyTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ArrayOfNumberOnlyTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ArrayTestTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/BigCatAllOfTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/BigCatTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/CapitalizationTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/CatAllOfTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/CatTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ClassModelTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ClientTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/DogAllOfTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/DogTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/EnumArraysTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/EnumClassTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/EnumTestTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/FileTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/FormatTestTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/HasOnlyReadOnlyTest.php rename samples/server/petstore/php-slim4/test/Model/{FileSchemaTestClassTest.php => InlineObject1Test.php} (58%) rename samples/server/petstore/php-slim4/test/Model/{Model200ResponseTest.php => InlineObjectTest.php} (59%) delete mode 100644 samples/server/petstore/php-slim4/test/Model/MapTestTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ModelListTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ModelReturnTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/NameTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/NumberOnlyTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/OuterCompositeTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/OuterEnumTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/ReadOnlyFirstTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/SpecialModelNameTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/TypeHolderDefaultTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/TypeHolderExampleTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Model/XmlItemTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Utils/ModelUtilsTraitTest.php delete mode 100644 samples/server/petstore/php-slim4/test/Utils/StringUtilsTraitTest.php diff --git a/bin/configs/php-slim4.yaml b/bin/configs/php-slim4.yaml new file mode 100644 index 00000000000..a15c313a772 --- /dev/null +++ b/bin/configs/php-slim4.yaml @@ -0,0 +1,4 @@ +generatorName: php-slim4 +outputDir: samples/server/petstore/php-slim4 +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/php-slim4-server diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java index 1a8f20529fa..aed75feb5e0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java @@ -32,10 +32,6 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { public static final String PSR7_IMPLEMENTATION = "psr7Implementation"; protected String psr7Implementation = "slim-psr7"; - protected String mockDirName = "Mock"; - protected String mockPackage = ""; - protected String utilsDirName = "Utils"; - protected String utilsPackage = ""; protected String interfacesDirName = "Interfaces"; protected String interfacesPackage = ""; @@ -46,8 +42,6 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { .stability(Stability.STABLE) .build(); - mockPackage = invokerPackage + "\\" + mockDirName; - utilsPackage = invokerPackage + "\\" + utilsDirName; interfacesPackage = invokerPackage + "\\" + interfacesDirName; outputFolder = "generated-code" + File.separator + "slim4"; embeddedTemplateDir = templateDir = "php-slim4-server"; @@ -84,30 +78,15 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { super.processOpts(); if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - // Update mockPackage and utilsPackage - mockPackage = invokerPackage + "\\" + mockDirName; - utilsPackage = invokerPackage + "\\" + utilsDirName; + // Update interfacesPackage interfacesPackage = invokerPackage + "\\" + interfacesDirName; } - // make mock src path available in mustache template - additionalProperties.put("mockPackage", mockPackage); - additionalProperties.put("mockSrcPath", "./" + toSrcPath(mockPackage, srcBasePath)); - additionalProperties.put("mockTestPath", "./" + toSrcPath(mockPackage, testBasePath)); - - // same for utils package - additionalProperties.put("utilsPackage", utilsPackage); - additionalProperties.put("utilsSrcPath", "./" + toSrcPath(utilsPackage, srcBasePath)); - additionalProperties.put("utilsTestPath", "./" + toSrcPath(utilsPackage, testBasePath)); - // same for interfaces package additionalProperties.put("interfacesPackage", interfacesPackage); additionalProperties.put("interfacesSrcPath", "./" + toSrcPath(interfacesPackage, srcBasePath)); additionalProperties.put("interfacesTestPath", "./" + toSrcPath(interfacesPackage, testBasePath)); - // external docs folder - additionalProperties.put("docsBasePath", "./" + docsBasePath); - if (additionalProperties.containsKey(PSR7_IMPLEMENTATION)) { this.setPsr7Implementation((String) additionalProperties.get(PSR7_IMPLEMENTATION)); } @@ -140,23 +119,8 @@ public class PhpSlim4ServerCodegen extends PhpSlimServerCodegen { // Slim 4 doesn't parse JSON body anymore we need to add suggested middleware // ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body supportingFiles.add(new SupportingFile("json_body_parser_middleware.mustache", toSrcPath(invokerPackage + "\\Middleware", srcBasePath), "JsonBodyParserMiddleware.php")); - - // mocking feature - supportingFiles.add(new SupportingFile("openapi_data_mocker_interface.mustache", toSrcPath(mockPackage, srcBasePath), toInterfaceName("OpenApiDataMocker") + ".php")); - supportingFiles.add(new SupportingFile("openapi_data_mocker.mustache", toSrcPath(mockPackage, srcBasePath), "OpenApiDataMocker.php")); - supportingFiles.add(new SupportingFile("openapi_data_mocker_test.mustache", toSrcPath(mockPackage, testBasePath), "OpenApiDataMockerTest.php")); - supportingFiles.add(new SupportingFile("openapi_data_mocker_middleware.mustache", toSrcPath(mockPackage, srcBasePath), "OpenApiDataMockerMiddleware.php")); - supportingFiles.add(new SupportingFile("openapi_data_mocker_middleware_test.mustache", toSrcPath(mockPackage, testBasePath), "OpenApiDataMockerMiddlewareTest.php")); - supportingFiles.add(new SupportingFile("mock_server.mustache", docsBasePath, "MockServer.md")); - - // traits of ported utils - supportingFiles.add(new SupportingFile("string_utils_trait.mustache", toSrcPath(utilsPackage, srcBasePath), toTraitName("StringUtils") + ".php")); - supportingFiles.add(new SupportingFile("string_utils_trait_test.mustache", toSrcPath(utilsPackage, testBasePath), toTraitName("StringUtils") + "Test.php")); - supportingFiles.add(new SupportingFile("model_utils_trait.mustache", toSrcPath(utilsPackage, srcBasePath), toTraitName("ModelUtils") + ".php")); - supportingFiles.add(new SupportingFile("model_utils_trait_test.mustache", toSrcPath(utilsPackage, testBasePath), toTraitName("ModelUtils") + "Test.php")); - - // model interface - supportingFiles.add(new SupportingFile("model_interface.mustache", toSrcPath(interfacesPackage, srcBasePath), toInterfaceName("Model") + ".php")); + supportingFiles.add(new SupportingFile("base_model.mustache", toSrcPath(invokerPackage, srcBasePath), "BaseModel.php")); + supportingFiles.add(new SupportingFile("base_model_test.mustache", toSrcPath(invokerPackage, testBasePath), "BaseModelTest.php")); } /** diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache index d96d2c46cb4..6746071f556 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache @@ -46,9 +46,9 @@ $ php -S localhost:8888 -t php-slim-server ### PHPUnit -This package uses PHPUnit 6 or 7(depends from your PHP version) for unit testing. +This package uses PHPUnit 8 or 9(depends from your PHP version) for unit testing. [Test folder]({{testBasePath}}) contains templates which you can fill with real test assertions. -How to write tests read at [PHPUnit Manual - Chapter 2. Writing Tests for PHPUnit](https://phpunit.de/manual/6.5/en/writing-tests-for-phpunit.html). +How to write tests read at [2. Writing Tests for PHPUnit - PHPUnit 8.5 Manual](https://phpunit.readthedocs.io/en/8.5/writing-tests-for-phpunit.html). #### Run @@ -57,14 +57,12 @@ Command | Target `$ composer test` | All tests `$ composer test-apis` | Apis tests `$ composer test-models` | Models tests -`$ composer test-mock` | Mock feature tests -`$ composer test-utils` | Utils tests #### Config Package contains fully functional config `./phpunit.xml.dist` file. Create `./phpunit.xml` in root folder to override it. -Quote from [3. The Command-Line Test Runner — PHPUnit 7.4 Manual](https://phpunit.readthedocs.io/en/7.4/textui.html#command-line-options): +Quote from [3. The Command-Line Test Runner — PHPUnit 8.5 Manual](https://phpunit.readthedocs.io/en/8.5/textui.html#command-line-options): > If phpunit.xml or phpunit.xml.dist (in that order) exist in the current working directory and --configuration is not used, the configuration will be automatically read from that file. @@ -112,7 +110,13 @@ Switch on option in `./index.php`: +++ $app->addErrorMiddleware(true, true, true); ``` -## [Mock Server Documentation]({{docsBasePath}}/MockServer.md) +## Mock Server +For a quick start uncomment [mocker middleware config](index.php#L62-L89). + +Used packages: +* [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator. +* [Openapi Data Mocker Server Middleware](https://github.com/ybelenko/openapi-data-mocker-server-middleware) - PSR-15 HTTP server middleware. +* [Openapi Data Mocker Interfaces](https://github.com/ybelenko/openapi-data-mocker-interfaces) - package with mocking interfaces. {{#generateApiDocs}} ## API Endpoints diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/SlimRouter.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/SlimRouter.mustache index 68433fc3402..10b458d4fd0 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/SlimRouter.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/SlimRouter.mustache @@ -18,8 +18,20 @@ use Dyorg\TokenAuthentication; use Dyorg\TokenAuthentication\TokenSearch; use Psr\Http\Message\ServerRequestInterface; use {{invokerPackage}}\Middleware\JsonBodyParserMiddleware; -use {{mockPackage}}\OpenApiDataMocker; -use {{mockPackage}}\OpenApiDataMockerMiddleware; +use OpenAPIServer\Mock\OpenApiDataMocker; +use OpenAPIServer\Mock\OpenApiDataMockerRouteMiddleware; +{{#isSlimPsr7}} +use Slim\Psr7\Factory\ResponseFactory; +{{/isSlimPsr7}} +{{#isNyholmPsr7}} +use Nyholm\Psr7\Factory\Psr17Factory +{{/isNyholmPsr7}} +{{#isGuzzlePsr7}} +use GuzzleHttp\Psr7\HttpFactory; +{{/isGuzzlePsr7}} +{{#isZendDiactoros}} +use Zend\Diactoros\ResponseFactory; +{{/isZendDiactoros}} use Exception; /** @@ -51,8 +63,6 @@ class SlimRouter 'responses' => [ {{#responses}} '{{#isDefault}}default{{/isDefault}}{{^isDefault}}{{code}}{{/isDefault}}' => [ - 'code' => {{code}}, - 'message' => '{{message}}', 'jsonSchema' => '{{{jsonSchema}}}', ], {{/responses}} @@ -155,7 +165,19 @@ class SlimRouter // mocker options $mockerOptions = $this->getSetting($settings, 'mockerOptions', null); $dataMocker = $mockerOptions['dataMocker'] ?? new OpenApiDataMocker(); - $getMockResponseCallback = $mockerOptions['getMockResponseCallback'] ?? null; + {{#isSlimPsr7}} + $responseFactory = new ResponseFactory(); + {{/isSlimPsr7}} + {{#isNyholmPsr7}} + $responseFactory = new Psr17Factory(); + {{/isNyholmPsr7}} + {{#isGuzzlePsr7}} + $responseFactory = new HttpFactory(); + {{/isGuzzlePsr7}} + {{#isZendDiactoros}} + $responseFactory = new ResponseFactory(); + {{/isZendDiactoros}} + $getMockStatusCodeCallback = $mockerOptions['getMockStatusCodeCallback'] ?? null; $mockAfterCallback = $mockerOptions['afterCallback'] ?? null; foreach ($this->operations as $operation) { @@ -223,8 +245,11 @@ class SlimRouter } {{/hasAuthMethods}} - if (is_callable($getMockResponseCallback)) { - $middlewares[] = new OpenApiDataMockerMiddleware($dataMocker, $operation['responses'], $getMockResponseCallback, $mockAfterCallback); + if (is_callable($getMockStatusCodeCallback)) { + $mockSchemaResponses = array_map(function ($item) { + return json_decode($item['jsonSchema'], true); + }, $operation['responses']); + $middlewares[] = new OpenApiDataMockerRouteMiddleware($dataMocker, $mockSchemaResponses, $responseFactory, $getMockStatusCodeCallback, $mockAfterCallback); } $this->addRoute( diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/base_model.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/base_model.mustache new file mode 100644 index 00000000000..a40df85841c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/base_model.mustache @@ -0,0 +1,319 @@ +licenseInfo}} + +/** + * NOTE: This class is auto generated by the openapi generator program. + * https://github.com/openapitools/openapi-generator + * Do not edit the class manually. + */ + +declare(strict_types=1); + +namespace {{invokerPackage}}; + +use OpenAPIServer\Mock\OpenApiModelInterface; +use OpenAPIServer\Mock\OpenApiDataMockerInterface as IMocker; +use InvalidArgumentException; +use StdClass; + +/** + * BaseModel. + */ +class BaseModel implements OpenApiModelInterface +{ + // phpcs:disable Generic.Commenting.DocComment + + /** + * @var string Constant with OAS schema of current class. + * Should be overwritten by inherited class. + */ + protected const MODEL_SCHEMA = + <<<'SCHEMA' + { + "type" : "object", + "properties": {} + } +SCHEMA; + + /** @var string[] Valid OAS data types */ + protected const VALID_OAS_DATA_TYPES = [ + IMocker::DATA_TYPE_INTEGER, + IMocker::DATA_TYPE_NUMBER, + IMocker::DATA_TYPE_STRING, + IMocker::DATA_TYPE_BOOLEAN, + IMocker::DATA_TYPE_ARRAY, + IMocker::DATA_TYPE_OBJECT, + ]; + + /** + * @var string Models namespace. + * Can be required for data deserialization when model contains referenced schemas. + */ + protected const MODELS_NAMESPACE = '\{{modelPackage}}'; + + /** + * @var mixed Data container. + * PHP has restrictions on variable names, while OAS is much more permissive. + * This container helps to store unusual properties like '123_prop' without renaming. + */ + protected $dataContainer; + // phpcs:enable + + /** + * Model constructor. + */ + public function __construct() + { + $schema = static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + $this->validateModelType($modelType, true); + + // set initial data + switch ($modelType) { + case IMocker::DATA_TYPE_OBJECT: + case IMocker::DATA_TYPE_ARRAY: + $this->dataContainer = []; + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + default: + // scalar type + $this->dataContainer = null; + } + } + + /** + * Gets OAS 3.0 schema mapped to current class. + * + * @return array + */ + public static function getOpenApiSchema(): array + { + return json_decode(static::MODEL_SCHEMA, true); + } + + /** + * Creates new instance from provided data. + * + * @param mixed $data Data with values for new instance. + * + * @return OpenApiModelInterface + */ + public static function createFromData($data): OpenApiModelInterface + { + $instance = new static(); + $instance->setData($data); + return $instance; + } + + /** + * Sets instance data. + * + * @param mixed $data Data with values for new instance. + * + * @throws \InvalidArgumentException When value for array type is invalid. + * + * @return void + */ + public function setData($data): void + { + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + switch ($modelType) { + case IMocker::DATA_TYPE_ARRAY: + // data for array OAS type should be straight indexed array + if (is_array($data)) { + $arr = []; + for ($i = 0; $i < count($data); $i++) { + if (isset($data[$i])) { + $arr[$i] = $data[$i]; + } + } + + if (count($arr) === count($data)) { + $this->dataContainer = $arr; + return; + } + } + + throw new InvalidArgumentException( + sprintf('Invalid data for %s model because it accepts straight indexed arrays only', static::class) + ); + break; + case IMocker::DATA_TYPE_OBJECT: + foreach ($data as $key => $value) { + // this action handles __set method + $this->{$key} = $value; + } + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + default: + $this->dataContainer = $data; + break; + } + } + + /** + * Returns instance data. + * + * @return mixed + */ + public function getData() + { + $data = null; + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + switch ($modelType) { + case IMocker::DATA_TYPE_OBJECT: + // need to convert data container to object + $data = new StdClass(); + $definedProps = (array_key_exists('properties', $schema)) ? $schema['properties'] : null; + if (is_array($definedProps) || is_object($definedProps)) { + foreach ($definedProps as $propName => $propSchema) { + if (array_key_exists($propName, $this->dataContainer)) { + $data->{$propName} = $this->dataContainer[$propName]; + } elseif (array_key_exists('required', $schema) && in_array($propName, $schema['required'])) { + // property is required but not set + $data->{$propName} = null; + } + } + } + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + case IMocker::DATA_TYPE_ARRAY: + default: + $data = $this->dataContainer; + } + return $data; + } + + /** + * Writes data to inaccessible (protected or private) or non-existing properties. + * Ref @link https://www.php.net/manual/en/language.oop5.overloading.php#object.set + * + * @param string $param Property name. + * @param mixed $value Property value. + * + * @throws \InvalidArgumentException When property doesn't exist in related OAS schema. + * + * @return void + */ + public function __set(string $param, $value): void + { + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + switch ($modelType) { + case IMocker::DATA_TYPE_OBJECT: + $definedProps = (array_key_exists('properties', $schema)) ? (array) $schema['properties'] : null; + if (is_array($definedProps) && !in_array($param, array_keys($definedProps))) { + throw new InvalidArgumentException( + sprintf('Cannot set %s property of %s model because it doesn\'t exist in related OAS schema', $param, static::class) + ); + } + $this->dataContainer[$param] = $value; + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + case IMocker::DATA_TYPE_ARRAY: + default: + // scalar type and array cannot use property assignation + throw new InvalidArgumentException( + sprintf('Cannot set %s property of %s model because it\'s %s type. Use setData method instead', $param, static::class, $modelType) + ); + } + } + + /** + * Reads data from inaccessible (protected or private) or non-existing properties. + * Ref @link https://www.php.net/manual/en/language.oop5.overloading.php#object.get + * + * @param string $param Property name. + * + * @throws \InvalidArgumentException When property doesn't exist in related OAS schema. + * + * @return mixed Property value + */ + public function __get(string $param) + { + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + $definedProps = (array_key_exists('properties', $schema)) ? (array) $schema['properties'] : null; + if (!in_array($modelType, [null, IMocker::DATA_TYPE_OBJECT])) { + // scalar type + throw new InvalidArgumentException( + sprintf('Cannot get %s property of %s model because getter is for object OAS type only', $param, static::class) + ); + } + + if ( + is_array($definedProps) + && in_array($param, array_keys($definedProps)) + ) { + return $this->dataContainer[$param]; + } elseif ($definedProps === null) { + // props are undefined + return (isset($this->dataContainer[$param])) ? $this->dataContainer[$param] : null; + } + + throw new InvalidArgumentException( + sprintf('Cannot get %s property of %s model because it doesn\'t exist in related OAS schema', $param, static::class) + ); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * Ref @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. + */ + public function jsonSerialize() + { + return $this->getData(); + } + + /** + * Checks if type is valid OAS data type. + * + * @param string|null $type Model type. + * @param bool $throwException Throws InvalidArgumentException when set to true and processed type is invalid. + * + * @throws \InvalidArgumentException When $throwException set to TRUE. + * + * @return bool + */ + protected function validateModelType(?string $type = null, bool $throwException = true): bool + { + $isValid = in_array($type, static::VALID_OAS_DATA_TYPES); + if ($type !== null && $isValid === false && $throwException) { + throw new InvalidArgumentException( + sprintf( + 'Invalid OAS schema of %s model, "type" must be one of %s', + static::class, + implode(', ', static::VALID_OAS_DATA_TYPES) + ) + ); + } + return $isValid; + } + + /** + * Returns models namespace. + * + * @return string + */ + public static function getModelsNamespace(): string + { + return static::MODELS_NAMESPACE . stripslashes('\\'); + } +} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/base_model_test.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/base_model_test.mustache new file mode 100644 index 00000000000..6c182d5403c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/base_model_test.mustache @@ -0,0 +1,586 @@ +licenseInfo}} + +/** + * NOTE: This class is auto generated by the openapi generator program. + * https://github.com/openapitools/openapi-generator + * Do not edit the class manually. + */ + +namespace {{invokerPackage}}; + +use PHPUnit\Framework\TestCase; +use {{invokerPackage}}\BaseModel; +use OpenAPIServer\Mock\OpenApiModelInterface; +use InvalidArgumentException; +use StdClass; + +/** + * BaseModelTest + * + * phpcs:disable Squiz.Commenting,Generic.Commenting,PEAR.Commenting + * @coversDefaultClass \{{invokerPackage}}\BaseModel + */ +class BaseModelTest extends TestCase +{ + + /** + * @covers ::__construct + * @covers ::validateModelType + * @dataProvider provideClassesAndDefaultData + */ + public function testConstructorAndDefaultData($className, $expectedJson) + { + $item = new $className(); + $this->assertEquals($expectedJson, json_encode($item->getData())); + } + + public function provideClassesAndDefaultData() + { + return [ + 'boolean model' => [BasicBooleanTestClass::class, json_encode(null)], + 'integer model' => [BasicIntegerTestClass::class, json_encode(null)], + 'number model' => [BasicNumberTestClass::class, json_encode(null)], + 'string model' => [BasicStringTestClass::class, json_encode(null)], + 'array model' => [BasicArrayTestClass::class, json_encode([])], + 'object model' => [BasicObjectTestClass::class, json_encode(new StdClass())], + 'missing type model' => [MissingTypeTestClass::class, json_encode(null)], + ]; + } + + /** + * @covers ::__construct + * @covers ::validateModelType + * @dataProvider provideInvalidClasses + */ + public function testConstructorWithInvalidTypes($className) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + } + + public function provideInvalidClasses() + { + return [ + 'unknown type model' => [UnknownTypeTestClass::class], + ]; + } + + /** + * @covers ::getOpenApiSchema + */ + public function testGetOpenApiSchema() + { + foreach ( + [ + BaseModel::getOpenApiSchema(), + CatRefTestClass::getOpenApiSchema(), + DogRefTestClass::getOpenApiSchema(), + BasicArrayTestClass::getOpenApiSchema(), + BasicBooleanTestClass::getOpenApiSchema(), + BasicIntegerTestClass::getOpenApiSchema(), + BasicNumberTestClass::getOpenApiSchema(), + BasicObjectTestClass::getOpenApiSchema(), + BasicStringTestClass::getOpenApiSchema(), + ] as $schema + ) { + $this->assertTrue(is_array($schema) || is_object($schema)); + } + } + + /** + * @covers ::createFromData + * @covers ::__set + * @covers ::__get + * @dataProvider provideCreateFromDataArguments + */ + public function testCreateFromData($modelClass, $data) + { + $item = $modelClass::createFromData($data); + $this->assertInstanceOf($modelClass, $item); + $this->assertInstanceOf(OpenApiModelInterface::class, $item); + foreach ($data as $propName => $propValue) { + $this->assertSame($propValue, $item->{$propName}); + } + } + + public function provideCreateFromDataArguments() + { + return [ + 'CatRefTestClass' => [ + CatRefTestClass::class, + [ + 'className' => 'cheshire', + 'color' => 'gray', + 'declawed' => true, + ], + ], + 'DogRefTestClass' => [ + DogRefTestClass::class, + [ + 'className' => 'bulldog', + 'color' => 'black', + 'declawed' => false, + ], + ], + ]; + } + + /** + * @covers ::setData + * @covers ::getData + * @dataProvider provideScalarModels + */ + public function testSetDataScalar($className, array $setDataValues, array $expectedDataValues) + { + $item = new $className(); + for ($i = 0; $i < count($setDataValues); $i++) { + if ($i > 0) { + // value should be previous + $this->assertSame($expectedDataValues[$i - 1], $item->getData()); + } else { + // initial value should be null + $this->assertNull($item->getData()); + } + $item->setData($setDataValues[$i]); + // values should be overwritten + $this->assertSame($expectedDataValues[$i], $item->getData()); + } + } + + public function provideScalarModels() + { + return [ + 'boolean model' => [ + BasicBooleanTestClass::class, + [false, true, false], + [false, true, false], + ], + 'integer model' => [ + BasicIntegerTestClass::class, + [-50, 322, 100500, -1000, 0], + [-50, 322, 100500, -1000, 0], + ], + 'number model' => [ + BasicNumberTestClass::class, + [-50.324, 322.756, 100500.09, -1000.43, 0], + [-50.324, 322.756, 100500.09, -1000.43, 0], + ], + 'string model' => [ + BasicStringTestClass::class, + ['foobar', 'hello world', '100', '-56', 'true', 'null', 'false'], + ['foobar', 'hello world', '100', '-56', 'true', 'null', 'false'], + ], + ]; + } + + /** + * @covers ::setData + * @covers ::getData + */ + public function testSetDataOfArray() + { + $basic = new BasicArrayTestClass(); + $data = ['foo', 'bar', 'baz']; + $basic->setData($data); + $this->assertEquals($data, $basic->getData()); + } + + /** + * @covers ::setData + * @dataProvider provideInvalidDataForArrayModel + */ + public function testSetDataOfArrayWithInvalidData($className, $data) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + $item->setData($data); + } + + public function provideInvalidDataForArrayModel() + { + $obj = new StdClass(); + $obj->foo = 'bar'; + $obj->baz = 'baf'; + $arr = []; + $arr[5] = 'foo'; + $arr[6] = 'bar'; + return [ + 'array with spaced indexes data' => [ + BasicArrayTestClass::class, + $arr, + ], + 'assoc array data' => [ + BasicArrayTestClass::class, + ['foo' => 'bar', 'baz' => 'baf'], + ], + 'object data' => [ + BasicArrayTestClass::class, + $obj, + ], + ]; + } + + /** + * @covers ::setData + * @covers ::getData + */ + public function testSetDataOfObject() + { + $basic = new BasicObjectTestClass(); + $data = ['foo' => 'bar']; + $basic->setData($data); + $this->assertSame('bar', $basic->foo); + } + + /** + * @covers ::getData + */ + public function testGetDataOfObject() + { + $catItem = new CatRefTestClass(); + $catItem->setData([ + 'color' => 'grey', + 'declawed' => false, + ]); + $data = $catItem->getData(); + $this->assertInstanceOf(StdClass::class, $data); + $this->assertSame('grey', $data->color); + $this->assertSame(false, $data->declawed); + } + + /** + * @covers ::__set + * @covers ::__get + */ + public function testSetter() + { + $item = new CatRefTestClass(); + $item->className = 'cheshire'; + $item->color = 'black'; + $item->declawed = false; + $this->assertSame('cheshire', $item->className); + $this->assertSame('black', $item->color); + $this->assertSame(false, $item->declawed); + } + + /** + * @covers ::__set + * @dataProvider provideScalarsAndArray + */ + public function testSetterOfScalarAndArray($className) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + $item->foo = 'bar'; + } + + public function provideScalarsAndArray() + { + return [ + 'boolean model' => [BasicBooleanTestClass::class], + 'integer model' => [BasicIntegerTestClass::class], + 'number model' => [BasicNumberTestClass::class], + 'string model' => [BasicStringTestClass::class], + 'array model' => [BasicArrayTestClass::class], + ]; + } + + /** + * @covers ::__set + */ + public function testSetterWithUnknownProp() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf( + 'Cannot set unknownProp property of %s model because it doesn\'t exist in related OAS schema', + CatRefTestClass::class + ) + ); + $item = new CatRefTestClass(); + $item->unknownProp = 'foobar'; + } + + /** + * @covers ::__get + */ + public function testGetterWithUnknownProp() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf( + 'Cannot get unknownProp property of %s model because it doesn\'t exist in related OAS schema', + CatRefTestClass::class + ) + ); + $item = new CatRefTestClass(); + $unknownProp = $item->unknownProp; + } + + /** + * @covers ::__get + * @dataProvider provideScalarsAndArray + */ + public function testGetterOfScalarAndArray($className) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + $bar = $item->foo; + } + + /** + * @covers ::__set + * @covers ::__get + */ + public function testSetterAndGetterOfBasicObject() + { + $item = new BasicObjectTestClass(); + $item->unknown = 'foo'; + $this->assertEquals('foo', $item->unknown); + } + + /** + * @covers ::jsonSerialize + * @dataProvider provideJsonSerializeArguments + */ + public function testJsonSerialize($className, $data, $expectedJson) + { + $item = $className::createFromData($data); + $this->assertEquals($expectedJson, json_encode($item)); + } + + public function provideJsonSerializeArguments() + { + return [ + 'model with all props' => [ + CatRefTestClass::class, + [ + 'className' => 'cheshire', + 'color' => 'black', + 'declawed' => false, + ], + json_encode([ + 'className' => 'cheshire', + 'color' => 'black', + 'declawed' => false, + ]), + ], + 'model with required props' => [ + CatRefTestClass::class, + [ + 'className' => 'cheshire', + ], + json_encode([ + 'className' => 'cheshire', + ]), + ], + 'model with missed required prop' => [ + CatRefTestClass::class, + [ + 'color' => 'black', + ], + json_encode([ + 'className' => null, + 'color' => 'black', + ]), + ], + 'model with schema serialized as assoc array' => [ + DogRefTestClass::class, + [ + 'className' => 'bulldog', + 'color' => 'gray', + 'declawed' => false, + ], + json_encode([ + 'className' => 'bulldog', + 'color' => 'gray', + 'declawed' => false, + ]), + ], + 'model of basic array' => [ + BasicArrayTestClass::class, + ['hello', 'world'], + json_encode(['hello', 'world']), + ], + 'model of basic boolean' => [ + BasicBooleanTestClass::class, + false, + json_encode(false), + ], + 'model of basic integer' => [ + BasicIntegerTestClass::class, + -500, + json_encode(-500), + ], + 'model of basic number' => [ + BasicNumberTestClass::class, + -3.1434, + json_encode(-3.1434), + ], + 'model of basic object' => [ + BasicObjectTestClass::class, + new \StdClass(), + json_encode(new \StdClass()), + ], + 'model of basic string' => [ + BasicStringTestClass::class, + 'foobar', + json_encode('foobar'), + ], + ]; + } + + /** + * @covers ::getModelsNamespace + * @dataProvider provideTestClasses + */ + public function testGetModelsNamespace($classname) + { + $this->assertTrue(method_exists($classname, 'getModelsNamespace')); + $getModelsNamespace = $classname . '::getModelsNamespace'; + $namespace = $getModelsNamespace(); + $this->assertIsString($namespace); + } + + public function provideTestClasses() + { + return [ + [BasicArrayTestClass::class], + [BasicBooleanTestClass::class], + [BasicIntegerTestClass::class], + [BasicNumberTestClass::class], + [BasicObjectTestClass::class], + [BasicStringTestClass::class], + [CatRefTestClass::class], + [DogRefTestClass::class], + ]; + } +} + +// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses +class BasicArrayTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "array" +} +SCHEMA; +} + +class BasicBooleanTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "boolean" +} +SCHEMA; +} + +class BasicIntegerTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "integer" +} +SCHEMA; +} + +class BasicNumberTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "number" +} +SCHEMA; +} + +class BasicObjectTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "object" +} +SCHEMA; +} + +class BasicStringTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "string" +} +SCHEMA; +} + +class CatRefTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "required" : [ "className" ], + "type" : "object", + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "type" : "string", + "default" : "red" + }, + "declawed" : { + "type" : "boolean" + } + }, + "discriminator" : { + "propertyName" : "className" + } +} +SCHEMA; +} + +class ClassWithoutGetSchemaMethod +{ + +} + +class DogRefTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "required" : [ "className" ], + "type" : "object", + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "type" : "string", + "default" : "black" + }, + "declawed" : { + "type" : "boolean" + } + }, + "discriminator" : { + "propertyName" : "className" + } +} +SCHEMA; +} + +class MissingTypeTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{} +SCHEMA; +} + +class UnknownTypeTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "foobar" +} +SCHEMA; +} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache index ad746666cb2..78373208494 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache @@ -11,6 +11,8 @@ "php": "^7.2", "slim/slim": "^4.5.0", "dyorg/slim-token-authentication": "dev-slim4", + "ybelenko/openapi-data-mocker": "^1.0", + "ybelenko/openapi-data-mocker-server-middleware": "^1.0", {{#isSlimPsr7}} "slim/psr7": "^1.1.0" {{/isSlimPsr7}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache index 01c9049226d..1175d76e7bf 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache @@ -12,7 +12,7 @@ require_once __DIR__ . '/vendor/autoload.php'; use {{invokerPackage}}\SlimRouter; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; -use {{mockPackage}}\OpenApiDataMocker; +use OpenAPIServer\Mock\OpenApiDataMocker; {{/apiInfo}} $config = []; @@ -53,21 +53,28 @@ $config['tokenAuthenticationOptions'] = [ /** * Mocker Middleware options. */ +$mocker = new OpenApiDataMocker(); +$mocker->setModelsNamespace('{{modelPackage}}\\'); $config['mockerOptions'] = [ - // 'dataMocker' => new OpenApiDataMocker(), + // 'dataMocker' => $mocker, - // 'getMockResponseCallback' => function (ServerRequestInterface $request, array $responses) { + // 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, $responses) { // // check if client clearly asks for mocked response + // $pingHeader = 'X-{{invokerPackage}}-Mock'; + // $pingHeaderCode = 'X-{{invokerPackage}}-Mock-Code'; // if ( - // $request->hasHeader('X-{{invokerPackage}}-Mock') - // && $request->getHeader('X-{{invokerPackage}}-Mock')[0] === 'ping' + // $request->hasHeader($pingHeader) + // && $request->getHeader($pingHeader)[0] === 'ping' // ) { - // if (array_key_exists('default', $responses)) { - // return $responses['default']; + // $responses = (array) $responses; + // $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default'; + // if (array_key_exists($requestedResponseCode, $responses)) { + // return $requestedResponseCode; // } - // // return first response - // return $responses[array_key_first($responses)]; + // // return first response key + // reset($responses); + // return key($responses); // } // return false; diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/mock_server.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/mock_server.mustache deleted file mode 100644 index 15d8c2dcadf..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/mock_server.mustache +++ /dev/null @@ -1,135 +0,0 @@ -# {{packageName}} - PHP Slim 4 Server library for {{appName}} - -## Mock Server Documentation - -### Mocker Options -To enable mock server uncomment these lines in `index.php` config file: - -```php -/** - * Mocker Middleware options. - */ -$config['mockerOptions'] = [ - 'dataMocker' => new OpenApiDataMocker(), - - 'getMockResponseCallback' => function (ServerRequestInterface $request, array $responses) { - // check if client clearly asks for mocked response - if ( - $request->hasHeader('X-{{invokerPackage}}-Mock') - && $request->getHeader('X-{{invokerPackage}}-Mock')[0] === 'ping' - ) { - if (array_key_exists('default', $responses)) { - return $responses['default']; - } - - // return first response - return $responses[array_key_first($responses)]; - } - - return false; - }, - - 'afterCallback' => function ($request, $response) { - // mark mocked response to distinguish real and fake responses - return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong'); - }, -]; -``` - -* `dataMocker` is mocker class instance. To create custom data mocker extend `{{mockPackage}}\{{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}}`. -* `getMockResponseCallback` is callback before mock data generation. Above example shows how to enable mock feature for only requests with `{{X-{{invokerPackage}}}}-mock: ping` HTTP header. Adjust requests filtering to fit your project requirements. This function must return single response schema from `$responses` array parameter. **Mock feature is disabled when callback returns anything beside array.** -* `afterCallback` is callback executed after mock data generation. Most obvious use case is append specific HTTP headers to distinguish real and fake responses. **This function must always return response instance.** - -### Supported features - -All data types supported except specific string formats: `email`, `uuid`, `password` which are poorly implemented. - -#### Data Types Support - -| Data Type | Data Format | Supported | -|:---------:|:-----------:|:------------------:| -| `integer` | `int32` | :white_check_mark: | -| `integer` | `int64` | :white_check_mark: | -| `number` | `float` | :white_check_mark: | -| `number` | `double` | | -| `string` | `byte` | :white_check_mark: | -| `string` | `binary` | :white_check_mark: | -| `boolean` | | :white_check_mark: | -| `string` | `date` | :white_check_mark: | -| `string` | `date-time` | :white_check_mark: | -| `string` | `password` | :white_check_mark: | -| `string` | `email` | :white_check_mark: | -| `string` | `uuid` | :white_check_mark: | - -#### Data Options Support - -| Data Type | Option | Supported | -|:-----------:|:----------------------:|:------------------:| -| `string` | `minLength` | :white_check_mark: | -| `string` | `maxLength` | :white_check_mark: | -| `string` | `enum` | :white_check_mark: | -| `string` | `pattern` | | -| `integer` | `minimum` | :white_check_mark: | -| `integer` | `maximum` | :white_check_mark: | -| `integer` | `exclusiveMinimum` | :white_check_mark: | -| `integer` | `exclusiveMaximum` | :white_check_mark: | -| `number` | `minimum` | :white_check_mark: | -| `number` | `maximum` | :white_check_mark: | -| `number` | `exclusiveMinimum` | :white_check_mark: | -| `number` | `exclusiveMaximum` | :white_check_mark: | -| `array` | `items` | :white_check_mark: | -| `array` | `additionalItems` | | -| `array` | `minItems` | :white_check_mark: | -| `array` | `maxItems` | :white_check_mark: | -| `array` | `uniqueItems` | | -| `object` | `properties` | :white_check_mark: | -| `object` | `maxProperties` | | -| `object` | `minProperties` | | -| `object` | `patternProperties` | | -| `object` | `additionalProperties` | | -| `object` | `required` | | -| `*` | `$ref` | :white_check_mark: | -| `*` | `allOf` | | -| `*` | `anyOf` | | -| `*` | `oneOf` | | -| `*` | `not` | | - -### Known Limitations - -Avoid circular refs in your schema. Schema below can cause infinite loop and `Out of Memory` PHP error: -```yml -# ModelA has reference to ModelB while ModelB has reference to ModelA. -# Mock server will produce huge nested JSON example and ended with `Out of Memory` error. -definitions: - ModelA: - type: object - properties: - model_b: - $ref: '#/definitions/ModelB' - ModelB: - type: array - items: - $ref: '#/definitions/ModelA' -``` - -Don't ref scalar types, because generator will not produce models which mock server can find. So schema below will cause error: -```yml -# generated build contains only `OuterComposite` model class which referenced to not existed `OuterNumber`, `OuterString`, `OuterBoolean` classes -# mock server cannot mock `OuterComposite` model and throws exception -definitions: - OuterComposite: - type: object - properties: - my_number: - $ref: '#/definitions/OuterNumber' - my_string: - $ref: '#/definitions/OuterString' - my_boolean: - $ref: '#/definitions/OuterBoolean' - OuterNumber: - type: number - OuterString: - type: string - OuterBoolean: - type: boolean -``` diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/model.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/model.mustache index e9ec40e4b6e..53f70127a77 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/model.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/model.mustache @@ -8,7 +8,7 @@ */{{#models}}{{#model}} namespace {{modelPackage}}; -use {{interfacesPackage}}\{{interfaceNamePrefix}}Model{{interfaceNameSuffix}}; +use {{invokerPackage}}\BaseModel; /** * {{classname}} @@ -17,27 +17,20 @@ use {{interfacesPackage}}\{{interfaceNamePrefix}}Model{{interfaceNameSuffix}}; * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator */ -class {{classname}} implements {{interfaceNamePrefix}}Model{{interfaceNameSuffix}} +class {{classname}} extends BaseModel { - private const MODEL_SCHEMA = <<<'SCHEMA' -{{{modelJson}}} -SCHEMA; - {{#vars}} - - /** @var {{dataType}} ${{name}} {{#description}}{{description}}{{/description}}*/ - private ${{name}}; - {{/vars}} + /** + * @var string Models namespace. + * Can be required for data deserialization when model contains referenced schemas. + */ + protected const MODELS_NAMESPACE = '\{{modelPackage}}'; /** - * Returns model schema. - * - * @param bool $assoc When TRUE, returned objects will be converted into associative arrays. Default FALSE. - * - * @return array + * @var string Constant with OAS schema of current class. + * Should be overwritten by inherited class. */ - public static function getOpenApiSchema($assoc = false) - { - return json_decode(static::MODEL_SCHEMA, $assoc); - } + protected const MODEL_SCHEMA = <<<'SCHEMA' +{{{modelJson}}} +SCHEMA; } {{/model}}{{/models}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/model_interface.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/model_interface.mustache deleted file mode 100644 index 07b75f7d558..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/model_interface.mustache +++ /dev/null @@ -1,30 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{interfacesPackage}}; - -/** - * {{interfaceNamePrefix}}Model{{interfaceNameSuffix}} Class Doc Comment - * - * @package {{interfacesPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - */ -interface {{interfaceNamePrefix}}Model{{interfaceNameSuffix}} -{ - /** - * Returns model schema. - * - * @param bool $assoc When TRUE, returned objects will be converted into associative arrays. Default FALSE. - * - * @return array - */ - public static function getOpenApiSchema($assoc = false); -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/model_test.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/model_test.mustache index 7aa842baef3..218a941c346 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/model_test.mustache @@ -59,6 +59,12 @@ class {{classname}}Test extends TestCase public function test{{classname}}() { $test{{classname}} = new {{classname}}(); + $namespacedClassname = {{classname}}::getModelsNamespace() . '\\{{classname}}'; + $this->assertSame('\\' . {{classname}}::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( 'Test of "{{classname}}" model has not been implemented yet.' ); @@ -82,9 +88,7 @@ class {{classname}}Test extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = {{classname}}::getOpenApiSchema(); - $schemaArr = {{classname}}::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = {{classname}}::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait.mustache deleted file mode 100644 index 2c29d3ae820..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait.mustache +++ /dev/null @@ -1,108 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{utilsPackage}}; - -use {{utilsPackage}}\{{traitNamePrefix}}StringUtils{{traitNameSuffix}}; - -/** - * {{traitNamePrefix}}ModelUtils{{traitNameSuffix}} Class Doc Comment - * This class duplicates functionality of ModelUtils.java and AbstractPhpCodegen.java classes. - * - * @package {{utilsPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - */ -trait {{traitNamePrefix}}ModelUtils{{traitNameSuffix}} -{ - use {{traitNamePrefix}}StringUtils{{traitNameSuffix}}; - - /** - * Parses model class name from provided ref. - * @link https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#reference-object - * This method doesn't check that class exists and autoloaded. - * This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java class. - * - * @param string $ref Reference, eg. #/components/schemas/Pet - * - * @return string|null classname or null on fail - */ - public static function getSimpleRef($ref) - { - $model = null; - if (stripos($ref, '#/components/') === 0) { - // starts with #/components/ - $model = substr($ref, strrpos($ref, '/') + 1); - } elseif (stripos($ref, '#/definitions/') === 0) { - // starts with #/definitions/ - $model = substr($ref, strrpos($ref, '/') + 1); - } - - return $model; - } - - /** - * Output the proper model name (capitalized). - * In case the name belongs to the TypeSystem it won't be renamed. - * This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java class. - * - * @param string $name the name of the model - * @param string|null $modelNamePrefix modelNamePrefix generator option - * @param string|null $modelNameSuffix modelNameSuffix generator option - * - * @return string capitalized model name - */ - public static function toModelName( - $name, - $modelNamePrefix = {{#modelNamePrefix}}'{{modelNamePrefix}}'{{/modelNamePrefix}}{{^modelNamePrefix}}null{{/modelNamePrefix}}, - $modelNameSuffix = {{#modelNameSuffix}}'{{modelNameSuffix}}'{{/modelNameSuffix}}{{^modelNameSuffix}}null{{/modelNameSuffix}} - ) { - if (is_string($name) === false || empty($name)) { - return null; - } - - // remove [ - $name = str_replace(']', '', $name); - - // Note: backslash ("\\") is allowed for e.g. "\\DateTime" - $name = preg_replace('/[^\w\\\\]+/', '_', $name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - - // remove underscores from start and end - $name = trim($name, '_'); - - // remove dollar sign - $name = str_replace('$', '', $name); - - // model name cannot use reserved keyword - if (self::isReservedWord($name)) { - $name = 'model_' . $name; // e.g. return => ModelReturn (after camelize) - } - - // model name starts with number - if (preg_match('/^\d.*/', $name) === 1) { - $name = 'model_' . $name; // e.g. 200Response => Model200Response (after camelize) - } - - // add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime) - if (preg_match('/^\\\\.*/', $name) !== 1) { - if (is_string($modelNamePrefix) && !empty($modelNamePrefix)) { - $name = $modelNamePrefix . '_' . $name; - } - - if (is_string($modelNameSuffix) && !empty($modelNameSuffix)) { - $name = $name . '_' . $modelNameSuffix; - } - } - - // camelize the model name - // phone_number => PhoneNumber - return self::camelize($name); - } -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait_test.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait_test.mustache deleted file mode 100644 index 123d9cf648b..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/model_utils_trait_test.mustache +++ /dev/null @@ -1,87 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{utilsPackage}}; - -use {{utilsPackage}}\{{traitNamePrefix}}ModelUtils{{traitNameSuffix}} as ModelUtils; -use PHPUnit\Framework\TestCase; - -/** - * {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}Test Class Doc Comment - * - * @package {{utilsPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - * @coversDefaultClass \{{utilsPackage}}\{{traitNamePrefix}}ModelUtils{{traitNameSuffix}} - */ -class {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}Test extends TestCase -{ - /** - * @covers ::getSimpleRef - * @dataProvider provideRefs - */ - public function testGetSimpleRef($ref, $expectedRef) - { - $this->assertSame($expectedRef, ModelUtils::getSimpleRef($ref)); - } - - public function provideRefs() - { - return [ - 'Reference Object OAS 3.0' => [ - '#/components/schemas/Pet', 'Pet', - ], - 'Reference Object Swagger 2.0' => [ - '#/definitions/Pet', 'Pet', - ], - 'Underscored classname' => [ - '#/components/schemas/_foobar_Objects', '_foobar_Objects', - ], - 'Relative Documents With Embedded Schema' => [ - 'definitions.json#/Pet', null, - ], - 'null as argument' => [ - null, null, - ], - 'number as argument' => [ - 156, null, - ], - ]; - } - - /** - * @covers ::toModelName - * @dataProvider provideModelNames - */ - public function testToModelName($name, $prefix, $suffix, $expectedModel) - { - $this->assertSame($expectedModel, ModelUtils::toModelName($name, $prefix, $suffix)); - } - - public function provideModelNames() - { - return [ - // fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java - ['abcd', null, null, 'Abcd'], - ['some-value', null, null, 'SomeValue'], - ['some_value', null, null, 'SomeValue'], - ['$type', null, null, 'Type'], - ['123', null, null, 'Model123'], - ['$123', null, null, 'Model123'], - ['return', null, null, 'ModelReturn'], - ['200Response', null, null, 'Model200Response'], - ['abcd', 'SuperModel', null, 'SuperModelAbcd'], - ['abcd', null, 'WithEnd', 'AbcdWithEnd'], - ['abcd', 'WithStart', 'AndEnd', 'WithStartAbcdAndEnd'], - ['_foobar_Objects', null, null, 'FoobarObjects'], - [null, null, null, null], - ]; - } -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker.mustache deleted file mode 100644 index a432434d924..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker.mustache +++ /dev/null @@ -1,609 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{mockPackage}}; - -use {{mockPackage}}\{{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} as IMocker; -use {{utilsPackage}}\{{traitNamePrefix}}ModelUtils{{traitNameSuffix}}; -use StdClass; -use DateTime; -use InvalidArgumentException; - -/** - * OpenApiDataMocker Class Doc Comment - * - * @package {{mockPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - */ -final class OpenApiDataMocker implements IMocker -{ - use {{traitNamePrefix}}ModelUtils{{traitNameSuffix}}; - - /** - * Mocks OpenApi Data. - * @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#data-types - * - * @param $dataType string OpenApi data type. Use constants from {{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} class - * @param $dataFormat string (optional) OpenApi data format - * @param $options array|null (optional) OpenApi data options - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return mixed - */ - public function mock($dataType, $dataFormat = null, $options = []) - { - switch ($dataType) { - case IMocker::DATA_TYPE_INTEGER: - case IMocker::DATA_TYPE_NUMBER: - $minimum = $options['minimum'] ?? null; - $maximum = $options['maximum'] ?? null; - $exclusiveMinimum = $options['exclusiveMinimum'] ?? false; - $exclusiveMaximum = $options['exclusiveMaximum'] ?? false; - if ($dataType === IMocker::DATA_TYPE_INTEGER) { - return $this->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - } - return $this->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - case IMocker::DATA_TYPE_STRING: - $minLength = $options['minLength'] ?? 0; - $maxLength = $options['maxLength'] ?? null; - $enum = $options['enum'] ?? null; - return $this->mockString($dataFormat, $minLength, $maxLength, $enum); - case IMocker::DATA_TYPE_BOOLEAN: - return $this->mockBoolean(); - case IMocker::DATA_TYPE_ARRAY: - $items = $options['items'] ?? null; - $minItems = $options['minItems'] ?? 0; - $maxItems = $options['maxItems'] ?? null; - $uniqueItems = $options['uniqueItems'] ?? false; - return $this->mockArray($items, $minItems, $maxItems, $uniqueItems); - case IMocker::DATA_TYPE_OBJECT: - $properties = $options['properties'] ?? null; - $minProperties = $options['minProperties'] ?? 0; - $maxProperties = $options['maxProperties'] ?? null; - $additionalProperties = $options['additionalProperties'] ?? null; - $required = $options['required'] ?? null; - return $this->mockObject($properties, $minProperties, $maxProperties, $additionalProperties, $required); - default: - throw new InvalidArgumentException('"dataType" must be one of ' . implode(', ', [ - IMocker::DATA_TYPE_INTEGER, - IMocker::DATA_TYPE_NUMBER, - IMocker::DATA_TYPE_STRING, - IMocker::DATA_TYPE_BOOLEAN, - IMocker::DATA_TYPE_ARRAY, - IMocker::DATA_TYPE_OBJECT, - ])); - } - } - - /** - * Shortcut to mock integer type - * Equivalent to mockData(DATA_TYPE_INTEGER); - * - * @param string|null $dataFormat (optional) int32 or int64 - * @param number|null $minimum (optional) Default is 0 - * @param number|null $maximum (optional) Default is mt_getrandmax() - * @param bool|null $exclusiveMinimum (optional) Default is false - * @param bool|null $exclusiveMaximum (optional) Default is false - * - * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided - * - * @return int - */ - public function mockInteger( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - $dataFormat = is_string($dataFormat) ? strtolower($dataFormat) : $dataFormat; - switch ($dataFormat) { - case IMocker::DATA_FORMAT_INT32: - // -2147483647..2147483647 - $minimum = is_numeric($minimum) ? max($minimum, -2147483647) : -2147483647; - $maximum = is_numeric($maximum) ? min($maximum, 2147483647) : 2147483647; - break; - case IMocker::DATA_FORMAT_INT64: - // -9223372036854775807..9223372036854775807 - $minimum = is_numeric($minimum) ? max($minimum, -9223372036854775807) : -9223372036854775807; - $maximum = is_numeric($maximum) ? min($maximum, 9223372036854775807) : 9223372036854775807; - break; - default: - // do nothing, unsupported format - } - - return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 0); - } - - /** - * Shortcut to mock number type - * Equivalent to mockData(DATA_TYPE_NUMBER); - * - * @param string|null $dataFormat (optional) float or double - * @param number|null $minimum (optional) Default is 0 - * @param number|null $maximum (optional) Default is mt_getrandmax() - * @param bool|null $exclusiveMinimum (optional) Default is false - * @param bool|null $exclusiveMaximum (optional) Default is false - * - * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided - * - * @return float - */ - public function mockNumber( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 4); - } - - /** - * Shortcut to mock string type - * Equivalent to mockData(DATA_TYPE_STRING); - * - * @param string|null $dataFormat (optional) one of byte, binary, date, date-time, password - * @param int|null $minLength (optional) Default is 0 - * @param int|null $maxLength (optional) Default is 100 chars - * @param array $enum (optional) This array should have at least one element. - * Elements in the array should be unique. - * @param string|null $pattern (optional) This string should be a valid regular expression, according to the ECMA 262 regular expression dialect. - * Recall: regular expressions are not implicitly anchored. - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return string - */ - public function mockString( - $dataFormat = null, - $minLength = 0, - $maxLength = null, - $enum = null, - $pattern = null - ) { - $str = ''; - $getLoremIpsum = function ($length) { - return str_pad( - '', - $length, - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', - \STR_PAD_RIGHT - ); - }; - $truncateOrPad = function ($text, $min = null, $max = null, $glue = '') { - if ($max !== null && mb_strlen($text) > $max) { - // truncate - $text = substr($text, 0, $max); - } elseif ($min !== null && mb_strlen($text) < $min) { - // pad - $text = str_pad('', $min, $text . $glue, \STR_PAD_RIGHT); - } - return $text; - }; - - if ($enum !== null) { - if ( - is_array($enum) === false - || empty($enum) - || count($enum) > count(array_unique($enum)) - ) { - throw new InvalidArgumentException('"enum" must be an array. This array should have at least one element. Elements in the array should be unique.'); - } - - // return random variant - return $enum[mt_rand(0, count($enum) - 1)]; - } - - if ($minLength !== 0 && $minLength !== null) { - if (is_int($minLength) === false) { - throw new InvalidArgumentException('"minLength" must be an integer'); - } elseif ($minLength < 0) { - throw new InvalidArgumentException('"minLength" must be greater than, or equal to, 0'); - } - } else { - $minLength = 0; - } - - if ($maxLength !== null) { - if (is_int($maxLength) === false) { - throw new InvalidArgumentException('"maxLength" must be an integer'); - } elseif ($maxLength < 0) { - throw new InvalidArgumentException('"maxLength" must be greater than, or equal to, 0'); - } - } else { - // since we don't need huge texts by default, lets cut them down to 100 chars - $maxLength = 100; - } - - if ($maxLength < $minLength) { - throw new InvalidArgumentException('"maxLength" value cannot be less than "minLength"'); - } - - switch ($dataFormat) { - case IMocker::DATA_FORMAT_BYTE: - case IMocker::DATA_FORMAT_BINARY: - // base64 encoded string - $inputLength = 1; - $str = base64_encode($getLoremIpsum($inputLength)); - while (mb_strlen($str) < $minLength) { - $inputLength++; - $str = base64_encode($getLoremIpsum($inputLength)); - } - - // base64 encoding produces strings devided by 4, so resulted string can exceed maxLength parameter - // I think truncated(invalid) base64 string is better than oversized, cause this data is fake anyway - $str = $truncateOrPad($str, null, $maxLength, '. '); - break; - case IMocker::DATA_FORMAT_DATE: - case IMocker::DATA_FORMAT_DATE_TIME: - // min unix timestamp is 0 and max is 2147483647 for 32bit systems which equals 2038-01-19 03:14:07 - $date = DateTime::createFromFormat('U', mt_rand(0, 2147483647)); - $str = ($dataFormat === IMocker::DATA_FORMAT_DATE) ? $date->format('Y-m-d') : $date->format('Y-m-d\TH:i:sP'); - - // truncate or pad datestring to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength, ' '); - break; - case IMocker::DATA_FORMAT_PASSWORD: - // use list of most popular passwords - $obviousPassList = [ - 'qwerty', - 'qwerty12345', - 'hello', - '12345', - '0000', - 'qwerty12345!', - 'qwertyuiop[]', - ]; - $str = $obviousPassList[mt_rand(0, count($obviousPassList) - 1)]; - - // truncate or pad password to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength); - break; - case IMocker::DATA_FORMAT_UUID: - // use php built-in uniqid function - $str = uniqid(); - - // truncate or pad password to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength); - break; - case IMocker::DATA_FORMAT_EMAIL: - // just for visionary purpose, not related to real persons - $fakeEmailList = [ - 'johndoe', - 'lhoswald', - 'ojsimpson', - 'mlking', - 'jfkennedy', - ]; - $str = $fakeEmailList[mt_rand(0, count($fakeEmailList) - 1)] . '@example.com'; - - // truncate or pad email to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength); - break; - default: - $str = $getLoremIpsum(mt_rand($minLength, $maxLength)); - } - - return $str; - } - - /** - * Shortcut to mock boolean type - * Equivalent to mockData(DATA_TYPE_BOOLEAN); - * - * @return bool - */ - public function mockBoolean() - { - return (bool) mt_rand(0, 1); - } - - /** - * Shortcut to mock array type - * Equivalent to mockData(DATA_TYPE_ARRAY); - * - * @param object|array $items Object or assoc array of described items - * @param int|null $minItems (optional) An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this keyword. - * @param int|null $maxItems (optional) An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword - * @param bool|null $uniqueItems (optional) If it has boolean value true, the instance validates successfully if all of its elements are unique - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return array - */ - public function mockArray( - $items, - $minItems = 0, - $maxItems = null, - $uniqueItems = false - ) { - $arr = []; - $minSize = 0; - $maxSize = \PHP_INT_MAX; - - if ( - (is_array($items) === false && is_object($items) === false) - || (is_array($items) && array_key_exists('type', $items) === false) - || (is_object($items) && isset($items->type) === false) - ) { - new InvalidArgumentException('"items" must be object or assoc array with "type" key'); - } - - if ($minItems !== null) { - if (is_integer($minItems) === false || $minItems < 0) { - throw new InvalidArgumentException('"mitItems" must be an integer. This integer must be greater than, or equal to, 0'); - } - $minSize = $minItems; - } - - if ($maxItems !== null) { - if (is_integer($maxItems) === false || $maxItems < 0) { - throw new InvalidArgumentException('"maxItems" must be an integer. This integer must be greater than, or equal to, 0.'); - } - if ($maxItems < $minItems) { - throw new InvalidArgumentException('"maxItems" value cannot be less than "minItems"'); - } - $maxSize = $maxItems; - } - - $options = $this->extractSchemaProperties($items); - $dataType = $options['type']; - $dataFormat = $options['format'] ?? null; - $ref = $options['$ref'] ?? null; - - // always generate smallest possible array to avoid huge JSON responses - $arrSize = ($maxSize < 1) ? $maxSize : max($minSize, 1); - while (count($arr) < $arrSize) { - $data = $this->mockFromRef($ref); - $arr[] = ($data) ? $data : $this->mock($dataType, $dataFormat, $options); - } - return $arr; - } - - /** - * Shortcut to mock object type. - * Equivalent to mockData(DATA_TYPE_OBJECT); - * - * @param object|array $properties Object or array of described properties - * @param int|null $minProperties (optional) An object instance is valid against "minProperties" if its number of properties is greater than, or equal to, the value of this keyword. - * @param int|null $maxProperties (optional) An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. - * @param bool|object|array|null $additionalProperties (optional) If "additionalProperties" is true, validation always succeeds. - * If "additionalProperties" is false, validation succeeds only if the instance is an object and all properties on the instance were covered by "properties" and/or "patternProperties". - * If "additionalProperties" is an object, validate the value as a schema to all of the properties that weren't validated by "properties" nor "patternProperties". - * @param array|null $required (optional) This array MUST have at least one element. Elements of this array must be strings, and MUST be unique. - * An object instance is valid if its property set contains all elements in this array value. - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return object - */ - public function mockObject( - $properties, - $minProperties = 0, - $maxProperties = null, - $additionalProperties = null, - $required = null - ) { - $obj = new StdClass(); - - if (is_object($properties) === false && is_array($properties) === false) { - throw new InvalidArgumentException('The value of "properties" must be an array or object'); - } - - foreach ($properties as $propName => $propValue) { - if (is_object($propValue) === false && is_array($propValue) === false) { - throw new InvalidArgumentException('Each value of "properties" must be an array or object'); - } - } - - if ($minProperties !== null) { - if (is_integer($minProperties) === false || $minProperties < 0) { - throw new InvalidArgumentException('"minProperties" must be an integer. This integer must be greater than, or equal to, 0'); - } - } - - if ($maxProperties !== null) { - if (is_integer($maxProperties) === false || $maxProperties < 0) { - throw new InvalidArgumentException('"maxProperties" must be an integer. This integer must be greater than, or equal to, 0.'); - } - if ($maxProperties < $minProperties) { - throw new InvalidArgumentException('"maxProperties" value cannot be less than "minProperties"'); - } - } - - if ($additionalProperties !== null) { - if (is_bool($additionalProperties) === false && is_object($additionalProperties) === false && is_array($additionalProperties) === false) { - throw new InvalidArgumentException('The value of "additionalProperties" must be a boolean or object or array.'); - } - } - - if ($required !== null) { - if ( - is_array($required) === false - || count($required) > count(array_unique($required)) - ) { - throw new InvalidArgumentException('The value of "required" must be an array. Elements of this array must be unique.'); - } - foreach ($required as $requiredPropName) { - if (is_string($requiredPropName) === false) { - throw new InvalidArgumentException('Elements of "required" array must be strings'); - } - } - } - - foreach ($properties as $propName => $propValue) { - $options = $this->extractSchemaProperties($propValue); - $dataType = $options['type']; - $dataFormat = $options['format'] ?? null; - $ref = $options['$ref'] ?? null; - $data = $this->mockFromRef($ref); - $obj->$propName = ($data) ? $data : $this->mock($dataType, $dataFormat, $options); - } - - return $obj; - } - - /** - * Mocks OpenApi Data from schema. - * - * @param array|object $schema OpenAPI schema - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return mixed - */ - public function mockFromSchema($schema) - { - $props = $this->extractSchemaProperties($schema); - if (array_key_exists('$ref', $props) && !empty($props['$ref'])) { - return $this->mockFromRef($props['$ref']); - } elseif ($props['type'] === null) { - throw new InvalidArgumentException('"schema" must be object or assoc array with "type" property'); - } - return $this->mock($props['type'], $props['format'], $props); - } - - /** - * Mock data by referenced schema. - * TODO: this method will return model instance, not an StdClass - * - * @param string|null $ref Ref to model, eg. #/components/schemas/User - * - * @return mixed - */ - public function mockFromRef($ref) - { - $data = null; - if (is_string($ref) && !empty($ref)) { - $refName = static::getSimpleRef($ref); - $modelName = static::toModelName($refName); - $modelClass = '{{modelPackage}}\\' . $modelName; - if (!class_exists($modelClass) || !method_exists($modelClass, 'getOpenApiSchema')) { - throw new InvalidArgumentException(sprintf( - 'Model %s not found or method %s doesn\'t exist', - $modelClass, - $modelClass . '::getOpenApiSchema' - )); - } - $data = $this->mockFromSchema($modelClass::getOpenApiSchema(true)); - } - - return $data; - } - - /** - * @internal Extract OAS properties from array or object. - * @codeCoverageIgnore - * - * @param array|object $val Processed array or object - * - * @return array - */ - private function extractSchemaProperties($val) - { - $props = [ - 'type' => null, - 'format' => null, - ]; - foreach ( - [ - 'type', - 'format', - 'minimum', - 'maximum', - 'exclusiveMinimum', - 'exclusiveMaximum', - 'minLength', - 'maxLength', - 'pattern', - 'enum', - 'items', - 'minItems', - 'maxItems', - 'uniqueItems', - 'properties', - 'minProperties', - 'maxProperties', - 'additionalProperties', - 'required', - 'example', - '$ref', - ] as $propName - ) { - if (is_array($val) && array_key_exists($propName, $val)) { - $props[$propName] = $val[$propName]; - } elseif (is_object($val) && isset($val->$propName)) { - $props[$propName] = $val->$propName; - } - } - return $props; - } - - /** - * @internal - * @codeCoverageIgnore - * - * @return float|int - */ - protected function getRandomNumber( - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $maxDecimals = 4 - ) { - $min = 0; - $max = mt_getrandmax(); - - if ($minimum !== null) { - if (is_numeric($minimum) === false) { - throw new InvalidArgumentException('"minimum" must be a number'); - } - $min = $minimum; - } - - if ($maximum !== null) { - if (is_numeric($maximum) === false) { - throw new InvalidArgumentException('"maximum" must be a number'); - } - $max = $maximum; - } - - if ($exclusiveMinimum !== false) { - if (is_bool($exclusiveMinimum) === false) { - throw new InvalidArgumentException('"exclusiveMinimum" must be a boolean'); - } elseif ($minimum === null) { - throw new InvalidArgumentException('If "exclusiveMinimum" is present, "minimum" must also be present'); - } - $min += 1; - } - - if ($exclusiveMaximum !== false) { - if (is_bool($exclusiveMaximum) === false) { - throw new InvalidArgumentException('"exclusiveMaximum" must be a boolean'); - } elseif ($maximum === null) { - throw new InvalidArgumentException('If "exclusiveMaximum" is present, "maximum" must also be present'); - } - $max -= 1; - } - - if ($max < $min) { - throw new InvalidArgumentException('"maximum" value cannot be less than "minimum"'); - } - - if ($maxDecimals > 0) { - return round($min + mt_rand() / mt_getrandmax() * ($max - $min), $maxDecimals); - } - return mt_rand((int) $min, (int) $max); - } -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_interface.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_interface.mustache deleted file mode 100644 index 72920c76812..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_interface.mustache +++ /dev/null @@ -1,239 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{mockPackage}}; - -use InvalidArgumentException; - -/** - * {{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} Class Doc Comment - * - * @package {{mockPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - */ -interface {{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} -{ - /** @var string DATA_TYPE_INTEGER */ - public const DATA_TYPE_INTEGER = 'integer'; - - /** @var string DATA_TYPE_NUMBER */ - public const DATA_TYPE_NUMBER = 'number'; - - /** @var string DATA_TYPE_STRING */ - public const DATA_TYPE_STRING = 'string'; - - /** @var string DATA_TYPE_BOOLEAN */ - public const DATA_TYPE_BOOLEAN = 'boolean'; - - /** @var string DATA_TYPE_FILE */ - public const DATA_TYPE_FILE = 'file'; - - /** @var string DATA_TYPE_ARRAY */ - public const DATA_TYPE_ARRAY = 'array'; - - /** @var string DATA_TYPE_OBJECT */ - public const DATA_TYPE_OBJECT = 'object'; - - /** @var string DATA_FORMAT_INT32 Signed 32 bits */ - public const DATA_FORMAT_INT32 = 'int32'; - - /** @var string DATA_FORMAT_INT64 Signed 64 bits */ - public const DATA_FORMAT_INT64 = 'int64'; - - /** @var string DATA_FORMAT_FLOAT */ - public const DATA_FORMAT_FLOAT = 'float'; - - /** @var string DATA_FORMAT_DOUBLE */ - public const DATA_FORMAT_DOUBLE = 'double'; - - /** @var string DATA_FORMAT_BYTE base64 encoded characters */ - public const DATA_FORMAT_BYTE = 'byte'; - - /** @var string DATA_FORMAT_BINARY Any sequence of octets */ - public const DATA_FORMAT_BINARY = 'binary'; - - /** @var string DATA_FORMAT_DATE As defined by full-date [RFC3339](http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) */ - public const DATA_FORMAT_DATE = 'date'; - - /** @var string DATA_FORMAT_DATE_TIME As defined by date-time [RFC3339](http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) */ - public const DATA_FORMAT_DATE_TIME = 'date-time'; - - /** @var string DATA_FORMAT_PASSWORD Used to hint UIs the input needs to be obscured. */ - public const DATA_FORMAT_PASSWORD = 'password'; - - /** @var string DATA_FORMAT_EMAIL */ - public const DATA_FORMAT_EMAIL = 'email'; - - /** @var string DATA_FORMAT_UUID */ - public const DATA_FORMAT_UUID = 'uuid'; - - /** - * Mocks OpenApi Data. - * @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#data-types - * - * @param $dataType string OpenApi data type. Use constants from this class - * @param $dataFormat string (optional) OpenApi data format - * @param $options array|null (optional) OpenApi data options - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return mixed - */ - public function mock( - $dataType, - $dataFormat = null, - $options = [] - ); - - /** - * Shortcut to mock integer type - * Equivalent to mockData(DATA_TYPE_INTEGER); - * - * @param string|null $dataFormat (optional) int32 or int64 - * @param number|null $minimum (optional) Default is 0 - * @param number|null $maximum (optional) Default is mt_getrandmax() - * @param bool|null $exclusiveMinimum (optional) Default is false - * @param bool|null $exclusiveMaximum (optional) Default is false - * - * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided - * - * @return int - */ - public function mockInteger( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ); - - /** - * Shortcut to mock number type - * Equivalent to mockData(DATA_TYPE_NUMBER); - * - * @param string|null $dataFormat (optional) float or double - * @param number|null $minimum (optional) Default is 0 - * @param number|null $maximum (optional) Default is mt_getrandmax() - * @param bool|null $exclusiveMinimum (optional) Default is false - * @param bool|null $exclusiveMaximum (optional) Default is false - * - * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided - * - * @return float - */ - public function mockNumber( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ); - - /** - * Shortcut to mock string type - * Equivalent to mockData(DATA_TYPE_STRING); - * - * @param string|null $dataFormat (optional) one of byte, binary, date, date-time, password - * @param int|null $minLength (optional) Default is 0 - * @param int|null $maxLength (optional) Default is 100 chars - * @param array $enum (optional) This array should have at least one element. - * Elements in the array should be unique. - * @param string|null $pattern (optional) This string should be a valid regular expression, according to the ECMA 262 regular expression dialect. - * Recall: regular expressions are not implicitly anchored. - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return string - */ - public function mockString( - $dataFormat = null, - $minLength = 0, - $maxLength = null, - $enum = null, - $pattern = null - ); - - /** - * Shortcut to mock boolean type - * Equivalent to mockData(DATA_TYPE_BOOLEAN); - * - * @return bool - */ - public function mockBoolean(); - - /** - * Shortcut to mock array type - * Equivalent to mockData(DATA_TYPE_ARRAY); - * - * @param object|array $items Object or assoc array of described items - * @param int|null $minItems (optional) An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this keyword. - * @param int|null $maxItems (optional) An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword - * @param bool|null $uniqueItems (optional) If it has boolean value true, the instance validates successfully if all of its elements are unique - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return array - */ - public function mockArray( - $items, - $minItems = 0, - $maxItems = null, - $uniqueItems = false - ); - - /** - * Shortcut to mock object type. - * Equivalent to mockData(DATA_TYPE_OBJECT); - * - * @param object|array $properties Object or array of described properties - * @param int|null $minProperties (optional) An object instance is valid against "minProperties" if its number of properties is greater than, or equal to, the value of this keyword. - * @param int|null $maxProperties (optional) An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. - * @param bool|object|array|null $additionalProperties (optional) If "additionalProperties" is true, validation always succeeds. - * If "additionalProperties" is false, validation succeeds only if the instance is an object and all properties on the instance were covered by "properties" and/or "patternProperties". - * If "additionalProperties" is an object, validate the value as a schema to all of the properties that weren't validated by "properties" nor "patternProperties". - * @param array|null $required (optional) This array MUST have at least one element. Elements of this array must be strings, and MUST be unique. - * An object instance is valid if its property set contains all elements in this array value. - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return object - */ - public function mockObject( - $properties, - $minProperties = 0, - $maxProperties = null, - $additionalProperties = null, - $required = null - ); - - /** - * Mocks OpenApi Data from schema. - * - * @param array|object $schema OpenAPI schema - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return mixed - */ - public function mockFromSchema($schema); - - /** - * Mock data by referenced schema. - * TODO: this method will return model instance, not an StdClass - * - * @param string|null $ref Ref to model, eg. #/components/schemas/User - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return mixed - */ - public function mockFromRef($ref); -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware.mustache deleted file mode 100644 index d710ec6c24e..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware.mustache +++ /dev/null @@ -1,171 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{mockPackage}}; - -use Slim\Factory\AppFactory; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\ServerRequestInterface; -use Psr\Http\Server\MiddlewareInterface; -use Psr\Http\Server\RequestHandlerInterface; -use {{mockPackage}}\{{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}}; -use InvalidArgumentException; - -/** - * OpenApiDataMockerMiddleware Class Doc Comment - * - * @package {{mockPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - */ -final class OpenApiDataMockerMiddleware implements MiddlewareInterface -{ - /** - * @var {{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} DataMocker. - */ - private $mocker; - - /** - * @var array Array of responses schemas. - */ - private $responses; - - /** - * @var callable|null Custom callback to select mocked response. - */ - private $getMockResponseCallback; - - /** - * @var callable|null Custom after callback. - */ - private $afterCallback; - - /** - * Class constructor. - * - * @param {{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} $mocker DataMocker. - * @param array $responses Array of responses schemas. - * @param callable|null $getMockResponseCallback Custom callback to select mocked response. - * Mock feature is disabled when this argument is null. - * @example $getMockResponseCallback = function (ServerRequestInterface $request, array $responses) { - * // check if client clearly asks for mocked response - * if ( - * $request->hasHeader('X-{{invokerPackage}}-Mock') - * && $request->header('X-{{invokerPackage}}-Mock')[0] === 'ping' - * ) { - * return $responses[array_key_first($responses)]; - * } - * return false; - * }; - * @param callable|null $afterCallback After callback. - * Function must return response instance. - * @example $afterCallback = function (ServerRequestInterface $request, ResponseInterface $response) { - * // mark mocked response to distinguish real and fake responses - * return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong'); - * }; - */ - public function __construct( - {{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} $mocker, - array $responses, - $getMockResponseCallback = null, - $afterCallback = null - ) { - $this->mocker = $mocker; - $this->responses = $responses; - if (is_callable($getMockResponseCallback)) { - $this->getMockResponseCallback = $getMockResponseCallback; - } elseif ($getMockResponseCallback !== null) { - // wrong argument type - throw new InvalidArgumentException('\$getMockResponseCallback must be closure or null'); - } - - if (is_callable($afterCallback)) { - $this->afterCallback = $afterCallback; - } elseif ($afterCallback !== null) { - // wrong argument type - throw new InvalidArgumentException('\$afterCallback must be closure or null'); - } - } - - /** - * Parse incoming JSON input into a native PHP format - * - * @param ServerRequestInterface $request HTTP request - * @param RequestHandlerInterface $handler Request handler - * - * @return ResponseInterface HTTP response - */ - public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface - { - $customCallback = $this->getMockResponseCallback; - $customAfterCallback = $this->afterCallback; - $mockedResponse = (is_callable($customCallback)) ? $customCallback($request, $this->responses) : null; - if ( - is_array($mockedResponse) - && array_key_exists('code', $mockedResponse) - && array_key_exists('jsonSchema', $mockedResponse) - ) { - // response schema succesfully selected, we can mock it now - $statusCode = ($mockedResponse['code'] === 0) ? 200 : $mockedResponse['code']; - $contentType = '*/*'; - $response = AppFactory::determineResponseFactory()->createResponse($statusCode); - $responseSchema = json_decode($mockedResponse['jsonSchema'], true); - - if (is_array($responseSchema) && array_key_exists('headers', $responseSchema)) { - // response schema contains headers definitions, apply them one by one - foreach ($responseSchema['headers'] as $headerName => $headerDefinition) { - $response = $response->withHeader($headerName, $this->mocker->mockFromSchema($headerDefinition['schema'])); - } - } - - if ( - is_array($responseSchema) - && array_key_exists('content', $responseSchema) - && !empty($responseSchema['content']) - ) { - // response schema contains body definition - $responseContentSchema = null; - foreach ($responseSchema['content'] as $schemaContentType => $schemaDefinition) { - // we can respond in JSON format when any(*/*) content-type allowed - // or JSON(application/json) content-type specifically defined - if ( - $schemaContentType === '*/*' - || strtolower(substr($schemaContentType, 0, 16)) === 'application/json' - ) { - $contentType = 'application/json'; - $responseContentSchema = $schemaDefinition['schema']; - } - } - - if ($contentType === 'application/json') { - $responseBody = $this->mocker->mockFromSchema($responseContentSchema); - $response->getBody()->write(json_encode($responseBody)); - } else { - // notify developer that only application/json response supported so far - $response->getBody()->write('Mock feature supports only "application/json" content-type!'); - } - } - - // after callback applied only when mocked response schema has been selected - if (is_callable($customAfterCallback)) { - $response = $customAfterCallback($request, $response); - } - - // no reason to execute following middlewares (auth, validation etc.) - // return mocked response and end connection - return $response - ->withHeader('Content-Type', $contentType); - } - - // no response selected, mock feature disabled - // execute following middlewares - return $handler->handle($request); - } -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware_test.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware_test.mustache deleted file mode 100644 index b341a98ed4c..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_middleware_test.mustache +++ /dev/null @@ -1,258 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{mockPackage}}; - -use {{mockPackage}}\OpenApiDataMockerMiddleware; -use {{mockPackage}}\OpenApiDataMocker; -use Slim\Factory\AppFactory; -use Slim\Factory\ServerRequestCreatorFactory; -use Psr\Http\Message\ResponseInterface; -use Psr\Http\Message\ServerRequestInterface; -use Psr\Http\Server\RequestHandlerInterface; -use PHPUnit\Framework\TestCase; -use StdClass; - -/** - * OpenApiDataMockerMiddlewareTest Class Doc Comment - * - * @package {{mockPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - * @coversDefaultClass \{{mockPackage}}\OpenApiDataMockerMiddleware - */ -class OpenApiDataMockerMiddlewareTest extends TestCase -{ - /** - * @covers ::__construct - * @dataProvider provideConstructCorrectArguments - */ - public function testConstructor( - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback - ) { - $middleware = new OpenApiDataMockerMiddleware($mocker, $responses, $getMockResponseCallback, $afterCallback); - $this->assertInstanceOf(OpenApiDataMockerMiddleware::class, $middleware); - $this->assertNotNull($middleware); - } - - public function provideConstructCorrectArguments() - { - $getMockResponseCallback = function () { - return false; - }; - $afterCallback = function () { - return false; - }; - return [ - [new OpenApiDataMocker(), [], null, null], - [new OpenApiDataMocker(), [], $getMockResponseCallback, $afterCallback], - ]; - } - - /** - * @covers ::__construct - * @dataProvider provideConstructInvalidArguments - * @expectedException \InvalidArgumentException - * @expectedException \TypeError - */ - public function testConstructorWithInvalidArguments( - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback - ) { - $middleware = new OpenApiDataMockerMiddleware($mocker, $responses, $getMockResponseCallback, $afterCallback); - } - - public function provideConstructInvalidArguments() - { - return [ - 'getMockResponseCallback not callable' => [ - new OpenApiDataMocker(), [], 'foobar', null, - ], - 'afterCallback not callable' => [ - new OpenApiDataMocker(), [], null, 'foobar', - ], - ]; - } - - /** - * @covers ::process - * @dataProvider provideProcessArguments - */ - public function testProcess( - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback, - $request, - $expectedStatusCode, - $expectedHeaders, - $notExpectedHeaders, - $expectedBody - ) { - - // Create a stub for the RequestHandlerInterface interface. - $handler = $this->createMock(RequestHandlerInterface::class); - $handler->method('handle') - ->willReturn(AppFactory::determineResponseFactory()->createResponse()); - - $middleware = new OpenApiDataMockerMiddleware( - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback - ); - $response = $middleware->process($request, $handler); - - // check status code - $this->assertSame($expectedStatusCode, $response->getStatusCode()); - - // check http headers in request - foreach ($expectedHeaders as $expectedHeader => $expectedHeaderValue) { - $this->assertTrue($response->hasHeader($expectedHeader)); - if ($expectedHeaderValue !== '*') { - $this->assertSame($expectedHeaderValue, $response->getHeader($expectedHeader)[0]); - } - } - foreach ($notExpectedHeaders as $notExpectedHeader) { - $this->assertFalse($response->hasHeader($notExpectedHeader)); - } - - // check body - if (is_array($expectedBody)) { - // random values, check keys only - foreach ($expectedBody as $attribute => $value) { - $this->assertObjectHasAttribute($attribute, json_decode((string) $response->getBody(), false)); - } - } else { - $this->assertEquals($expectedBody, (string) $response->getBody()); - } - } - - public function provideProcessArguments() - { - $mocker = new OpenApiDataMocker(); - $isMockResponseRequired = function (ServerRequestInterface $request) { - $mockHttpHeader = 'X-{{invokerPackage}}-Mock'; - return $request->hasHeader($mockHttpHeader) - && $request->getHeader($mockHttpHeader)[0] === 'ping'; - }; - - $getMockResponseCallback = function (ServerRequestInterface $request, array $responses) use ($isMockResponseRequired) { - if ($isMockResponseRequired($request)) { - if (array_key_exists('default', $responses)) { - return $responses['default']; - } - - // return first response - return $responses[array_key_first($responses)]; - } - - return false; - }; - - $afterCallback = function ($request, $response) use ($isMockResponseRequired) { - if ($isMockResponseRequired($request)) { - $response = $response->withHeader('X-{{invokerPackage}}-Mock', 'pong'); - } - - return $response; - }; - - $responses = [ - '400' => [ - 'code' => 400, - 'jsonSchema' => json_encode([ - 'description' => 'Bad Request Response', - 'content' => new StdClass(), - ]), - ], - 'default' => [ - 'code' => 201, - 'jsonSchema' => json_encode([ - 'description' => 'Success Response', - 'headers' => [ - 'X-Location' => ['schema' => ['type' => 'string']], - 'X-Created-Id' => ['schema' => ['type' => 'integer']], - ], - 'content' => [ - 'application/json;encoding=utf-8' => ['schema' => ['type' => 'object', 'properties' => ['id' => ['type' => 'integer'], 'className' => ['type' => 'string'], 'declawed' => ['type' => 'boolean']]]], - ], - ]), - ], - ]; - - $responsesXmlOnly = [ - 'default' => [ - 'code' => 201, - 'jsonSchema' => json_encode([ - 'description' => 'Success Response', - 'content' => [ - 'application/xml' => [ - 'schema' => [ - 'type' => 'string', - ], - ], - ], - ]), - ], - ]; - - $requestFactory = ServerRequestCreatorFactory::create(); - - return [ - 'callbacks null' => [ - $mocker, - $responses, - null, - null, - $requestFactory->createServerRequestFromGlobals(), - 200, - [], - ['X-{{invokerPackage}}-Mock', 'x-location', 'x-created-id'], - '', - ], - 'xml not supported' => [ - $mocker, - $responsesXmlOnly, - $getMockResponseCallback, - $afterCallback, - $requestFactory - ->createServerRequestFromGlobals() - ->withHeader('X-{{invokerPackage}}-Mock', 'ping'), - 201, - ['X-{{invokerPackage}}-Mock' => 'pong', 'content-type' => '*/*'], - ['x-location', 'x-created-id'], - 'Mock feature supports only "application/json" content-type!', - ], - 'mock response default schema' => [ - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback, - $requestFactory - ->createServerRequestFromGlobals() - ->withHeader('X-{{invokerPackage}}-Mock', 'ping'), - 201, - ['X-{{invokerPackage}}-Mock' => 'pong', 'content-type' => 'application/json', 'x-location' => '*', 'x-created-id' => '*'], - [], - [ - 'id' => 1, - 'className' => 'cat', - 'declawed' => false, - ], - ], - ]; - } -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_test.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_test.mustache deleted file mode 100644 index 51e50bc16f2..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/openapi_data_mocker_test.mustache +++ /dev/null @@ -1,1233 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{mockPackage}}; - -use {{mockPackage}}\OpenApiDataMocker; -use {{mockPackage}}\{{interfaceNamePrefix}}OpenApiDataMocker{{interfaceNameSuffix}} as IMocker; -use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\Constraint\IsType; -use StdClass; -use DateTime; - -/** - * OpenApiDataMockerTest Class Doc Comment - * - * @package {{mockPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - * @coversDefaultClass \{{mockPackage}}\OpenApiDataMocker - */ -class OpenApiDataMockerTest extends TestCase -{ - /** - * @covers ::mock - * @dataProvider provideMockCorrectArguments - */ - public function testMockCorrectArguments($dataType, $dataFormat, $options, $expectedType) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mock($dataType, $dataFormat, $options); - $this->assertInternalType($expectedType, $data); - } - - public function provideMockCorrectArguments() - { - return [ - [IMocker::DATA_TYPE_INTEGER, null, null, IsType::TYPE_INT], - [IMocker::DATA_TYPE_NUMBER, null, null, IsType::TYPE_FLOAT], - [IMocker::DATA_TYPE_STRING, null, null, IsType::TYPE_STRING], - [IMocker::DATA_TYPE_BOOLEAN, null, null, IsType::TYPE_BOOL], - [IMocker::DATA_TYPE_ARRAY, null, [ - 'items' => [ - 'type' => IMocker::DATA_TYPE_INTEGER, - ], - ], IsType::TYPE_ARRAY], - [IMocker::DATA_TYPE_OBJECT, null, [ - 'properties' => [ - 'username' => [ - 'type' => IMocker::DATA_TYPE_INTEGER, - ], - ], - ], IsType::TYPE_OBJECT], - ]; - } - - /** - * @covers ::mock - * @dataProvider provideMockInvalidArguments - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage "dataType" must be one of integer, number, string, boolean, array, object - */ - public function testMockInvalidArguments($dataType, $dataFormat, $options) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mock($dataType, $dataFormat, $options); - } - - public function provideMockInvalidArguments() - { - return [ - ['foobar', null, null], - [3.14, null, null], - [null, null, null], - ]; - } - - /** - * @covers ::mock - */ - public function testMockWithStringEnumOptions() - { - $mocker = new OpenApiDataMocker(); - $string = $mocker->mock(IMocker::DATA_TYPE_STRING, null, [ - 'enum' => ['foobar', 'foobaz', 'helloworld'], - ]); - $this->assertContains($string, ['foobar', 'foobaz', 'helloworld']); - } - - /** - * @dataProvider provideMockIntegerCorrectArguments - * @covers ::mockInteger - */ - public function testMockIntegerWithCorrectArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - $mocker = new OpenApiDataMocker(); - $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - - $this->internalAssertNumber( - $integer, - $minimum, - $maximum, - $exclusiveMinimum, - $exclusiveMaximum, - $matchingInternalTypes, - $notMatchingInternalTypes - ); - } - - public function provideMockIntegerCorrectArguments() - { - $types = [ - IsType::TYPE_INT, - IsType::TYPE_NUMERIC, - IsType::TYPE_SCALAR, - ]; - $notTypes = [ - IsType::TYPE_ARRAY, - IsType::TYPE_BOOL, - IsType::TYPE_FLOAT, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_STRING, - IsType::TYPE_CALLABLE, - ]; - - return [ - [null, -100, 100, false, false, $types, $notTypes], - [null, -100, null, false, false, $types, $notTypes], - [null, null, 100, false, false, $types, $notTypes], - [null, -99.5, null, true, false, $types, $notTypes], - [null, null, 99.5, false, true, $types, $notTypes], - [null, -99.5, 99.5, true, true, $types, $notTypes], - ]; - } - - /** - * @dataProvider provideMockIntegerInvalidArguments - * @covers ::mockInteger - * @expectedException \InvalidArgumentException - */ - public function testMockIntegerWithInvalidArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - $mocker = new OpenApiDataMocker(); - $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - } - - public function provideMockIntegerInvalidArguments() - { - return [ - [null, 'foo', null, false, false], - [null, null, false, false, false], - [null, null, null, true, false], - [null, null, null, false, true], - [null, 100, -100, false, false], - ]; - } - - /** - * @covers ::mockInteger - * @dataProvider provideMockIntegerFormats - */ - public function testMockIntegerWithFormats( - $dataFormat, - $minimum, - $maximum, - $expectedMin, - $expectedMax - ) { - $mocker = new OpenApiDataMocker(); - $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum); - $this->assertGreaterThanOrEqual($expectedMin, $integer); - $this->assertLessThanOrEqual($expectedMax, $integer); - } - - public function provideMockIntegerFormats() - { - return [ - [IMocker::DATA_FORMAT_INT32, -2147483648, 2147483648, -2147483647, 2147483647], - [IMocker::DATA_FORMAT_INT64, '-9223372036854775808', '9223372036854775808', -9223372036854775807, 9223372036854775807], - [IMocker::DATA_FORMAT_INT32, -10, 10, -10, 10], - [IMocker::DATA_FORMAT_INT64, -10, 10, -10, 10], - [IMocker::DATA_FORMAT_INT32, -9223372036854775807, 9223372036854775807, -2147483647, 2147483647], - [strtoupper(IMocker::DATA_FORMAT_INT32), -2147483648, 2147483648, -2147483647, 2147483647], - [strtoupper(IMocker::DATA_FORMAT_INT64), '-9223372036854775808', '9223372036854775808', -9223372036854775807, 9223372036854775807], - ]; - } - - /** - * @dataProvider provideMockNumberCorrectArguments - * @covers ::mockNumber - */ - public function testMockNumberWithCorrectArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - $mocker = new OpenApiDataMocker(); - $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - - $this->internalAssertNumber( - $number, - $minimum, - $maximum, - $exclusiveMinimum, - $exclusiveMaximum, - $matchingInternalTypes, - $notMatchingInternalTypes - ); - } - - public function provideMockNumberCorrectArguments() - { - $types = [ - IsType::TYPE_SCALAR, - IsType::TYPE_NUMERIC, - IsType::TYPE_FLOAT, - ]; - $notTypes = [ - IsType::TYPE_INT, - IsType::TYPE_ARRAY, - IsType::TYPE_BOOL, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_STRING, - IsType::TYPE_CALLABLE, - ]; - - return [ - [null, -100, 100, false, false, $types, $notTypes], - [null, -100, null, false, false, $types, $notTypes], - [null, null, 100, false, false, $types, $notTypes], - [null, -99.5, null, true, false, $types, $notTypes], - [null, null, 99.5, false, true, $types, $notTypes], - [null, -99.5, 99.5, true, true, $types, $notTypes], - ]; - } - - /** - * @dataProvider provideMockNumberInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockNumber - */ - public function testMockNumberWithInvalidArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - $mocker = new OpenApiDataMocker(); - $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - } - - public function provideMockNumberInvalidArguments() - { - return [ - [null, 'foo', null, false, false], - [null, null, false, false, false], - [null, null, null, true, false], - [null, null, null, false, true], - [null, 100, -100, false, false], - ]; - } - - /** - * @dataProvider provideMockStringCorrectArguments - * @covers ::mockString - */ - public function testMockStringWithCorrectArguments( - $dataFormat = null, - $minLength = 0, - $maxLength = null, - $enum = null, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); - - $this->internalAssertString( - $str, - $minLength, - $maxLength, - $enum, - $matchingInternalTypes, - $notMatchingInternalTypes - ); - } - - public function provideMockStringCorrectArguments() - { - $types = [ - IsType::TYPE_SCALAR, - IsType::TYPE_STRING, - ]; - $notTypes = [ - IsType::TYPE_FLOAT, - IsType::TYPE_INT, - IsType::TYPE_ARRAY, - IsType::TYPE_BOOL, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_CALLABLE, - ]; - - return [ - [null, 0, null, null, $types, $notTypes], - [null, 10, null, null, $types, $notTypes], - [null, 0, 100, null, $types, $notTypes], - [null, 10, 50, null, $types, $notTypes], - [null, 10, 10, null, $types, $notTypes], - [null, 0, 0, null, $types, $notTypes], - [null, null, null, null, $types, $notTypes], - [null, null, null, ['foobar', 'foobaz', 'hello world'], $types, $notTypes], - [null, null, null, ['foobar'], $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 0, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 10, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 0, 100, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 10, 50, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 10, 10, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 0, 0, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, null, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 10, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 10, 10, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, null, 8, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 16, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 25, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 25, 25, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, null, 20, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 30, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 1, 1, null, $types, $notTypes], - ]; - } - - /** - * @dataProvider provideMockStringInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockString - */ - public function testMockStringWithInvalidArguments( - $dataFormat = null, - $minLength = 0, - $maxLength = null, - $enum = null - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); - } - - public function provideMockStringInvalidArguments() - { - return [ - 'negative minLength' => [null, -10, null], - 'negative maxLength' => [null, 0, -10], - 'both minLength maxLength negative' => [null, -10, -10], - 'decimal minLength and maxLength' => [null, 0.5, 0.5], - 'string minLength' => [null, '10', null], - 'string maxLength' => [null, 0, '50'], - 'string minLength and maxLength' => [null, '10', '50'], - 'maxLength less than minLength' => [null, 50, 10], - 'enum is string' => [null, null, null, 'foobar'], - 'enum is empty array' => [null, null, null, []], - 'enum array is not unique' => [null, null, null, ['foobar', 'foobaz', 'foobar']], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringByteFormatArguments - */ - public function testMockStringWithByteFormat( - $dataFormat, - $minLength, - $maxLength - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, $dataFormat, ['minLength' => $minLength, 'maxLength' => $maxLength]); - $base64pattern = '/^[\w\+\/\=]*$/'; - $this->assertRegExp($base64pattern, $str); - $this->assertRegExp($base64pattern, $str2); - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str)); - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str)); - $this->assertLessThanOrEqual($maxLength, mb_strlen($str2)); - } - } - - public function provideMockStringByteFormatArguments() - { - return [ - [IMocker::DATA_FORMAT_BYTE, null, null], - [IMocker::DATA_FORMAT_BYTE, 10, null], - [IMocker::DATA_FORMAT_BYTE, 10, 10], - [IMocker::DATA_FORMAT_BYTE, null, 12], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringBinaryFormatArguments - */ - public function testMockStringWithBinaryFormat( - $dataFormat, - $minLength, - $maxLength - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, $dataFormat, ['minLength' => $minLength, 'maxLength' => $maxLength]); - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, strlen($str)); - $this->assertGreaterThanOrEqual($minLength, strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, strlen($str)); - $this->assertLessThanOrEqual($maxLength, strlen($str2)); - } - } - - public function provideMockStringBinaryFormatArguments() - { - return [ - [IMocker::DATA_FORMAT_BINARY, 0, null], - [IMocker::DATA_FORMAT_BINARY, 10, null], - [IMocker::DATA_FORMAT_BINARY, 0, 100], - [IMocker::DATA_FORMAT_BINARY, 10, 50], - [IMocker::DATA_FORMAT_BINARY, 10, 10], - [IMocker::DATA_FORMAT_BINARY, 0, 0], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringDateFormatArguments - */ - public function testMockStringWithDateAndDateTimeFormat( - $dataFormat, - $minLength, - $maxLength, - $dtFormat - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, $dataFormat, ['minLength' => $minLength, 'maxLength' => $maxLength]); - - if ($dtFormat !== null) { - $date = DateTime::createFromFormat($dtFormat, $str); - $date2 = DateTime::createFromFormat($dtFormat, $str2); - $this->assertInstanceOf(DateTime::class, $date); - $this->assertInstanceOf(DateTime::class, $date2); - } - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str)); - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str)); - $this->assertLessThanOrEqual($maxLength, mb_strlen($str2)); - } - } - - public function provideMockStringDateFormatArguments() - { - return [ - [IMocker::DATA_FORMAT_DATE, null, null, 'Y-m-d'], - [IMocker::DATA_FORMAT_DATE, 10, null, 'Y-m-d'], - [IMocker::DATA_FORMAT_DATE, 10, 10, 'Y-m-d'], - [IMocker::DATA_FORMAT_DATE, null, 8, null], - [IMocker::DATA_FORMAT_DATE, 16, null, null], - [IMocker::DATA_FORMAT_DATE_TIME, null, null, 'Y-m-d\TH:i:sP'], - [IMocker::DATA_FORMAT_DATE_TIME, 25, null, 'Y-m-d\TH:i:sP'], - [IMocker::DATA_FORMAT_DATE_TIME, 25, 25, 'Y-m-d\TH:i:sP'], - [IMocker::DATA_FORMAT_DATE_TIME, null, 20, null], - [IMocker::DATA_FORMAT_DATE_TIME, 30, null, null], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringUuidFormatArguments - */ - public function testMockStringWithUuidFormat( - $minLength, - $maxLength - ) { - $mocker = new OpenApiDataMocker(); - $arr = []; - $arr2 = []; - $hexPattern = '/^[a-f0-9]*$/'; - - while (count($arr) < 100 && count($arr2) < 100) { - $str = $mocker->mockString(IMocker::DATA_FORMAT_UUID, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, IMocker::DATA_FORMAT_UUID, ['minLength' => $minLength, 'maxLength' => $maxLength]); - $arr[] = $str; - $arr2[] = $str2; - - $this->assertRegExp($hexPattern, $str); - $this->assertRegExp($hexPattern, $str2); - - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str)); - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str)); - $this->assertLessThanOrEqual($maxLength, mb_strlen($str2)); - } - } - } - - public function provideMockStringUuidFormatArguments() - { - return [ - [null, null], - [10, null], - [10, 10], - [null, 8], - [16, null], - [null, null], - [25, null], - [25, 25], - [null, 20], - [30, null], - [1, 1], - ]; - } - - /** - * @covers ::mockBoolean - */ - public function testMockBoolean() - { - $mocker = new OpenApiDataMocker(); - $bool = $mocker->mockBoolean(); - - $matchingInternalTypes = [ - IsType::TYPE_SCALAR, - IsType::TYPE_BOOL, - ]; - - foreach ($matchingInternalTypes as $matchType) { - $this->assertInternalType($matchType, $bool); - } - - $notMatchingInternalTypes = [ - IsType::TYPE_NUMERIC, - IsType::TYPE_FLOAT, - IsType::TYPE_INT, - IsType::TYPE_ARRAY, - IsType::TYPE_STRING, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_CALLABLE, - ]; - - foreach ($notMatchingInternalTypes as $notMatchType) { - $this->assertNotInternalType($notMatchType, $bool); - } - } - - private function internalAssertNumber( - $number, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - foreach ($matchingInternalTypes as $matchType) { - $this->assertInternalType($matchType, $number); - } - - foreach ($notMatchingInternalTypes as $notMatchType) { - $this->assertNotInternalType($notMatchType, $number); - } - - if ($minimum !== null) { - if ($exclusiveMinimum) { - $this->assertGreaterThan($minimum, $number); - } else { - $this->assertGreaterThanOrEqual($minimum, $number); - } - } - - if ($maximum !== null) { - if ($exclusiveMaximum) { - $this->assertLessThan($maximum, $number); - } else { - $this->assertLessThanOrEqual($maximum, $number); - } - } - } - - private function internalAssertString( - $str, - $minLength = null, - $maxLength = null, - $enum = null, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - foreach ($matchingInternalTypes as $matchType) { - $this->assertInternalType($matchType, $str); - } - - foreach ($notMatchingInternalTypes as $notMatchType) { - $this->assertNotInternalType($notMatchType, $str); - } - - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str, 'UTF-8')); - } - - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str, 'UTF-8')); - } - - if (is_array($enum) && !empty($enum)) { - $this->assertContains($str, $enum); - } - } - - /** - * @dataProvider provideMockArrayCorrectArguments - * @covers ::mockArray - */ - public function testMockArrayFlattenWithCorrectArguments( - $items, - $minItems, - $maxItems, - $uniqueItems, - $expectedItemsType = null, - $expectedArraySize = null - ) { - $mocker = new OpenApiDataMocker(); - $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); - - $this->assertIsArray($arr); - if ($expectedArraySize !== null) { - $this->assertCount($expectedArraySize, $arr); - } - if ($expectedItemsType && $expectedArraySize > 0) { - $this->assertContainsOnly($expectedItemsType, $arr, true); - } - - if (is_array($items)) { - $dataType = $items['type']; - $dataFormat = $items['dataFormat'] ?? null; - - // items field numeric properties - $minimum = $items['minimum'] ?? null; - $maximum = $items['maximum'] ?? null; - $exclusiveMinimum = $items['exclusiveMinimum'] ?? null; - $exclusiveMaximum = $items['exclusiveMaximum'] ?? null; - - // items field string properties - $minLength = $items['minLength'] ?? null; - $maxLength = $items['maxLength'] ?? null; - $enum = $items['enum'] ?? null; - $pattern = $items['pattern'] ?? null; - - // items field array properties - $subItems = $items['items'] ?? null; - $subMinItems = $items['minItems'] ?? null; - $subMaxItems = $items['maxItems'] ?? null; - $subUniqueItems = $items['uniqueItems'] ?? null; - } else { - // is object - $dataType = $items->type; - $dataFormat = $items->dataFormat ?? null; - - // items field numeric properties - $minimum = $items->minimum ?? null; - $maximum = $items->maximum ?? null; - $exclusiveMinimum = $items->exclusiveMinimum ?? null; - $exclusiveMaximum = $items->exclusiveMaximum ?? null; - - // items field string properties - $minLength = $items->minLength ?? null; - $maxLength = $items->maxLength ?? null; - $enum = $items->enum ?? null; - $pattern = $items->pattern ?? null; - - // items field array properties - $subItems = $items->items ?? null; - $subMinItems = $items->minItems ?? null; - $subMaxItems = $items->maxItems ?? null; - $subUniqueItems = $items->uniqueItems ?? null; - } - - - foreach ($arr as $item) { - switch ($dataType) { - case IMocker::DATA_TYPE_INTEGER: - $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - break; - case IMocker::DATA_TYPE_NUMBER: - $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - break; - case IMocker::DATA_TYPE_STRING: - $this->internalAssertString($item, $minLength, $maxLength); - break; - case IMocker::DATA_TYPE_BOOLEAN: - $this->assertInternalType(IsType::TYPE_BOOL, $item); - break; - case IMocker::DATA_TYPE_ARRAY: - $this->testMockArrayFlattenWithCorrectArguments($subItems, $subMinItems, $subMaxItems, $subUniqueItems); - break; - } - } - } - - public function provideMockArrayCorrectArguments() - { - $intItems = ['type' => IMocker::DATA_TYPE_INTEGER, 'minimum' => 5, 'maximum' => 10]; - $floatItems = ['type' => IMocker::DATA_TYPE_NUMBER, 'minimum' => -32.4, 'maximum' => 88.6, 'exclusiveMinimum' => true, 'exclusiveMaximum' => true]; - $strItems = ['type' => IMocker::DATA_TYPE_STRING, 'minLength' => 20, 'maxLength' => 50]; - $boolItems = (object) ['type' => IMocker::DATA_TYPE_BOOLEAN]; - $arrayItems = (object) ['type' => IMocker::DATA_TYPE_ARRAY, 'items' => ['type' => IMocker::DATA_TYPE_STRING, 'minItems' => 3, 'maxItems' => 10]]; - $objectItems = (object) ['type' => IMocker::DATA_TYPE_OBJECT, 'properties' => (object)['username' => ['type' => IMocker::DATA_TYPE_STRING]]]; - $expectedInt = IsType::TYPE_INT; - $expectedFloat = IsType::TYPE_FLOAT; - $expectedStr = IsType::TYPE_STRING; - $expectedBool = IsType::TYPE_BOOL; - $expectedArray = IsType::TYPE_ARRAY; - $expectedObject = IsType::TYPE_OBJECT; - - return [ - 'empty array' => [ - $strItems, null, 0, false, null, 0, - ], - 'empty array, limit zero' => [ - $strItems, 0, 0, false, null, 0, - ], - 'array of one string as default size' => [ - $strItems, null, null, false, $expectedStr, 1, - ], - 'array of one string, limit one' => [ - $strItems, 1, 1, false, $expectedStr, 1, - ], - 'array of two strings' => [ - $strItems, 2, null, false, $expectedStr, 2, - ], - 'array of five strings, limit ten' => [ - $strItems, 5, 10, false, $expectedStr, 5, - ], - 'array of five strings, limit five' => [ - $strItems, 5, 5, false, $expectedStr, 5, - ], - 'array of one string, limit five' => [ - $strItems, null, 5, false, $expectedStr, 1, - ], - 'array of one integer' => [ - $intItems, null, null, false, $expectedInt, 1, - ], - 'array of one float' => [ - $floatItems, null, null, false, $expectedFloat, 1, - ], - 'array of one boolean' => [ - $boolItems, null, null, false, $expectedBool, 1, - ], - 'array of one array of strings' => [ - $arrayItems, null, null, false, $expectedArray, 1, - ], - 'array of one object' => [ - $objectItems, null, null, false, $expectedObject, 1 - ], - ]; - } - - /** - * @dataProvider provideMockArrayInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockArray - */ - public function testMockArrayWithInvalidArguments( - $items, - $minItems, - $maxItems, - $uniqueItems - ) { - $mocker = new OpenApiDataMocker(); - $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); - } - - public function provideMockArrayInvalidArguments() - { - $intItems = ['type' => IMocker::DATA_TYPE_INTEGER]; - - return [ - 'items is nor array' => [ - 'foobar', null, null, false, - ], - 'items doesnt have "type" key' => [ - ['foobar' => 'foobaz'], null, null, false, - ], - 'minItems is not integer' => [ - $intItems, 3.12, null, false, - ], - 'minItems is negative' => [ - $intItems, -10, null, false, - ], - 'minItems is not number' => [ - $intItems, '1', null, false, - ], - 'maxItems is not integer' => [ - $intItems, null, 3.12, false, - ], - 'maxItems is negative' => [ - $intItems, null, -10, false, - ], - 'maxItems is not number' => [ - $intItems, null, 'foobaz', false, - ], - 'maxItems less than minItems' => [ - $intItems, 5, 2, false, - ], - 'items with ref to unknown class' => [ - ['$ref' => '#/components/schemas/UnknownClass'], null, null, false, - ], - 'items with ref to class without getOpenApiSchema method' => [ - ['$ref' => '#/components/schemas/ClassWithoutGetSchemaMethod'], null, null, false, - ], - ]; - } - - /** - * @dataProvider provideMockArrayWithRefArguments - * @covers ::mockArray - */ - public function testMockArrayWithRef($items, $expectedStructure) - { - $mocker = new OpenApiDataMocker(); - $arr = $mocker->mockArray($items); - $this->assertIsArray($arr); - $this->assertCount(1, $arr); - foreach ($arr as $item) { - // TODO: replace with assertInstanceOf assertion - $this->assertInternalType(IsType::TYPE_OBJECT, $item); - foreach ($expectedStructure as $expectedProp => $expectedType) { - $this->assertInternalType($expectedType, $item->$expectedProp); - } - } - } - - public function provideMockArrayWithRefArguments() - { - return [ - 'items with ref to CatRefTestClass' => [ - ['$ref' => '#/components/schemas/CatRefTestClass'], - [ - 'className' => IsType::TYPE_STRING, - 'color' => IsType::TYPE_STRING, - 'declawed' => IsType::TYPE_BOOL, - ], - ], - ]; - } - - /** - * @dataProvider provideMockObjectCorrectArguments - * @covers ::mockObject - */ - public function testMockObjectWithCorrectArguments( - $properties, - $minProperties, - $maxProperties, - $additionalProperties, - $required, - $expectedKeys - ) { - $mocker = new OpenApiDataMocker(); - $obj = $mocker->mockObject( - $properties, - $minProperties, - $maxProperties, - $additionalProperties, - $required - ); - - $this->assertInternalType(IsType::TYPE_OBJECT, $obj); - $this->assertSame($expectedKeys, array_keys(get_object_vars($obj))); - } - - public function provideMockObjectCorrectArguments() - { - $additionProps = [ - 'extra' => [ - 'type' => IMocker::DATA_TYPE_STRING, - ], - ]; - return [ - 'empty object' => [ - [], 1, 10, true, null, [], - ], - 'empty object from StdClass' => [ - new StdClass(), 1, 5, false, null, [], - ], - 'object with username property' => [ - [ - 'username' => [ - 'type' => IMocker::DATA_TYPE_STRING, - ], - ], 0, 5, $additionProps, null, ['username'], - ], - 'object with foobar property' => [ - (object) [ - 'foobar' => [ - 'type' => IMocker::DATA_TYPE_INTEGER, - ], - ], 1, 1, (object) $additionProps, null, ['foobar'], - ], - ]; - } - - /** - * @dataProvider provideMockObjectInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockObject - */ - public function testMockObjectWithInvalidArguments( - $properties, - $minProperties, - $maxProperties, - $additionalProperties, - $required - ) { - $mocker = new OpenApiDataMocker(); - $obj = $mocker->mockObject($properties, $minProperties, $maxProperties, $additionalProperties, $required); - } - - public function provideMockObjectInvalidArguments() - { - return [ - 'properties cannot be null' => [ - null, 0, 10, false, null, - ], - 'properties cannot be a string' => [ - 'foobar', 0, 10, false, null, - ], - 'property value cannot be a string' => [ - ['username' => 'foobar'], 0, 10, false, null, - ], - 'minProperties is not integer' => [ - [], 3.12, null, false, null, - ], - 'minProperties is negative' => [ - [], -10, null, false, null, - ], - 'minProperties is not number' => [ - [], '1', null, false, null, - ], - 'maxProperties is not integer' => [ - [], null, 3.12, false, null, - ], - 'maxProperties is negative' => [ - [], null, -10, false, null, - ], - 'maxProperties is not number' => [ - [], null, 'foobaz', false, null, - ], - 'maxProperties less than minProperties' => [ - [], 5, 2, false, null, - ], - 'additionalProperties is not object|array|boolean' => [ - [], null, null, 'foobar', null, - ], - 'required is object, not array' => [ - [], null, null, null, new StdClass(), - ], - 'required is not array' => [ - [], null, null, null, 'foobar', - ], - 'required array with duplicates' => [ - [], null, null, null, ['username', 'username'], - ], - 'required array of non-strings' => [ - [], null, null, null, [1, 2, 3], - ], - ]; - } - - /** - * @covers ::mockObject - */ - public function testMockObjectWithReferencedProps() - { - $mocker = new OpenApiDataMocker(); - $obj = $mocker->mockObject( - (object) [ - 'cat' => [ - '$ref' => '#/components/schemas/CatRefTestClass', - ], - ] - ); - $this->assertInternalType(IsType::TYPE_OBJECT, $obj->cat); - $this->assertInternalType(IsType::TYPE_STRING, $obj->cat->className); - $this->assertInternalType(IsType::TYPE_STRING, $obj->cat->color); - $this->assertInternalType(IsType::TYPE_BOOL, $obj->cat->declawed); - } - - /** - * @dataProvider provideMockFromSchemaCorrectArguments - * @covers ::mockFromSchema - */ - public function testMockFromSchemaWithCorrectArguments($schema, $expectedType) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromSchema($schema); - $this->assertInternalType($expectedType, $data); - } - - public function provideMockFromSchemaCorrectArguments() - { - return [ - 'string from object' => [ - (object) ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'string from array' => [ - ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'integer from object' => [ - (object) ['type' => IMocker::DATA_TYPE_INTEGER], - IsType::TYPE_INT, - ], - 'integer from array' => [ - ['type' => IMocker::DATA_TYPE_INTEGER], - IsType::TYPE_INT, - ], - 'number from object' => [ - (object) ['type' => IMocker::DATA_TYPE_NUMBER], - IsType::TYPE_FLOAT, - ], - 'number from array' => [ - ['type' => IMocker::DATA_TYPE_NUMBER], - IsType::TYPE_FLOAT, - ], - 'string from object' => [ - (object) ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'string from array' => [ - ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'boolean from object' => [ - (object) ['type' => IMocker::DATA_TYPE_BOOLEAN], - IsType::TYPE_BOOL, - ], - 'boolean from array' => [ - ['type' => IMocker::DATA_TYPE_BOOLEAN], - IsType::TYPE_BOOL, - ], - 'array of strings from object' => [ - (object) [ - 'type' => IMocker::DATA_TYPE_ARRAY, - 'items' => ['type' => IMocker::DATA_TYPE_STRING], - ], - IsType::TYPE_ARRAY, - ], - 'array of strings from array' => [ - [ - 'type' => IMocker::DATA_TYPE_ARRAY, - 'items' => ['type' => IMocker::DATA_TYPE_STRING], - ], - IsType::TYPE_ARRAY, - ], - 'object with username prop from object' => [ - (object) [ - 'type' => IMocker::DATA_TYPE_OBJECT, - 'properties' => ['username' => ['type' => IMocker::DATA_TYPE_STRING]], - ], - IsType::TYPE_OBJECT, - ], - 'object with username prop from array' => [ - [ - 'type' => IMocker::DATA_TYPE_OBJECT, - 'properties' => ['username' => ['type' => IMocker::DATA_TYPE_STRING]], - ], - IsType::TYPE_OBJECT, - ], - 'referenced class' => [ - ['$ref' => '#/components/schemas/CatRefTestClass'], - IsType::TYPE_OBJECT, - ], - ]; - } - - /** - * @dataProvider provideMockFromSchemaInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockFromSchema - */ - public function testMockFromSchemaWithInvalidArguments($schema) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromSchema($schema); - } - - - public function provideMockFromSchemaInvalidArguments() - { - return [ - 'null' => [null], - 'numeric' => [3.14], - 'empty array' => [[]], - 'empty object' => [(object) []], - 'string' => ['foobar'], - 'DateTime object' => [new DateTime()], - ]; - } - - /** - * @dataProvider provideMockFromRefCorrectArguments - * @covers ::mockFromRef - */ - public function testMockFromRefWithCorrectArguments($ref, $expectedStructure) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromRef($ref); - foreach ($expectedStructure as $expectedProp => $expectedType) { - $this->assertInternalType($expectedType, $data->$expectedProp); - } - } - - public function provideMockFromRefCorrectArguments() - { - return [ - 'CatRefTestClass model' => [ - '#/components/schemas/CatRefTestClass', - [ - 'className' => IsType::TYPE_STRING, - 'color' => IsType::TYPE_STRING, - 'declawed' => IsType::TYPE_BOOL, - ] - ], - ]; - } - - /** - * @dataProvider provideMockFromRefInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockFromRef - */ - public function testMockFromRefWithInvalidArguments($ref) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromRef($ref); - } - - public function provideMockFromRefInvalidArguments() - { - return [ - 'ref to unknown class' => ['#/components/schemas/UnknownClass'], - 'ref to class without getOpenApiSchema method' => ['#/components/schemas/ClassWithoutGetSchemaMethod'], - ]; - } -} - -namespace {{modelPackage}}; - -// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses -final class CatRefTestClass -{ - private const MODEL_SCHEMA = <<<'SCHEMA' -{ - "required" : [ "className" ], - "type" : "object", - "properties" : { - "className" : { - "type" : "string" - }, - "color" : { - "type" : "string", - "default" : "red" - }, - "declawed" : { - "type" : "boolean" - } - }, - "discriminator" : { - "propertyName" : "className" - } -} -SCHEMA; - - public static function getOpenApiSchema() - { - return json_decode(static::MODEL_SCHEMA, true); - } -} - -final class ClassWithoutGetSchemaMethod -{ -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache index b8852944a12..c8e5d27ca2a 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/phpunit.xml.mustache @@ -15,12 +15,14 @@ {{apiTestPath}} + ./{{testBasePath}}/BaseModelTest.php {{modelTestPath}} {{apiSrcPath}} + ./{{srcBasePath}}/BaseModel.php {{modelSrcPath}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait.mustache deleted file mode 100644 index f303bd7cc95..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait.mustache +++ /dev/null @@ -1,117 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{utilsPackage}}; - -/** - * {{traitNamePrefix}}StringUtils{{traitNameSuffix}} Class Doc Comment - * This class duplicates functionality of StringUtils.java and AbstractPhpCodegen.java classes. - * - * @package {{utilsPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - */ -trait {{traitNamePrefix}}StringUtils{{traitNameSuffix}} -{ - /** - * Camelize name (parameter, property, method, etc) - * This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/StringUtils.java class. - * - * @param string $word string to be camelize - * @param bool $lowercaseFirstLetter lower case for first letter if set to true - * - * @return string camelized string - */ - public static function camelize($word, $lowercaseFirstLetter = false) - { - // Replace all slashes with dots (package separator) - $p = '/\/(.?)/'; - $word = preg_replace($p, '.$1', $word); - - // case out dots - $parts = explode('.', $word); - $str = ''; - foreach ($parts as $z) { - if (strlen($z) > 0) { - $str .= strtoupper(substr($z, 0, 1)) . substr($z, 1); - } - } - $word = $str; - - // Uppercase the class name. - $p = '/(\.?)(\w)([^\.]*)$/'; - $word = preg_replace_callback($p, function ($matches) { - $rep = $matches[1] . strtoupper($matches[2]) . $matches[3]; - $rep = preg_replace('/\$/', '\\\$', $rep); - return $rep; - }, $word); - - // Remove all underscores (underscore_case to camelCase) - $p = '/(_)(.)/'; - while (preg_match($p, $word, $matches) === 1) { - $original = $matches[2][0]; - $upperCase = strtoupper($original); - if ($original === $upperCase) { - $word = preg_replace($p, '$2', $word); - } else { - $word = preg_replace($p, $upperCase, $word); - } - } - - // Remove all hyphens (hyphen-case to camelCase) - $p = '/(-)(.)/'; - while (preg_match($p, $word, $matches) === 1) { - $upperCase = strtoupper($matches[2][0]); - $word = preg_replace($p, $upperCase, $word); - } - - if ($lowercaseFirstLetter === true && strlen($word) > 0) { - $i = 0; - $charAt = substr($word, $i, 1); - while ( - $i + 1 < strlen($word) - && !( - ($charAt >= 'a' && $charAt <= 'z') - || ($charAt >= 'A' && $charAt <= 'Z') - ) - ) { - $i++; - $charAt = substr($word, $i, 1); - } - $i++; - $word = strtolower(substr($word, 0, $i)) . substr($word, $i); - } - - // remove all underscore - $word = str_replace('_', '', $word); - - return $word; - } - - /** - * Checks whether string is reserved php keyword. - * This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java class. - * - * @param string $word Checked string - * - * @return bool - */ - public static function isReservedWord($word) - { - if (is_string($word) === false) { - return false; - } - // __halt_compiler is ommited because class names with underscores not allowed anyway - return in_array( - strtolower($word), - ['abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor'] - ); - } -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait_test.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait_test.mustache deleted file mode 100644 index d54c6bbee38..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/string_utils_trait_test.mustache +++ /dev/null @@ -1,84 +0,0 @@ -licenseInfo}} - -/** - * NOTE: This class is auto generated by the openapi generator program. - * https://github.com/openapitools/openapi-generator - * Do not edit the class manually. - */{{#apiInfo}} -namespace {{utilsPackage}}; - -use {{utilsPackage}}\{{traitNamePrefix}}StringUtils{{traitNameSuffix}} as StringUtils; -use PHPUnit\Framework\TestCase; - -/** - * {{traitNamePrefix}}StringUtils{{traitNameSuffix}}Test Class Doc Comment - * - * @package {{utilsPackage}} - * @author OpenAPI Generator team - * @link https://github.com/openapitools/openapi-generator - * @coversDefaultClass \{{utilsPackage}}\{{traitNamePrefix}}StringUtils{{traitNameSuffix}} - */ -class {{traitNamePrefix}}StringUtils{{traitNameSuffix}}Test extends TestCase -{ - /** - * @covers ::camelize - * @dataProvider provideWordsForCamelizeTest - */ - public function testCamelize($word, $lowercaseFirstLetter, $expectedWord) - { - $this->assertSame($expectedWord, StringUtils::camelize($word, $lowercaseFirstLetter)); - } - - public function provideWordsForCamelizeTest() - { - return [ - // fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java - ['openApiServer/model/pet', null, 'OpenApiServerModelPet'], - ['abcd', null, 'Abcd'], - ['some-value', null, 'SomeValue'], - ['some-Value', null, 'SomeValue'], - ['some_value', null, 'SomeValue'], - ['some_Value', null, 'SomeValue'], - ['$type', null, '$Type'], - - ['abcd', true, 'abcd'], - ['some-value', true, 'someValue'], - ['some_value', true, 'someValue'], - ['Abcd', true, 'abcd'], - ['$type', true, '$type'], - - ['123', true, '123'], - ['$123', true, '$123'], - ]; - } - - /** - * @covers ::isReservedWord - * @dataProvider provideWordsForIsReservedTest - */ - public function testisReservedWord($word, $expected) - { - $this->assertSame($expected, StringUtils::isReservedWord($word)); - } - - public function provideWordsForIsReservedTest() - { - return [ - ['return', true], - ['switch', true], - ['class', true], - ['interface', true], - ['ABSTRACT', true], - ['Trait', true], - ['final', true], - ['foobar', false], - ['DateTime', false], - ['Pet', false], - [123, false], - [null, false], - ]; - } -} -{{/apiInfo}} diff --git a/samples/server/petstore/php-slim4/.openapi-generator/FILES b/samples/server/petstore/php-slim4/.openapi-generator/FILES index ba22c031220..09a56bb87d4 100644 --- a/samples/server/petstore/php-slim4/.openapi-generator/FILES +++ b/samples/server/petstore/php-slim4/.openapi-generator/FILES @@ -2,11 +2,7 @@ .htaccess README.md composer.json -docs/MockServer.md index.php -lib/Api/AbstractAnotherFakeApi.php -lib/Api/AbstractFakeApi.php -lib/Api/AbstractFakeClassnameTags123Api.php lib/Api/AbstractPetApi.php lib/Api/AbstractStoreApi.php lib/Api/AbstractUserApi.php @@ -23,65 +19,31 @@ lib/Auth/AbstractAuthenticator.php lib/Auth/AbstractAuthenticator.php lib/Auth/AbstractAuthenticator.php lib/Auth/AbstractAuthenticator.php -lib/Interfaces/ModelInterface.php +lib/Auth/AbstractAuthenticator.php +lib/Auth/AbstractAuthenticator.php +lib/Auth/AbstractAuthenticator.php +lib/BaseModel.php lib/Middleware/JsonBodyParserMiddleware.php -lib/Mock/OpenApiDataMocker.php -lib/Mock/OpenApiDataMockerInterface.php -lib/Mock/OpenApiDataMockerMiddleware.php -lib/Model/AdditionalPropertiesAnyType.php -lib/Model/AdditionalPropertiesArray.php -lib/Model/AdditionalPropertiesBoolean.php -lib/Model/AdditionalPropertiesClass.php -lib/Model/AdditionalPropertiesInteger.php -lib/Model/AdditionalPropertiesNumber.php -lib/Model/AdditionalPropertiesObject.php -lib/Model/AdditionalPropertiesString.php -lib/Model/Animal.php lib/Model/ApiResponse.php -lib/Model/ArrayOfArrayOfNumberOnly.php -lib/Model/ArrayOfNumberOnly.php -lib/Model/ArrayTest.php -lib/Model/BigCat.php -lib/Model/BigCatAllOf.php -lib/Model/Capitalization.php -lib/Model/Cat.php -lib/Model/CatAllOf.php lib/Model/Category.php -lib/Model/ClassModel.php -lib/Model/Client.php -lib/Model/Dog.php -lib/Model/DogAllOf.php -lib/Model/EnumArrays.php -lib/Model/EnumClass.php -lib/Model/EnumTest.php -lib/Model/File.php -lib/Model/FileSchemaTestClass.php -lib/Model/FormatTest.php -lib/Model/HasOnlyReadOnly.php -lib/Model/MapTest.php -lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php -lib/Model/Model200Response.php -lib/Model/ModelList.php -lib/Model/ModelReturn.php -lib/Model/Name.php -lib/Model/NumberOnly.php +lib/Model/InlineObject.php +lib/Model/InlineObject1.php lib/Model/Order.php -lib/Model/OuterComposite.php -lib/Model/OuterEnum.php lib/Model/Pet.php -lib/Model/ReadOnlyFirst.php -lib/Model/SpecialModelName.php lib/Model/Tag.php -lib/Model/TypeHolderDefault.php -lib/Model/TypeHolderExample.php lib/Model/User.php -lib/Model/XmlItem.php lib/SlimRouter.php -lib/Utils/ModelUtilsTrait.php -lib/Utils/StringUtilsTrait.php phpcs.xml.dist phpunit.xml.dist -test/Mock/OpenApiDataMockerMiddlewareTest.php -test/Mock/OpenApiDataMockerTest.php -test/Utils/ModelUtilsTraitTest.php -test/Utils/StringUtilsTraitTest.php +test/Api/PetApiTest.php +test/Api/StoreApiTest.php +test/Api/UserApiTest.php +test/BaseModelTest.php +test/Model/ApiResponseTest.php +test/Model/CategoryTest.php +test/Model/InlineObject1Test.php +test/Model/InlineObjectTest.php +test/Model/OrderTest.php +test/Model/PetTest.php +test/Model/TagTest.php +test/Model/UserTest.php diff --git a/samples/server/petstore/php-slim4/README.md b/samples/server/petstore/php-slim4/README.md index 7c550d25424..6a8bd154ccb 100644 --- a/samples/server/petstore/php-slim4/README.md +++ b/samples/server/petstore/php-slim4/README.md @@ -35,9 +35,9 @@ $ php -S localhost:8888 -t php-slim-server ### PHPUnit -This package uses PHPUnit 6 or 7(depends from your PHP version) for unit testing. +This package uses PHPUnit 8 or 9(depends from your PHP version) for unit testing. [Test folder](test) contains templates which you can fill with real test assertions. -How to write tests read at [PHPUnit Manual - Chapter 2. Writing Tests for PHPUnit](https://phpunit.de/manual/6.5/en/writing-tests-for-phpunit.html). +How to write tests read at [2. Writing Tests for PHPUnit - PHPUnit 8.5 Manual](https://phpunit.readthedocs.io/en/8.5/writing-tests-for-phpunit.html). #### Run @@ -46,14 +46,12 @@ Command | Target `$ composer test` | All tests `$ composer test-apis` | Apis tests `$ composer test-models` | Models tests -`$ composer test-mock` | Mock feature tests -`$ composer test-utils` | Utils tests #### Config Package contains fully functional config `./phpunit.xml.dist` file. Create `./phpunit.xml` in root folder to override it. -Quote from [3. The Command-Line Test Runner — PHPUnit 7.4 Manual](https://phpunit.readthedocs.io/en/7.4/textui.html#command-line-options): +Quote from [3. The Command-Line Test Runner — PHPUnit 8.5 Manual](https://phpunit.readthedocs.io/en/8.5/textui.html#command-line-options): > If phpunit.xml or phpunit.xml.dist (in that order) exist in the current working directory and --configuration is not used, the configuration will be automatically read from that file. @@ -101,11 +99,17 @@ Switch on option in `./index.php`: +++ $app->addErrorMiddleware(true, true, true); ``` -## [Mock Server Documentation](./docs/MockServer.md) +## Mock Server +For a quick start uncomment [mocker middleware config](index.php#L62-L89). + +Used packages: +* [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator. +* [Openapi Data Mocker Server Middleware](https://github.com/ybelenko/openapi-data-mocker-server-middleware) - PSR-15 HTTP server middleware. +* [Openapi Data Mocker Interfaces](https://github.com/ybelenko/openapi-data-mocker-interfaces) - package with mocking interfaces. ## API Endpoints -All URIs are relative to *http://petstore.swagger.io:80/v2* +All URIs are relative to *http://petstore.swagger.io/v2* > Important! Do not modify abstract API controllers directly! Instead extend them by implementation classes like: @@ -131,22 +135,6 @@ For instance, when abstract class located at `./lib/Api/AbstractPetApi.php` you Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*AbstractAnotherFakeApi* | **call123TestSpecialTags** | **PATCH** /another-fake/dummy | To test special tags -*AbstractFakeApi* | **createXmlItem** | **POST** /fake/create_xml_item | creates an XmlItem -*AbstractFakeApi* | **fakeOuterBooleanSerialize** | **POST** /fake/outer/boolean | -*AbstractFakeApi* | **fakeOuterCompositeSerialize** | **POST** /fake/outer/composite | -*AbstractFakeApi* | **fakeOuterNumberSerialize** | **POST** /fake/outer/number | -*AbstractFakeApi* | **fakeOuterStringSerialize** | **POST** /fake/outer/string | -*AbstractFakeApi* | **testBodyWithFileSchema** | **PUT** /fake/body-with-file-schema | -*AbstractFakeApi* | **testBodyWithQueryParams** | **PUT** /fake/body-with-query-params | -*AbstractFakeApi* | **testClientModel** | **PATCH** /fake | To test \"client\" model -*AbstractFakeApi* | **testEndpointParameters** | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -*AbstractFakeApi* | **testEnumParameters** | **GET** /fake | To test enum parameters -*AbstractFakeApi* | **testGroupParameters** | **DELETE** /fake | Fake endpoint to test group parameters (optional) -*AbstractFakeApi* | **testInlineAdditionalProperties** | **POST** /fake/inline-additionalProperties | test inline additionalProperties -*AbstractFakeApi* | **testJsonFormData** | **GET** /fake/jsonFormData | test json serialization of form data -*AbstractFakeApi* | **testQueryParameterCollectionFormat** | **PUT** /fake/test-query-paramters | -*AbstractFakeClassnameTags123Api* | **testClassname** | **PATCH** /fake_classname_test | To test class name in snake case *AbstractPetApi* | **addPet** | **POST** /pet | Add a new pet to the store *AbstractPetApi* | **findPetsByStatus** | **GET** /pet/findByStatus | Finds Pets by status *AbstractPetApi* | **findPetsByTags** | **GET** /pet/findByTags | Finds Pets by tags @@ -155,11 +143,10 @@ Class | Method | HTTP request | Description *AbstractPetApi* | **getPetById** | **GET** /pet/{petId} | Find pet by ID *AbstractPetApi* | **updatePetWithForm** | **POST** /pet/{petId} | Updates a pet in the store with form data *AbstractPetApi* | **uploadFile** | **POST** /pet/{petId}/uploadImage | uploads an image -*AbstractPetApi* | **uploadFileWithRequiredFile** | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) *AbstractStoreApi* | **getInventory** | **GET** /store/inventory | Returns pet inventories by status *AbstractStoreApi* | **placeOrder** | **POST** /store/order | Place an order for a pet -*AbstractStoreApi* | **deleteOrder** | **DELETE** /store/order/{order_id} | Delete purchase order by ID -*AbstractStoreApi* | **getOrderById** | **GET** /store/order/{order_id} | Find purchase order by ID +*AbstractStoreApi* | **deleteOrder** | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*AbstractStoreApi* | **getOrderById** | **GET** /store/order/{orderId} | Find purchase order by ID *AbstractUserApi* | **createUser** | **POST** /user | Create user *AbstractUserApi* | **createUsersWithArrayInput** | **POST** /user/createWithArray | Creates list of users with given input array *AbstractUserApi* | **createUsersWithListInput** | **POST** /user/createWithList | Creates list of users with given input array @@ -172,54 +159,14 @@ Class | Method | HTTP request | Description ## Models -* OpenAPIServer\Model\AdditionalPropertiesAnyType -* OpenAPIServer\Model\AdditionalPropertiesArray -* OpenAPIServer\Model\AdditionalPropertiesBoolean -* OpenAPIServer\Model\AdditionalPropertiesClass -* OpenAPIServer\Model\AdditionalPropertiesInteger -* OpenAPIServer\Model\AdditionalPropertiesNumber -* OpenAPIServer\Model\AdditionalPropertiesObject -* OpenAPIServer\Model\AdditionalPropertiesString -* OpenAPIServer\Model\Animal * OpenAPIServer\Model\ApiResponse -* OpenAPIServer\Model\ArrayOfArrayOfNumberOnly -* OpenAPIServer\Model\ArrayOfNumberOnly -* OpenAPIServer\Model\ArrayTest -* OpenAPIServer\Model\BigCat -* OpenAPIServer\Model\BigCatAllOf -* OpenAPIServer\Model\Capitalization -* OpenAPIServer\Model\Cat -* OpenAPIServer\Model\CatAllOf * OpenAPIServer\Model\Category -* OpenAPIServer\Model\ClassModel -* OpenAPIServer\Model\Client -* OpenAPIServer\Model\Dog -* OpenAPIServer\Model\DogAllOf -* OpenAPIServer\Model\EnumArrays -* OpenAPIServer\Model\EnumClass -* OpenAPIServer\Model\EnumTest -* OpenAPIServer\Model\File -* OpenAPIServer\Model\FileSchemaTestClass -* OpenAPIServer\Model\FormatTest -* OpenAPIServer\Model\HasOnlyReadOnly -* OpenAPIServer\Model\MapTest -* OpenAPIServer\Model\MixedPropertiesAndAdditionalPropertiesClass -* OpenAPIServer\Model\Model200Response -* OpenAPIServer\Model\ModelList -* OpenAPIServer\Model\ModelReturn -* OpenAPIServer\Model\Name -* OpenAPIServer\Model\NumberOnly +* OpenAPIServer\Model\InlineObject +* OpenAPIServer\Model\InlineObject1 * OpenAPIServer\Model\Order -* OpenAPIServer\Model\OuterComposite -* OpenAPIServer\Model\OuterEnum * OpenAPIServer\Model\Pet -* OpenAPIServer\Model\ReadOnlyFirst -* OpenAPIServer\Model\SpecialModelName * OpenAPIServer\Model\Tag -* OpenAPIServer\Model\TypeHolderDefault -* OpenAPIServer\Model\TypeHolderExample * OpenAPIServer\Model\User -* OpenAPIServer\Model\XmlItem ## Authentication @@ -227,12 +174,6 @@ Class | Method | HTTP request | Description ### Security schema `api_key` > Important! To make ApiKey authentication work you need to extend [\OpenAPIServer\Auth\AbstractAuthenticator](./lib/Auth/AbstractAuthenticator.php) class by [\OpenAPIServer\Auth\ApiKeyAuthenticator](./src/Auth/ApiKeyAuthenticator.php) class. -### Security schema `api_key_query` -> Important! To make ApiKey authentication work you need to extend [\OpenAPIServer\Auth\AbstractAuthenticator](./lib/Auth/AbstractAuthenticator.php) class by [\OpenAPIServer\Auth\ApiKeyAuthenticator](./src/Auth/ApiKeyAuthenticator.php) class. - -### Security schema `http_basic_test` -> Important! To make Basic authentication work you need to extend [\OpenAPIServer\Auth\AbstractAuthenticator](./lib/Auth/AbstractAuthenticator.php) class by [\OpenAPIServer\Auth\BasicAuthenticator](./src/Auth/BasicAuthenticator.php) class. - ### Security schema `petstore_auth` > Important! To make OAuth authentication work you need to extend [\OpenAPIServer\Auth\AbstractAuthenticator](./lib/Auth/AbstractAuthenticator.php) class by [\OpenAPIServer\Auth\OAuthAuthenticator](./src/Auth/OAuthAuthenticator.php) class. diff --git a/samples/server/petstore/php-slim4/composer.json b/samples/server/petstore/php-slim4/composer.json index 0bc4d34e177..8181c11ae83 100644 --- a/samples/server/petstore/php-slim4/composer.json +++ b/samples/server/petstore/php-slim4/composer.json @@ -11,6 +11,8 @@ "php": "^7.2", "slim/slim": "^4.5.0", "dyorg/slim-token-authentication": "dev-slim4", + "ybelenko/openapi-data-mocker": "^1.0", + "ybelenko/openapi-data-mocker-server-middleware": "^1.0", "slim/psr7": "^1.1.0" }, "require-dev": { diff --git a/samples/server/petstore/php-slim4/docs/MockServer.md b/samples/server/petstore/php-slim4/docs/MockServer.md deleted file mode 100644 index 76f5668ad51..00000000000 --- a/samples/server/petstore/php-slim4/docs/MockServer.md +++ /dev/null @@ -1,135 +0,0 @@ -# php-base - PHP Slim 4 Server library for OpenAPI Petstore - -## Mock Server Documentation - -### Mocker Options -To enable mock server uncomment these lines in `index.php` config file: - -```php -/** - * Mocker Middleware options. - */ -$config['mockerOptions'] = [ - 'dataMocker' => new OpenApiDataMocker(), - - 'getMockResponseCallback' => function (ServerRequestInterface $request, array $responses) { - // check if client clearly asks for mocked response - if ( - $request->hasHeader('X-OpenAPIServer-Mock') - && $request->getHeader('X-OpenAPIServer-Mock')[0] === 'ping' - ) { - if (array_key_exists('default', $responses)) { - return $responses['default']; - } - - // return first response - return $responses[array_key_first($responses)]; - } - - return false; - }, - - 'afterCallback' => function ($request, $response) { - // mark mocked response to distinguish real and fake responses - return $response->withHeader('X-OpenAPIServer-Mock', 'pong'); - }, -]; -``` - -* `dataMocker` is mocker class instance. To create custom data mocker extend `OpenAPIServer\Mock\OpenApiDataMockerInterface`. -* `getMockResponseCallback` is callback before mock data generation. Above example shows how to enable mock feature for only requests with `{{X-OpenAPIServer}}-mock: ping` HTTP header. Adjust requests filtering to fit your project requirements. This function must return single response schema from `$responses` array parameter. **Mock feature is disabled when callback returns anything beside array.** -* `afterCallback` is callback executed after mock data generation. Most obvious use case is append specific HTTP headers to distinguish real and fake responses. **This function must always return response instance.** - -### Supported features - -All data types supported except specific string formats: `email`, `uuid`, `password` which are poorly implemented. - -#### Data Types Support - -| Data Type | Data Format | Supported | -|:---------:|:-----------:|:------------------:| -| `integer` | `int32` | :white_check_mark: | -| `integer` | `int64` | :white_check_mark: | -| `number` | `float` | :white_check_mark: | -| `number` | `double` | | -| `string` | `byte` | :white_check_mark: | -| `string` | `binary` | :white_check_mark: | -| `boolean` | | :white_check_mark: | -| `string` | `date` | :white_check_mark: | -| `string` | `date-time` | :white_check_mark: | -| `string` | `password` | :white_check_mark: | -| `string` | `email` | :white_check_mark: | -| `string` | `uuid` | :white_check_mark: | - -#### Data Options Support - -| Data Type | Option | Supported | -|:-----------:|:----------------------:|:------------------:| -| `string` | `minLength` | :white_check_mark: | -| `string` | `maxLength` | :white_check_mark: | -| `string` | `enum` | :white_check_mark: | -| `string` | `pattern` | | -| `integer` | `minimum` | :white_check_mark: | -| `integer` | `maximum` | :white_check_mark: | -| `integer` | `exclusiveMinimum` | :white_check_mark: | -| `integer` | `exclusiveMaximum` | :white_check_mark: | -| `number` | `minimum` | :white_check_mark: | -| `number` | `maximum` | :white_check_mark: | -| `number` | `exclusiveMinimum` | :white_check_mark: | -| `number` | `exclusiveMaximum` | :white_check_mark: | -| `array` | `items` | :white_check_mark: | -| `array` | `additionalItems` | | -| `array` | `minItems` | :white_check_mark: | -| `array` | `maxItems` | :white_check_mark: | -| `array` | `uniqueItems` | | -| `object` | `properties` | :white_check_mark: | -| `object` | `maxProperties` | | -| `object` | `minProperties` | | -| `object` | `patternProperties` | | -| `object` | `additionalProperties` | | -| `object` | `required` | | -| `*` | `$ref` | :white_check_mark: | -| `*` | `allOf` | | -| `*` | `anyOf` | | -| `*` | `oneOf` | | -| `*` | `not` | | - -### Known Limitations - -Avoid circular refs in your schema. Schema below can cause infinite loop and `Out of Memory` PHP error: -```yml -# ModelA has reference to ModelB while ModelB has reference to ModelA. -# Mock server will produce huge nested JSON example and ended with `Out of Memory` error. -definitions: - ModelA: - type: object - properties: - model_b: - $ref: '#/definitions/ModelB' - ModelB: - type: array - items: - $ref: '#/definitions/ModelA' -``` - -Don't ref scalar types, because generator will not produce models which mock server can find. So schema below will cause error: -```yml -# generated build contains only `OuterComposite` model class which referenced to not existed `OuterNumber`, `OuterString`, `OuterBoolean` classes -# mock server cannot mock `OuterComposite` model and throws exception -definitions: - OuterComposite: - type: object - properties: - my_number: - $ref: '#/definitions/OuterNumber' - my_string: - $ref: '#/definitions/OuterString' - my_boolean: - $ref: '#/definitions/OuterBoolean' - OuterNumber: - type: number - OuterString: - type: string - OuterBoolean: - type: boolean -``` diff --git a/samples/server/petstore/php-slim4/index.php b/samples/server/petstore/php-slim4/index.php index ffeb1b88200..f5295cedc9a 100644 --- a/samples/server/petstore/php-slim4/index.php +++ b/samples/server/petstore/php-slim4/index.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -65,21 +65,28 @@ $config['tokenAuthenticationOptions'] = [ /** * Mocker Middleware options. */ +$mocker = new OpenApiDataMocker(); +$mocker->setModelsNamespace('OpenAPIServer\Model\\'); $config['mockerOptions'] = [ - // 'dataMocker' => new OpenApiDataMocker(), + // 'dataMocker' => $mocker, - // 'getMockResponseCallback' => function (ServerRequestInterface $request, array $responses) { + // 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, $responses) { // // check if client clearly asks for mocked response + // $pingHeader = 'X-OpenAPIServer-Mock'; + // $pingHeaderCode = 'X-OpenAPIServer-Mock-Code'; // if ( - // $request->hasHeader('X-OpenAPIServer-Mock') - // && $request->getHeader('X-OpenAPIServer-Mock')[0] === 'ping' + // $request->hasHeader($pingHeader) + // && $request->getHeader($pingHeader)[0] === 'ping' // ) { - // if (array_key_exists('default', $responses)) { - // return $responses['default']; + // $responses = (array) $responses; + // $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default'; + // if (array_key_exists($requestedResponseCode, $responses)) { + // return $requestedResponseCode; // } - // // return first response - // return $responses[array_key_first($responses)]; + // // return first response key + // reset($responses); + // return key($responses); // } // return false; diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractAnotherFakeApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractAnotherFakeApi.php deleted file mode 100644 index 64347eabd0b..00000000000 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractAnotherFakeApi.php +++ /dev/null @@ -1,75 +0,0 @@ -container = $container; - } - - - /** - * PATCH call123TestSpecialTags - * Summary: To test special tags - * Notes: To test special tags and operation ID starting with number - * Output-Formats: [application/json] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function call123TestSpecialTags(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing call123TestSpecialTags as a PATCH method in OpenAPIServer\Api\AnotherFakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } -} diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractFakeApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractFakeApi.php deleted file mode 100644 index b07703a954f..00000000000 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractFakeApi.php +++ /dev/null @@ -1,356 +0,0 @@ -container = $container; - } - - - /** - * POST createXmlItem - * Summary: creates an XmlItem - * Notes: this route creates an XmlItem - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function createXmlItem(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing createXmlItem as a POST method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * POST fakeOuterBooleanSerialize - * Notes: Test serialization of outer boolean types - * Output-Formats: [*_/_*] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function fakeOuterBooleanSerialize(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing fakeOuterBooleanSerialize as a POST method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * POST fakeOuterCompositeSerialize - * Notes: Test serialization of object with outer number type - * Output-Formats: [*_/_*] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function fakeOuterCompositeSerialize(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing fakeOuterCompositeSerialize as a POST method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * POST fakeOuterNumberSerialize - * Notes: Test serialization of outer number types - * Output-Formats: [*_/_*] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function fakeOuterNumberSerialize(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing fakeOuterNumberSerialize as a POST method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * POST fakeOuterStringSerialize - * Notes: Test serialization of outer string types - * Output-Formats: [*_/_*] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function fakeOuterStringSerialize(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing fakeOuterStringSerialize as a POST method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * PUT testBodyWithFileSchema - * Notes: For this test, the body for this request much reference a schema named `File`. - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testBodyWithFileSchema(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing testBodyWithFileSchema as a PUT method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * PUT testBodyWithQueryParams - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testBodyWithQueryParams(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $queryParams = $request->getQueryParams(); - $query = (key_exists('query', $queryParams)) ? $queryParams['query'] : null; - $body = $request->getParsedBody(); - $message = "How about implementing testBodyWithQueryParams as a PUT method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * PATCH testClientModel - * Summary: To test \"client\" model - * Notes: To test \"client\" model - * Output-Formats: [application/json] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testClientModel(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing testClientModel as a PATCH method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * POST testEndpointParameters - * Summary: Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Notes: Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testEndpointParameters(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $integer = (isset($body['integer'])) ? $body['integer'] : null; - $int32 = (isset($body['int32'])) ? $body['int32'] : null; - $int64 = (isset($body['int64'])) ? $body['int64'] : null; - $number = (isset($body['number'])) ? $body['number'] : null; - $float = (isset($body['float'])) ? $body['float'] : null; - $double = (isset($body['double'])) ? $body['double'] : null; - $string = (isset($body['string'])) ? $body['string'] : null; - $patternWithoutDelimiter = (isset($body['pattern_without_delimiter'])) ? $body['pattern_without_delimiter'] : null; - $byte = (isset($body['byte'])) ? $body['byte'] : null; - $binary = (isset($body['binary'])) ? $body['binary'] : null; - $date = (isset($body['date'])) ? $body['date'] : null; - $dateTime = (isset($body['dateTime'])) ? $body['dateTime'] : null; - $password = (isset($body['password'])) ? $body['password'] : null; - $callback = (isset($body['callback'])) ? $body['callback'] : null; - $message = "How about implementing testEndpointParameters as a POST method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * GET testEnumParameters - * Summary: To test enum parameters - * Notes: To test enum parameters - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testEnumParameters(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $headers = $request->getHeaders(); - $enumHeaderStringArray = $request->hasHeader('enum_header_string_array') ? $headers['enum_header_string_array'] : null; - $enumHeaderString = $request->hasHeader('enum_header_string') ? $headers['enum_header_string'] : null; - $queryParams = $request->getQueryParams(); - $enumQueryStringArray = (key_exists('enum_query_string_array', $queryParams)) ? $queryParams['enum_query_string_array'] : null; - $enumQueryString = (key_exists('enum_query_string', $queryParams)) ? $queryParams['enum_query_string'] : null; - $enumQueryInteger = (key_exists('enum_query_integer', $queryParams)) ? $queryParams['enum_query_integer'] : null; - $enumQueryDouble = (key_exists('enum_query_double', $queryParams)) ? $queryParams['enum_query_double'] : null; - $body = $request->getParsedBody(); - $enumFormStringArray = (isset($body['enum_form_string_array'])) ? $body['enum_form_string_array'] : null; - $enumFormString = (isset($body['enum_form_string'])) ? $body['enum_form_string'] : null; - $message = "How about implementing testEnumParameters as a GET method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * DELETE testGroupParameters - * Summary: Fake endpoint to test group parameters (optional) - * Notes: Fake endpoint to test group parameters (optional) - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testGroupParameters(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $headers = $request->getHeaders(); - $requiredBooleanGroup = $request->hasHeader('required_boolean_group') ? $headers['required_boolean_group'] : null; - $booleanGroup = $request->hasHeader('boolean_group') ? $headers['boolean_group'] : null; - $queryParams = $request->getQueryParams(); - $requiredStringGroup = (key_exists('required_string_group', $queryParams)) ? $queryParams['required_string_group'] : null; - $requiredInt64Group = (key_exists('required_int64_group', $queryParams)) ? $queryParams['required_int64_group'] : null; - $stringGroup = (key_exists('string_group', $queryParams)) ? $queryParams['string_group'] : null; - $int64Group = (key_exists('int64_group', $queryParams)) ? $queryParams['int64_group'] : null; - $message = "How about implementing testGroupParameters as a DELETE method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * POST testInlineAdditionalProperties - * Summary: test inline additionalProperties - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testInlineAdditionalProperties(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing testInlineAdditionalProperties as a POST method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * GET testJsonFormData - * Summary: test json serialization of form data - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testJsonFormData(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $param = (isset($body['param'])) ? $body['param'] : null; - $param2 = (isset($body['param2'])) ? $body['param2'] : null; - $message = "How about implementing testJsonFormData as a GET method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } - - /** - * PUT testQueryParameterCollectionFormat - * Notes: To test the collection format in query parameters - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testQueryParameterCollectionFormat(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $queryParams = $request->getQueryParams(); - $pipe = (key_exists('pipe', $queryParams)) ? $queryParams['pipe'] : null; - $ioutil = (key_exists('ioutil', $queryParams)) ? $queryParams['ioutil'] : null; - $http = (key_exists('http', $queryParams)) ? $queryParams['http'] : null; - $url = (key_exists('url', $queryParams)) ? $queryParams['url'] : null; - $context = (key_exists('context', $queryParams)) ? $queryParams['context'] : null; - $message = "How about implementing testQueryParameterCollectionFormat as a PUT method in OpenAPIServer\Api\FakeApi class?"; - throw new HttpNotImplementedException($request, $message); - } -} diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractFakeClassnameTags123Api.php b/samples/server/petstore/php-slim4/lib/Api/AbstractFakeClassnameTags123Api.php deleted file mode 100644 index f49c392aa92..00000000000 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractFakeClassnameTags123Api.php +++ /dev/null @@ -1,75 +0,0 @@ -container = $container; - } - - - /** - * PATCH testClassname - * Summary: To test class name in snake case - * Notes: To test class name in snake case - * Output-Formats: [application/json] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function testClassname(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $body = $request->getParsedBody(); - $message = "How about implementing testClassname as a PATCH method in OpenAPIServer\Api\FakeClassnameTags123Api class?"; - throw new HttpNotImplementedException($request, $message); - } -} diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php index d835b2b0ab3..cffea37cd76 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -56,6 +56,7 @@ abstract class AbstractPetApi /** * POST addPet * Summary: Add a new pet to the store + * Output-Formats: [application/xml, application/json] * * @param ServerRequestInterface $request Request * @param ResponseInterface $response Response @@ -156,6 +157,7 @@ abstract class AbstractPetApi /** * PUT updatePet * Summary: Update an existing pet + * Output-Formats: [application/xml, application/json] * * @param ServerRequestInterface $request Request * @param ResponseInterface $response Response @@ -213,26 +215,4 @@ abstract class AbstractPetApi $message = "How about implementing uploadFile as a POST method in OpenAPIServer\Api\PetApi class?"; throw new HttpNotImplementedException($request, $message); } - - /** - * POST uploadFileWithRequiredFile - * Summary: uploads an image (required) - * Output-Formats: [application/json] - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws HttpNotImplementedException to force implementation class to override this method - */ - public function uploadFileWithRequiredFile(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - $petId = $args['petId']; - $body = $request->getParsedBody(); - $additionalMetadata = (isset($body['additionalMetadata'])) ? $body['additionalMetadata'] : null; - $requiredFile = (key_exists('requiredFile', $request->getUploadedFiles())) ? $request->getUploadedFiles()['requiredFile'] : null; - $message = "How about implementing uploadFileWithRequiredFile as a POST method in OpenAPIServer\Api\PetApi class?"; - throw new HttpNotImplementedException($request, $message); - } } diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php index fbcf6ad53b9..00d50340c81 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -67,7 +67,7 @@ abstract class AbstractStoreApi */ public function deleteOrder(ServerRequestInterface $request, ResponseInterface $response, array $args) { - $orderId = $args['order_id']; + $orderId = $args['orderId']; $message = "How about implementing deleteOrder as a DELETE method in OpenAPIServer\Api\StoreApi class?"; throw new HttpNotImplementedException($request, $message); } @@ -106,7 +106,7 @@ abstract class AbstractStoreApi */ public function getOrderById(ServerRequestInterface $request, ResponseInterface $response, array $args) { - $orderId = $args['order_id']; + $orderId = $args['orderId']; $message = "How about implementing getOrderById as a GET method in OpenAPIServer\Api\StoreApi class?"; throw new HttpNotImplementedException($request, $message); } diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php index ae779dbeda0..7b679c16c6d 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php b/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php index e9bdacd3f96..33fbd4dfe44 100644 --- a/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php +++ b/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/samples/server/petstore/php-slim4/lib/BaseModel.php b/samples/server/petstore/php-slim4/lib/BaseModel.php new file mode 100644 index 00000000000..d33e7921de9 --- /dev/null +++ b/samples/server/petstore/php-slim4/lib/BaseModel.php @@ -0,0 +1,332 @@ +validateModelType($modelType, true); + + // set initial data + switch ($modelType) { + case IMocker::DATA_TYPE_OBJECT: + case IMocker::DATA_TYPE_ARRAY: + $this->dataContainer = []; + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + default: + // scalar type + $this->dataContainer = null; + } + } + + /** + * Gets OAS 3.0 schema mapped to current class. + * + * @return array + */ + public static function getOpenApiSchema(): array + { + return json_decode(static::MODEL_SCHEMA, true); + } + + /** + * Creates new instance from provided data. + * + * @param mixed $data Data with values for new instance. + * + * @return OpenApiModelInterface + */ + public static function createFromData($data): OpenApiModelInterface + { + $instance = new static(); + $instance->setData($data); + return $instance; + } + + /** + * Sets instance data. + * + * @param mixed $data Data with values for new instance. + * + * @throws \InvalidArgumentException When value for array type is invalid. + * + * @return void + */ + public function setData($data): void + { + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + switch ($modelType) { + case IMocker::DATA_TYPE_ARRAY: + // data for array OAS type should be straight indexed array + if (is_array($data)) { + $arr = []; + for ($i = 0; $i < count($data); $i++) { + if (isset($data[$i])) { + $arr[$i] = $data[$i]; + } + } + + if (count($arr) === count($data)) { + $this->dataContainer = $arr; + return; + } + } + + throw new InvalidArgumentException( + sprintf('Invalid data for %s model because it accepts straight indexed arrays only', static::class) + ); + break; + case IMocker::DATA_TYPE_OBJECT: + foreach ($data as $key => $value) { + // this action handles __set method + $this->{$key} = $value; + } + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + default: + $this->dataContainer = $data; + break; + } + } + + /** + * Returns instance data. + * + * @return mixed + */ + public function getData() + { + $data = null; + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + switch ($modelType) { + case IMocker::DATA_TYPE_OBJECT: + // need to convert data container to object + $data = new StdClass(); + $definedProps = (array_key_exists('properties', $schema)) ? $schema['properties'] : null; + if (is_array($definedProps) || is_object($definedProps)) { + foreach ($definedProps as $propName => $propSchema) { + if (array_key_exists($propName, $this->dataContainer)) { + $data->{$propName} = $this->dataContainer[$propName]; + } elseif (array_key_exists('required', $schema) && in_array($propName, $schema['required'])) { + // property is required but not set + $data->{$propName} = null; + } + } + } + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + case IMocker::DATA_TYPE_ARRAY: + default: + $data = $this->dataContainer; + } + return $data; + } + + /** + * Writes data to inaccessible (protected or private) or non-existing properties. + * Ref @link https://www.php.net/manual/en/language.oop5.overloading.php#object.set + * + * @param string $param Property name. + * @param mixed $value Property value. + * + * @throws \InvalidArgumentException When property doesn't exist in related OAS schema. + * + * @return void + */ + public function __set(string $param, $value): void + { + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + switch ($modelType) { + case IMocker::DATA_TYPE_OBJECT: + $definedProps = (array_key_exists('properties', $schema)) ? (array) $schema['properties'] : null; + if (is_array($definedProps) && !in_array($param, array_keys($definedProps))) { + throw new InvalidArgumentException( + sprintf('Cannot set %s property of %s model because it doesn\'t exist in related OAS schema', $param, static::class) + ); + } + $this->dataContainer[$param] = $value; + break; + case IMocker::DATA_TYPE_INTEGER: + case IMocker::DATA_TYPE_NUMBER: + case IMocker::DATA_TYPE_STRING: + case IMocker::DATA_TYPE_BOOLEAN: + case IMocker::DATA_TYPE_ARRAY: + default: + // scalar type and array cannot use property assignation + throw new InvalidArgumentException( + sprintf('Cannot set %s property of %s model because it\'s %s type. Use setData method instead', $param, static::class, $modelType) + ); + } + } + + /** + * Reads data from inaccessible (protected or private) or non-existing properties. + * Ref @link https://www.php.net/manual/en/language.oop5.overloading.php#object.get + * + * @param string $param Property name. + * + * @throws \InvalidArgumentException When property doesn't exist in related OAS schema. + * + * @return mixed Property value + */ + public function __get(string $param) + { + $schema = (array) static::getOpenApiSchema(); + $modelType = (array_key_exists('type', $schema)) ? $schema['type'] : null; + $definedProps = (array_key_exists('properties', $schema)) ? (array) $schema['properties'] : null; + if (!in_array($modelType, [null, IMocker::DATA_TYPE_OBJECT])) { + // scalar type + throw new InvalidArgumentException( + sprintf('Cannot get %s property of %s model because getter is for object OAS type only', $param, static::class) + ); + } + + if ( + is_array($definedProps) + && in_array($param, array_keys($definedProps)) + ) { + return $this->dataContainer[$param]; + } elseif ($definedProps === null) { + // props are undefined + return (isset($this->dataContainer[$param])) ? $this->dataContainer[$param] : null; + } + + throw new InvalidArgumentException( + sprintf('Cannot get %s property of %s model because it doesn\'t exist in related OAS schema', $param, static::class) + ); + } + + /** + * Serializes the object to a value that can be serialized natively by json_encode(). + * Ref @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. + */ + public function jsonSerialize() + { + return $this->getData(); + } + + /** + * Checks if type is valid OAS data type. + * + * @param string|null $type Model type. + * @param bool $throwException Throws InvalidArgumentException when set to true and processed type is invalid. + * + * @throws \InvalidArgumentException When $throwException set to TRUE. + * + * @return bool + */ + protected function validateModelType(?string $type = null, bool $throwException = true): bool + { + $isValid = in_array($type, static::VALID_OAS_DATA_TYPES); + if ($type !== null && $isValid === false && $throwException) { + throw new InvalidArgumentException( + sprintf( + 'Invalid OAS schema of %s model, "type" must be one of %s', + static::class, + implode(', ', static::VALID_OAS_DATA_TYPES) + ) + ); + } + return $isValid; + } + + /** + * Returns models namespace. + * + * @return string + */ + public static function getModelsNamespace(): string + { + return static::MODELS_NAMESPACE . stripslashes('\\'); + } +} diff --git a/samples/server/petstore/php-slim4/lib/Interfaces/ModelInterface.php b/samples/server/petstore/php-slim4/lib/Interfaces/ModelInterface.php deleted file mode 100644 index b61edc27a1e..00000000000 --- a/samples/server/petstore/php-slim4/lib/Interfaces/ModelInterface.php +++ /dev/null @@ -1,42 +0,0 @@ -mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - } - return $this->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - case IMocker::DATA_TYPE_STRING: - $minLength = $options['minLength'] ?? 0; - $maxLength = $options['maxLength'] ?? null; - $enum = $options['enum'] ?? null; - return $this->mockString($dataFormat, $minLength, $maxLength, $enum); - case IMocker::DATA_TYPE_BOOLEAN: - return $this->mockBoolean(); - case IMocker::DATA_TYPE_ARRAY: - $items = $options['items'] ?? null; - $minItems = $options['minItems'] ?? 0; - $maxItems = $options['maxItems'] ?? null; - $uniqueItems = $options['uniqueItems'] ?? false; - return $this->mockArray($items, $minItems, $maxItems, $uniqueItems); - case IMocker::DATA_TYPE_OBJECT: - $properties = $options['properties'] ?? null; - $minProperties = $options['minProperties'] ?? 0; - $maxProperties = $options['maxProperties'] ?? null; - $additionalProperties = $options['additionalProperties'] ?? null; - $required = $options['required'] ?? null; - return $this->mockObject($properties, $minProperties, $maxProperties, $additionalProperties, $required); - default: - throw new InvalidArgumentException('"dataType" must be one of ' . implode(', ', [ - IMocker::DATA_TYPE_INTEGER, - IMocker::DATA_TYPE_NUMBER, - IMocker::DATA_TYPE_STRING, - IMocker::DATA_TYPE_BOOLEAN, - IMocker::DATA_TYPE_ARRAY, - IMocker::DATA_TYPE_OBJECT, - ])); - } - } - - /** - * Shortcut to mock integer type - * Equivalent to mockData(DATA_TYPE_INTEGER); - * - * @param string|null $dataFormat (optional) int32 or int64 - * @param number|null $minimum (optional) Default is 0 - * @param number|null $maximum (optional) Default is mt_getrandmax() - * @param bool|null $exclusiveMinimum (optional) Default is false - * @param bool|null $exclusiveMaximum (optional) Default is false - * - * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided - * - * @return int - */ - public function mockInteger( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - $dataFormat = is_string($dataFormat) ? strtolower($dataFormat) : $dataFormat; - switch ($dataFormat) { - case IMocker::DATA_FORMAT_INT32: - // -2147483647..2147483647 - $minimum = is_numeric($minimum) ? max($minimum, -2147483647) : -2147483647; - $maximum = is_numeric($maximum) ? min($maximum, 2147483647) : 2147483647; - break; - case IMocker::DATA_FORMAT_INT64: - // -9223372036854775807..9223372036854775807 - $minimum = is_numeric($minimum) ? max($minimum, -9223372036854775807) : -9223372036854775807; - $maximum = is_numeric($maximum) ? min($maximum, 9223372036854775807) : 9223372036854775807; - break; - default: - // do nothing, unsupported format - } - - return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 0); - } - - /** - * Shortcut to mock number type - * Equivalent to mockData(DATA_TYPE_NUMBER); - * - * @param string|null $dataFormat (optional) float or double - * @param number|null $minimum (optional) Default is 0 - * @param number|null $maximum (optional) Default is mt_getrandmax() - * @param bool|null $exclusiveMinimum (optional) Default is false - * @param bool|null $exclusiveMaximum (optional) Default is false - * - * @throws \InvalidArgumentException when $maximum less than $minimum or invalid arguments provided - * - * @return float - */ - public function mockNumber( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - return $this->getRandomNumber($minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum, 4); - } - - /** - * Shortcut to mock string type - * Equivalent to mockData(DATA_TYPE_STRING); - * - * @param string|null $dataFormat (optional) one of byte, binary, date, date-time, password - * @param int|null $minLength (optional) Default is 0 - * @param int|null $maxLength (optional) Default is 100 chars - * @param array $enum (optional) This array should have at least one element. - * Elements in the array should be unique. - * @param string|null $pattern (optional) This string should be a valid regular expression, according to the ECMA 262 regular expression dialect. - * Recall: regular expressions are not implicitly anchored. - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return string - */ - public function mockString( - $dataFormat = null, - $minLength = 0, - $maxLength = null, - $enum = null, - $pattern = null - ) { - $str = ''; - $getLoremIpsum = function ($length) { - return str_pad( - '', - $length, - 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. ', - \STR_PAD_RIGHT - ); - }; - $truncateOrPad = function ($text, $min = null, $max = null, $glue = '') { - if ($max !== null && mb_strlen($text) > $max) { - // truncate - $text = substr($text, 0, $max); - } elseif ($min !== null && mb_strlen($text) < $min) { - // pad - $text = str_pad('', $min, $text . $glue, \STR_PAD_RIGHT); - } - return $text; - }; - - if ($enum !== null) { - if ( - is_array($enum) === false - || empty($enum) - || count($enum) > count(array_unique($enum)) - ) { - throw new InvalidArgumentException('"enum" must be an array. This array should have at least one element. Elements in the array should be unique.'); - } - - // return random variant - return $enum[mt_rand(0, count($enum) - 1)]; - } - - if ($minLength !== 0 && $minLength !== null) { - if (is_int($minLength) === false) { - throw new InvalidArgumentException('"minLength" must be an integer'); - } elseif ($minLength < 0) { - throw new InvalidArgumentException('"minLength" must be greater than, or equal to, 0'); - } - } else { - $minLength = 0; - } - - if ($maxLength !== null) { - if (is_int($maxLength) === false) { - throw new InvalidArgumentException('"maxLength" must be an integer'); - } elseif ($maxLength < 0) { - throw new InvalidArgumentException('"maxLength" must be greater than, or equal to, 0'); - } - } else { - // since we don't need huge texts by default, lets cut them down to 100 chars - $maxLength = 100; - } - - if ($maxLength < $minLength) { - throw new InvalidArgumentException('"maxLength" value cannot be less than "minLength"'); - } - - switch ($dataFormat) { - case IMocker::DATA_FORMAT_BYTE: - case IMocker::DATA_FORMAT_BINARY: - // base64 encoded string - $inputLength = 1; - $str = base64_encode($getLoremIpsum($inputLength)); - while (mb_strlen($str) < $minLength) { - $inputLength++; - $str = base64_encode($getLoremIpsum($inputLength)); - } - - // base64 encoding produces strings devided by 4, so resulted string can exceed maxLength parameter - // I think truncated(invalid) base64 string is better than oversized, cause this data is fake anyway - $str = $truncateOrPad($str, null, $maxLength, '. '); - break; - case IMocker::DATA_FORMAT_DATE: - case IMocker::DATA_FORMAT_DATE_TIME: - // min unix timestamp is 0 and max is 2147483647 for 32bit systems which equals 2038-01-19 03:14:07 - $date = DateTime::createFromFormat('U', mt_rand(0, 2147483647)); - $str = ($dataFormat === IMocker::DATA_FORMAT_DATE) ? $date->format('Y-m-d') : $date->format('Y-m-d\TH:i:sP'); - - // truncate or pad datestring to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength, ' '); - break; - case IMocker::DATA_FORMAT_PASSWORD: - // use list of most popular passwords - $obviousPassList = [ - 'qwerty', - 'qwerty12345', - 'hello', - '12345', - '0000', - 'qwerty12345!', - 'qwertyuiop[]', - ]; - $str = $obviousPassList[mt_rand(0, count($obviousPassList) - 1)]; - - // truncate or pad password to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength); - break; - case IMocker::DATA_FORMAT_UUID: - // use php built-in uniqid function - $str = uniqid(); - - // truncate or pad password to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength); - break; - case IMocker::DATA_FORMAT_EMAIL: - // just for visionary purpose, not related to real persons - $fakeEmailList = [ - 'johndoe', - 'lhoswald', - 'ojsimpson', - 'mlking', - 'jfkennedy', - ]; - $str = $fakeEmailList[mt_rand(0, count($fakeEmailList) - 1)] . '@example.com'; - - // truncate or pad email to fit minLength and maxLength - $str = $truncateOrPad($str, $minLength, $maxLength); - break; - default: - $str = $getLoremIpsum(mt_rand($minLength, $maxLength)); - } - - return $str; - } - - /** - * Shortcut to mock boolean type - * Equivalent to mockData(DATA_TYPE_BOOLEAN); - * - * @return bool - */ - public function mockBoolean() - { - return (bool) mt_rand(0, 1); - } - - /** - * Shortcut to mock array type - * Equivalent to mockData(DATA_TYPE_ARRAY); - * - * @param object|array $items Object or assoc array of described items - * @param int|null $minItems (optional) An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this keyword. - * @param int|null $maxItems (optional) An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword - * @param bool|null $uniqueItems (optional) If it has boolean value true, the instance validates successfully if all of its elements are unique - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return array - */ - public function mockArray( - $items, - $minItems = 0, - $maxItems = null, - $uniqueItems = false - ) { - $arr = []; - $minSize = 0; - $maxSize = \PHP_INT_MAX; - - if ( - (is_array($items) === false && is_object($items) === false) - || (is_array($items) && array_key_exists('type', $items) === false) - || (is_object($items) && isset($items->type) === false) - ) { - new InvalidArgumentException('"items" must be object or assoc array with "type" key'); - } - - if ($minItems !== null) { - if (is_integer($minItems) === false || $minItems < 0) { - throw new InvalidArgumentException('"mitItems" must be an integer. This integer must be greater than, or equal to, 0'); - } - $minSize = $minItems; - } - - if ($maxItems !== null) { - if (is_integer($maxItems) === false || $maxItems < 0) { - throw new InvalidArgumentException('"maxItems" must be an integer. This integer must be greater than, or equal to, 0.'); - } - if ($maxItems < $minItems) { - throw new InvalidArgumentException('"maxItems" value cannot be less than "minItems"'); - } - $maxSize = $maxItems; - } - - $options = $this->extractSchemaProperties($items); - $dataType = $options['type']; - $dataFormat = $options['format'] ?? null; - $ref = $options['$ref'] ?? null; - - // always generate smallest possible array to avoid huge JSON responses - $arrSize = ($maxSize < 1) ? $maxSize : max($minSize, 1); - while (count($arr) < $arrSize) { - $data = $this->mockFromRef($ref); - $arr[] = ($data) ? $data : $this->mock($dataType, $dataFormat, $options); - } - return $arr; - } - - /** - * Shortcut to mock object type. - * Equivalent to mockData(DATA_TYPE_OBJECT); - * - * @param object|array $properties Object or array of described properties - * @param int|null $minProperties (optional) An object instance is valid against "minProperties" if its number of properties is greater than, or equal to, the value of this keyword. - * @param int|null $maxProperties (optional) An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword. - * @param bool|object|array|null $additionalProperties (optional) If "additionalProperties" is true, validation always succeeds. - * If "additionalProperties" is false, validation succeeds only if the instance is an object and all properties on the instance were covered by "properties" and/or "patternProperties". - * If "additionalProperties" is an object, validate the value as a schema to all of the properties that weren't validated by "properties" nor "patternProperties". - * @param array|null $required (optional) This array MUST have at least one element. Elements of this array must be strings, and MUST be unique. - * An object instance is valid if its property set contains all elements in this array value. - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return object - */ - public function mockObject( - $properties, - $minProperties = 0, - $maxProperties = null, - $additionalProperties = null, - $required = null - ) { - $obj = new StdClass(); - - if (is_object($properties) === false && is_array($properties) === false) { - throw new InvalidArgumentException('The value of "properties" must be an array or object'); - } - - foreach ($properties as $propName => $propValue) { - if (is_object($propValue) === false && is_array($propValue) === false) { - throw new InvalidArgumentException('Each value of "properties" must be an array or object'); - } - } - - if ($minProperties !== null) { - if (is_integer($minProperties) === false || $minProperties < 0) { - throw new InvalidArgumentException('"minProperties" must be an integer. This integer must be greater than, or equal to, 0'); - } - } - - if ($maxProperties !== null) { - if (is_integer($maxProperties) === false || $maxProperties < 0) { - throw new InvalidArgumentException('"maxProperties" must be an integer. This integer must be greater than, or equal to, 0.'); - } - if ($maxProperties < $minProperties) { - throw new InvalidArgumentException('"maxProperties" value cannot be less than "minProperties"'); - } - } - - if ($additionalProperties !== null) { - if (is_bool($additionalProperties) === false && is_object($additionalProperties) === false && is_array($additionalProperties) === false) { - throw new InvalidArgumentException('The value of "additionalProperties" must be a boolean or object or array.'); - } - } - - if ($required !== null) { - if ( - is_array($required) === false - || count($required) > count(array_unique($required)) - ) { - throw new InvalidArgumentException('The value of "required" must be an array. Elements of this array must be unique.'); - } - foreach ($required as $requiredPropName) { - if (is_string($requiredPropName) === false) { - throw new InvalidArgumentException('Elements of "required" array must be strings'); - } - } - } - - foreach ($properties as $propName => $propValue) { - $options = $this->extractSchemaProperties($propValue); - $dataType = $options['type']; - $dataFormat = $options['format'] ?? null; - $ref = $options['$ref'] ?? null; - $data = $this->mockFromRef($ref); - $obj->$propName = ($data) ? $data : $this->mock($dataType, $dataFormat, $options); - } - - return $obj; - } - - /** - * Mocks OpenApi Data from schema. - * - * @param array|object $schema OpenAPI schema - * - * @throws \InvalidArgumentException when invalid arguments passed - * - * @return mixed - */ - public function mockFromSchema($schema) - { - $props = $this->extractSchemaProperties($schema); - if (array_key_exists('$ref', $props) && !empty($props['$ref'])) { - return $this->mockFromRef($props['$ref']); - } elseif ($props['type'] === null) { - throw new InvalidArgumentException('"schema" must be object or assoc array with "type" property'); - } - return $this->mock($props['type'], $props['format'], $props); - } - - /** - * Mock data by referenced schema. - * TODO: this method will return model instance, not an StdClass - * - * @param string|null $ref Ref to model, eg. #/components/schemas/User - * - * @return mixed - */ - public function mockFromRef($ref) - { - $data = null; - if (is_string($ref) && !empty($ref)) { - $refName = static::getSimpleRef($ref); - $modelName = static::toModelName($refName); - $modelClass = 'OpenAPIServer\Model\\' . $modelName; - if (!class_exists($modelClass) || !method_exists($modelClass, 'getOpenApiSchema')) { - throw new InvalidArgumentException(sprintf( - 'Model %s not found or method %s doesn\'t exist', - $modelClass, - $modelClass . '::getOpenApiSchema' - )); - } - $data = $this->mockFromSchema($modelClass::getOpenApiSchema(true)); - } - - return $data; - } - - /** - * @internal Extract OAS properties from array or object. - * @codeCoverageIgnore - * - * @param array|object $val Processed array or object - * - * @return array - */ - private function extractSchemaProperties($val) - { - $props = [ - 'type' => null, - 'format' => null, - ]; - foreach ( - [ - 'type', - 'format', - 'minimum', - 'maximum', - 'exclusiveMinimum', - 'exclusiveMaximum', - 'minLength', - 'maxLength', - 'pattern', - 'enum', - 'items', - 'minItems', - 'maxItems', - 'uniqueItems', - 'properties', - 'minProperties', - 'maxProperties', - 'additionalProperties', - 'required', - 'example', - '$ref', - ] as $propName - ) { - if (is_array($val) && array_key_exists($propName, $val)) { - $props[$propName] = $val[$propName]; - } elseif (is_object($val) && isset($val->$propName)) { - $props[$propName] = $val->$propName; - } - } - return $props; - } - - /** - * @internal - * @codeCoverageIgnore - * - * @return float|int - */ - protected function getRandomNumber( - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $maxDecimals = 4 - ) { - $min = 0; - $max = mt_getrandmax(); - - if ($minimum !== null) { - if (is_numeric($minimum) === false) { - throw new InvalidArgumentException('"minimum" must be a number'); - } - $min = $minimum; - } - - if ($maximum !== null) { - if (is_numeric($maximum) === false) { - throw new InvalidArgumentException('"maximum" must be a number'); - } - $max = $maximum; - } - - if ($exclusiveMinimum !== false) { - if (is_bool($exclusiveMinimum) === false) { - throw new InvalidArgumentException('"exclusiveMinimum" must be a boolean'); - } elseif ($minimum === null) { - throw new InvalidArgumentException('If "exclusiveMinimum" is present, "minimum" must also be present'); - } - $min += 1; - } - - if ($exclusiveMaximum !== false) { - if (is_bool($exclusiveMaximum) === false) { - throw new InvalidArgumentException('"exclusiveMaximum" must be a boolean'); - } elseif ($maximum === null) { - throw new InvalidArgumentException('If "exclusiveMaximum" is present, "maximum" must also be present'); - } - $max -= 1; - } - - if ($max < $min) { - throw new InvalidArgumentException('"maximum" value cannot be less than "minimum"'); - } - - if ($maxDecimals > 0) { - return round($min + mt_rand() / mt_getrandmax() * ($max - $min), $maxDecimals); - } - return mt_rand((int) $min, (int) $max); - } -} diff --git a/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerInterface.php b/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerInterface.php deleted file mode 100644 index 84a9f253840..00000000000 --- a/samples/server/petstore/php-slim4/lib/Mock/OpenApiDataMockerInterface.php +++ /dev/null @@ -1,251 +0,0 @@ -hasHeader('X-OpenAPIServer-Mock') - * && $request->header('X-OpenAPIServer-Mock')[0] === 'ping' - * ) { - * return $responses[array_key_first($responses)]; - * } - * return false; - * }; - * @param callable|null $afterCallback After callback. - * Function must return response instance. - * @example $afterCallback = function (ServerRequestInterface $request, ResponseInterface $response) { - * // mark mocked response to distinguish real and fake responses - * return $response->withHeader('X-OpenAPIServer-Mock', 'pong'); - * }; - */ - public function __construct( - OpenApiDataMockerInterface $mocker, - array $responses, - $getMockResponseCallback = null, - $afterCallback = null - ) { - $this->mocker = $mocker; - $this->responses = $responses; - if (is_callable($getMockResponseCallback)) { - $this->getMockResponseCallback = $getMockResponseCallback; - } elseif ($getMockResponseCallback !== null) { - // wrong argument type - throw new InvalidArgumentException('\$getMockResponseCallback must be closure or null'); - } - - if (is_callable($afterCallback)) { - $this->afterCallback = $afterCallback; - } elseif ($afterCallback !== null) { - // wrong argument type - throw new InvalidArgumentException('\$afterCallback must be closure or null'); - } - } - - /** - * Parse incoming JSON input into a native PHP format - * - * @param ServerRequestInterface $request HTTP request - * @param RequestHandlerInterface $handler Request handler - * - * @return ResponseInterface HTTP response - */ - public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface - { - $customCallback = $this->getMockResponseCallback; - $customAfterCallback = $this->afterCallback; - $mockedResponse = (is_callable($customCallback)) ? $customCallback($request, $this->responses) : null; - if ( - is_array($mockedResponse) - && array_key_exists('code', $mockedResponse) - && array_key_exists('jsonSchema', $mockedResponse) - ) { - // response schema succesfully selected, we can mock it now - $statusCode = ($mockedResponse['code'] === 0) ? 200 : $mockedResponse['code']; - $contentType = '*/*'; - $response = AppFactory::determineResponseFactory()->createResponse($statusCode); - $responseSchema = json_decode($mockedResponse['jsonSchema'], true); - - if (is_array($responseSchema) && array_key_exists('headers', $responseSchema)) { - // response schema contains headers definitions, apply them one by one - foreach ($responseSchema['headers'] as $headerName => $headerDefinition) { - $response = $response->withHeader($headerName, $this->mocker->mockFromSchema($headerDefinition['schema'])); - } - } - - if ( - is_array($responseSchema) - && array_key_exists('content', $responseSchema) - && !empty($responseSchema['content']) - ) { - // response schema contains body definition - $responseContentSchema = null; - foreach ($responseSchema['content'] as $schemaContentType => $schemaDefinition) { - // we can respond in JSON format when any(*/*) content-type allowed - // or JSON(application/json) content-type specifically defined - if ( - $schemaContentType === '*/*' - || strtolower(substr($schemaContentType, 0, 16)) === 'application/json' - ) { - $contentType = 'application/json'; - $responseContentSchema = $schemaDefinition['schema']; - } - } - - if ($contentType === 'application/json') { - $responseBody = $this->mocker->mockFromSchema($responseContentSchema); - $response->getBody()->write(json_encode($responseBody)); - } else { - // notify developer that only application/json response supported so far - $response->getBody()->write('Mock feature supports only "application/json" content-type!'); - } - } - - // after callback applied only when mocked response schema has been selected - if (is_callable($customAfterCallback)) { - $response = $customAfterCallback($request, $response); - } - - // no reason to execute following middlewares (auth, validation etc.) - // return mocked response and end connection - return $response - ->withHeader('Content-Type', $contentType); - } - - // no response selected, mock feature disabled - // execute following middlewares - return $handler->handle($request); - } -} diff --git a/samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesAnyType.php b/samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesAnyType.php deleted file mode 100644 index 2a21dc42be0..00000000000 --- a/samples/server/petstore/php-slim4/lib/Model/AdditionalPropertiesAnyType.php +++ /dev/null @@ -1,64 +0,0 @@ -=", "$" ] - }, - "array_enum" : { - "type" : "array", - "items" : { - "type" : "string", - "enum" : [ "fish", "crab" ] - } - } - } -} -SCHEMA; - - /** @var string $justSymbol */ - private $justSymbol; - - /** @var string[] $arrayEnum */ - private $arrayEnum; - - /** - * Returns model schema. - * - * @param bool $assoc When TRUE, returned objects will be converted into associative arrays. Default FALSE. - * - * @return array - */ - public static function getOpenApiSchema($assoc = false) - { - return json_decode(static::MODEL_SCHEMA, $assoc); - } -} diff --git a/samples/server/petstore/php-slim4/lib/Model/EnumClass.php b/samples/server/petstore/php-slim4/lib/Model/EnumClass.php deleted file mode 100644 index 3a40149f684..00000000000 --- a/samples/server/petstore/php-slim4/lib/Model/EnumClass.php +++ /dev/null @@ -1,54 +0,0 @@ - 'PATCH', - 'basePathWithoutHost' => '/v2', - 'path' => '/another-fake/dummy', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractAnotherFakeApi', - 'userClassname' => 'AnotherFakeApi', - 'operationId' => 'call123TestSpecialTags', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Client" - } - } - } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/create_xml_item', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'createXmlItem', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/outer/boolean', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'fakeOuterBooleanSerialize', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'Output boolean', - 'jsonSchema' => '{ - "description" : "Output boolean", - "content" : { - "*/*" : { - "schema" : { - "$ref" : "#/components/schemas/OuterBoolean" - } - } - } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/outer/composite', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'fakeOuterCompositeSerialize', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'Output composite', - 'jsonSchema' => '{ - "description" : "Output composite", - "content" : { - "*/*" : { - "schema" : { - "$ref" : "#/components/schemas/OuterComposite" - } - } - } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/outer/number', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'fakeOuterNumberSerialize', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'Output number', - 'jsonSchema' => '{ - "description" : "Output number", - "content" : { - "*/*" : { - "schema" : { - "$ref" : "#/components/schemas/OuterNumber" - } - } - } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/outer/string', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'fakeOuterStringSerialize', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'Output string', - 'jsonSchema' => '{ - "description" : "Output string", - "content" : { - "*/*" : { - "schema" : { - "$ref" : "#/components/schemas/OuterString" - } - } - } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'PUT', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/body-with-file-schema', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testBodyWithFileSchema', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'Success', - 'jsonSchema' => '{ - "description" : "Success", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'PUT', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/body-with-query-params', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testBodyWithQueryParams', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'Success', - 'jsonSchema' => '{ - "description" : "Success", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'PATCH', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testClientModel', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Client" - } - } - } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testEndpointParameters', - 'responses' => [ - '400' => [ - 'code' => 400, - 'message' => 'Invalid username supplied', - 'jsonSchema' => '{ - "description" : "Invalid username supplied", - "content" : { } -}', - ], - '404' => [ - 'code' => 404, - 'message' => 'User not found', - 'jsonSchema' => '{ - "description" : "User not found", - "content" : { } -}', - ], - ], - 'authMethods' => [ - // http security schema named 'http_basic_test' - [ - 'type' => 'http', - 'isBasic' => true, - 'isBearer' => false, - 'isApiKey' => false, - 'isOAuth' => false, - ], - ], - ], - [ - 'httpMethod' => 'GET', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testEnumParameters', - 'responses' => [ - '400' => [ - 'code' => 400, - 'message' => 'Invalid request', - 'jsonSchema' => '{ - "description" : "Invalid request", - "content" : { } -}', - ], - '404' => [ - 'code' => 404, - 'message' => 'Not found', - 'jsonSchema' => '{ - "description" : "Not found", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'DELETE', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testGroupParameters', - 'responses' => [ - '400' => [ - 'code' => 400, - 'message' => 'Someting wrong', - 'jsonSchema' => '{ - "description" : "Someting wrong", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/inline-additionalProperties', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testInlineAdditionalProperties', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'GET', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/jsonFormData', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testJsonFormData', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'PUT', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/test-query-paramters', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeApi', - 'userClassname' => 'FakeApi', - 'operationId' => 'testQueryParameterCollectionFormat', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'Success', - 'jsonSchema' => '{ - "description" : "Success", - "content" : { } -}', - ], - ], - 'authMethods' => [ - ], - ], - [ - 'httpMethod' => 'PATCH', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake_classname_test', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractFakeClassnameTags123Api', - 'userClassname' => 'FakeClassnameTags123Api', - 'operationId' => 'testClassname', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/Client" - } - } - } -}', - ], - ], - 'authMethods' => [ - // apiKey security schema named 'api_key_query' - [ - 'type' => 'apiKey', - 'isBasic' => false, - 'isBearer' => false, - 'isApiKey' => true, - 'isOAuth' => false, - 'keyParamName' => 'api_key_query', - 'isKeyInHeader' => false, - 'isKeyInQuery' => true, - 'isKeyInCookie' => false, - ], - ], - ], [ 'httpMethod' => 'POST', 'basePathWithoutHost' => '/v2', @@ -474,19 +61,25 @@ class SlimRouter 'operationId' => 'addPet', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", - "content" : { } + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + } }', ], '405' => [ - 'code' => 405, - 'message' => 'Invalid input', 'jsonSchema' => '{ - "description" : "Invalid input", - "content" : { } + "description" : "Invalid input" }', ], ], @@ -515,8 +108,6 @@ class SlimRouter 'operationId' => 'findPetsByStatus', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { @@ -540,11 +131,8 @@ class SlimRouter }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid status value', 'jsonSchema' => '{ - "description" : "Invalid status value", - "content" : { } + "description" : "Invalid status value" }', ], ], @@ -557,7 +145,6 @@ class SlimRouter 'isApiKey' => false, 'isOAuth' => true, 'scopes' => [ - 'write:pets', // modify pets in your account 'read:pets', // read your pets ], ], @@ -573,14 +160,11 @@ class SlimRouter 'operationId' => 'findPetsByTags', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { "application/xml" : { "schema" : { - "uniqueItems" : true, "type" : "array", "items" : { "$ref" : "#/components/schemas/Pet" @@ -589,7 +173,6 @@ class SlimRouter }, "application/json" : { "schema" : { - "uniqueItems" : true, "type" : "array", "items" : { "$ref" : "#/components/schemas/Pet" @@ -600,11 +183,8 @@ class SlimRouter }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid tag value', 'jsonSchema' => '{ - "description" : "Invalid tag value", - "content" : { } + "description" : "Invalid tag value" }', ], ], @@ -617,7 +197,6 @@ class SlimRouter 'isApiKey' => false, 'isOAuth' => true, 'scopes' => [ - 'write:pets', // modify pets in your account 'read:pets', // read your pets ], ], @@ -633,35 +212,35 @@ class SlimRouter 'operationId' => 'updatePet', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", - "content" : { } + "content" : { + "application/xml" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + }, + "application/json" : { + "schema" : { + "$ref" : "#/components/schemas/Pet" + } + } + } }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid ID supplied', 'jsonSchema' => '{ - "description" : "Invalid ID supplied", - "content" : { } + "description" : "Invalid ID supplied" }', ], '404' => [ - 'code' => 404, - 'message' => 'Pet not found', 'jsonSchema' => '{ - "description" : "Pet not found", - "content" : { } + "description" : "Pet not found" }', ], '405' => [ - 'code' => 405, - 'message' => 'Validation exception', 'jsonSchema' => '{ - "description" : "Validation exception", - "content" : { } + "description" : "Validation exception" }', ], ], @@ -689,20 +268,9 @@ class SlimRouter 'userClassname' => 'PetApi', 'operationId' => 'deletePet', 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } -}', - ], '400' => [ - 'code' => 400, - 'message' => 'Invalid pet value', 'jsonSchema' => '{ - "description" : "Invalid pet value", - "content" : { } + "description" : "Invalid pet value" }', ], ], @@ -731,8 +299,6 @@ class SlimRouter 'operationId' => 'getPetById', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { @@ -750,19 +316,13 @@ class SlimRouter }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid ID supplied', 'jsonSchema' => '{ - "description" : "Invalid ID supplied", - "content" : { } + "description" : "Invalid ID supplied" }', ], '404' => [ - 'code' => 404, - 'message' => 'Pet not found', 'jsonSchema' => '{ - "description" : "Pet not found", - "content" : { } + "description" : "Pet not found" }', ], ], @@ -791,11 +351,8 @@ class SlimRouter 'operationId' => 'updatePetWithForm', 'responses' => [ '405' => [ - 'code' => 405, - 'message' => 'Invalid input', 'jsonSchema' => '{ - "description" : "Invalid input", - "content" : { } + "description" : "Invalid input" }', ], ], @@ -824,47 +381,6 @@ class SlimRouter 'operationId' => 'uploadFile', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', - 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { - "application/json" : { - "schema" : { - "$ref" : "#/components/schemas/ApiResponse" - } - } - } -}', - ], - ], - 'authMethods' => [ - // oauth2 security schema named 'petstore_auth' - [ - 'type' => 'oauth2', - 'isBasic' => false, - 'isBearer' => false, - 'isApiKey' => false, - 'isOAuth' => true, - 'scopes' => [ - 'write:pets', // modify pets in your account - 'read:pets', // read your pets - ], - ], - ], - ], - [ - 'httpMethod' => 'POST', - 'basePathWithoutHost' => '/v2', - 'path' => '/fake/{petId}/uploadImageWithRequiredFile', - 'apiPackage' => 'OpenAPIServer\Api', - 'classname' => 'AbstractPetApi', - 'userClassname' => 'PetApi', - 'operationId' => 'uploadFileWithRequiredFile', - 'responses' => [ - '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { @@ -902,8 +418,6 @@ class SlimRouter 'operationId' => 'getInventory', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { @@ -945,8 +459,6 @@ class SlimRouter 'operationId' => 'placeOrder', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { @@ -964,11 +476,8 @@ class SlimRouter }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid Order', 'jsonSchema' => '{ - "description" : "Invalid Order", - "content" : { } + "description" : "Invalid Order" }', ], ], @@ -978,26 +487,20 @@ class SlimRouter [ 'httpMethod' => 'DELETE', 'basePathWithoutHost' => '/v2', - 'path' => '/store/order/{order_id}', + 'path' => '/store/order/{orderId}', 'apiPackage' => 'OpenAPIServer\Api', 'classname' => 'AbstractStoreApi', 'userClassname' => 'StoreApi', 'operationId' => 'deleteOrder', 'responses' => [ '400' => [ - 'code' => 400, - 'message' => 'Invalid ID supplied', 'jsonSchema' => '{ - "description" : "Invalid ID supplied", - "content" : { } + "description" : "Invalid ID supplied" }', ], '404' => [ - 'code' => 404, - 'message' => 'Order not found', 'jsonSchema' => '{ - "description" : "Order not found", - "content" : { } + "description" : "Order not found" }', ], ], @@ -1007,15 +510,13 @@ class SlimRouter [ 'httpMethod' => 'GET', 'basePathWithoutHost' => '/v2', - 'path' => '/store/order/{order_id}', + 'path' => '/store/order/{orderId}', 'apiPackage' => 'OpenAPIServer\Api', 'classname' => 'AbstractStoreApi', 'userClassname' => 'StoreApi', 'operationId' => 'getOrderById', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { @@ -1033,19 +534,13 @@ class SlimRouter }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid ID supplied', 'jsonSchema' => '{ - "description" : "Invalid ID supplied", - "content" : { } + "description" : "Invalid ID supplied" }', ], '404' => [ - 'code' => 404, - 'message' => 'Order not found', 'jsonSchema' => '{ - "description" : "Order not found", - "content" : { } + "description" : "Order not found" }', ], ], @@ -1062,15 +557,24 @@ class SlimRouter 'operationId' => 'createUser', 'responses' => [ 'default' => [ - 'code' => 0, - 'message' => 'successful operation', 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } + "description" : "successful operation" }', ], ], 'authMethods' => [ + // apiKey security schema named 'api_key' + [ + 'type' => 'apiKey', + 'isBasic' => false, + 'isBearer' => false, + 'isApiKey' => true, + 'isOAuth' => false, + 'keyParamName' => 'api_key', + 'isKeyInHeader' => true, + 'isKeyInQuery' => false, + 'isKeyInCookie' => false, + ], ], ], [ @@ -1083,15 +587,24 @@ class SlimRouter 'operationId' => 'createUsersWithArrayInput', 'responses' => [ 'default' => [ - 'code' => 0, - 'message' => 'successful operation', 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } + "description" : "successful operation" }', ], ], 'authMethods' => [ + // apiKey security schema named 'api_key' + [ + 'type' => 'apiKey', + 'isBasic' => false, + 'isBearer' => false, + 'isApiKey' => true, + 'isOAuth' => false, + 'keyParamName' => 'api_key', + 'isKeyInHeader' => true, + 'isKeyInQuery' => false, + 'isKeyInCookie' => false, + ], ], ], [ @@ -1104,15 +617,24 @@ class SlimRouter 'operationId' => 'createUsersWithListInput', 'responses' => [ 'default' => [ - 'code' => 0, - 'message' => 'successful operation', 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } + "description" : "successful operation" }', ], ], 'authMethods' => [ + // apiKey security schema named 'api_key' + [ + 'type' => 'apiKey', + 'isBasic' => false, + 'isBearer' => false, + 'isApiKey' => true, + 'isOAuth' => false, + 'keyParamName' => 'api_key', + 'isKeyInHeader' => true, + 'isKeyInQuery' => false, + 'isKeyInCookie' => false, + ], ], ], [ @@ -1125,20 +647,31 @@ class SlimRouter 'operationId' => 'loginUser', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "headers" : { + "Set-Cookie" : { + "description" : "Cookie authentication key for use with the `api_key` apiKey authentication.", + "style" : "simple", + "explode" : false, + "schema" : { + "type" : "string", + "example" : "AUTH_KEY=abcde12345; Path=/; HttpOnly" + } + }, "X-Rate-Limit" : { "description" : "calls per hour allowed by the user", + "style" : "simple", + "explode" : false, "schema" : { "type" : "integer", "format" : "int32" } }, "X-Expires-After" : { - "description" : "date in UTC when token expires", + "description" : "date in UTC when toekn expires", + "style" : "simple", + "explode" : false, "schema" : { "type" : "string", "format" : "date-time" @@ -1160,11 +693,8 @@ class SlimRouter }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid username/password supplied', 'jsonSchema' => '{ - "description" : "Invalid username/password supplied", - "content" : { } + "description" : "Invalid username/password supplied" }', ], ], @@ -1181,15 +711,24 @@ class SlimRouter 'operationId' => 'logoutUser', 'responses' => [ 'default' => [ - 'code' => 0, - 'message' => 'successful operation', 'jsonSchema' => '{ - "description" : "successful operation", - "content" : { } + "description" : "successful operation" }', ], ], 'authMethods' => [ + // apiKey security schema named 'api_key' + [ + 'type' => 'apiKey', + 'isBasic' => false, + 'isBearer' => false, + 'isApiKey' => true, + 'isOAuth' => false, + 'keyParamName' => 'api_key', + 'isKeyInHeader' => true, + 'isKeyInQuery' => false, + 'isKeyInCookie' => false, + ], ], ], [ @@ -1202,23 +741,29 @@ class SlimRouter 'operationId' => 'deleteUser', 'responses' => [ '400' => [ - 'code' => 400, - 'message' => 'Invalid username supplied', 'jsonSchema' => '{ - "description" : "Invalid username supplied", - "content" : { } + "description" : "Invalid username supplied" }', ], '404' => [ - 'code' => 404, - 'message' => 'User not found', 'jsonSchema' => '{ - "description" : "User not found", - "content" : { } + "description" : "User not found" }', ], ], 'authMethods' => [ + // apiKey security schema named 'api_key' + [ + 'type' => 'apiKey', + 'isBasic' => false, + 'isBearer' => false, + 'isApiKey' => true, + 'isOAuth' => false, + 'keyParamName' => 'api_key', + 'isKeyInHeader' => true, + 'isKeyInQuery' => false, + 'isKeyInCookie' => false, + ], ], ], [ @@ -1231,8 +776,6 @@ class SlimRouter 'operationId' => 'getUserByName', 'responses' => [ '200' => [ - 'code' => 200, - 'message' => 'successful operation', 'jsonSchema' => '{ "description" : "successful operation", "content" : { @@ -1250,19 +793,13 @@ class SlimRouter }', ], '400' => [ - 'code' => 400, - 'message' => 'Invalid username supplied', 'jsonSchema' => '{ - "description" : "Invalid username supplied", - "content" : { } + "description" : "Invalid username supplied" }', ], '404' => [ - 'code' => 404, - 'message' => 'User not found', 'jsonSchema' => '{ - "description" : "User not found", - "content" : { } + "description" : "User not found" }', ], ], @@ -1279,23 +816,29 @@ class SlimRouter 'operationId' => 'updateUser', 'responses' => [ '400' => [ - 'code' => 400, - 'message' => 'Invalid user supplied', 'jsonSchema' => '{ - "description" : "Invalid user supplied", - "content" : { } + "description" : "Invalid user supplied" }', ], '404' => [ - 'code' => 404, - 'message' => 'User not found', 'jsonSchema' => '{ - "description" : "User not found", - "content" : { } + "description" : "User not found" }', ], ], 'authMethods' => [ + // apiKey security schema named 'api_key' + [ + 'type' => 'apiKey', + 'isBasic' => false, + 'isBearer' => false, + 'isApiKey' => true, + 'isOAuth' => false, + 'keyParamName' => 'api_key', + 'isKeyInHeader' => true, + 'isKeyInQuery' => false, + 'isKeyInCookie' => false, + ], ], ], ]; @@ -1338,7 +881,8 @@ class SlimRouter // mocker options $mockerOptions = $this->getSetting($settings, 'mockerOptions', null); $dataMocker = $mockerOptions['dataMocker'] ?? new OpenApiDataMocker(); - $getMockResponseCallback = $mockerOptions['getMockResponseCallback'] ?? null; + $responseFactory = new ResponseFactory(); + $getMockStatusCodeCallback = $mockerOptions['getMockStatusCodeCallback'] ?? null; $mockAfterCallback = $mockerOptions['afterCallback'] ?? null; foreach ($this->operations as $operation) { @@ -1404,8 +948,11 @@ class SlimRouter } } - if (is_callable($getMockResponseCallback)) { - $middlewares[] = new OpenApiDataMockerMiddleware($dataMocker, $operation['responses'], $getMockResponseCallback, $mockAfterCallback); + if (is_callable($getMockStatusCodeCallback)) { + $mockSchemaResponses = array_map(function ($item) { + return json_decode($item['jsonSchema'], true); + }, $operation['responses']); + $middlewares[] = new OpenApiDataMockerRouteMiddleware($dataMocker, $mockSchemaResponses, $responseFactory, $getMockStatusCodeCallback, $mockAfterCallback); } $this->addRoute( diff --git a/samples/server/petstore/php-slim4/lib/Utils/ModelUtilsTrait.php b/samples/server/petstore/php-slim4/lib/Utils/ModelUtilsTrait.php deleted file mode 100644 index 5eb771b9484..00000000000 --- a/samples/server/petstore/php-slim4/lib/Utils/ModelUtilsTrait.php +++ /dev/null @@ -1,120 +0,0 @@ - ModelReturn (after camelize) - } - - // model name starts with number - if (preg_match('/^\d.*/', $name) === 1) { - $name = 'model_' . $name; // e.g. 200Response => Model200Response (after camelize) - } - - // add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime) - if (preg_match('/^\\\\.*/', $name) !== 1) { - if (is_string($modelNamePrefix) && !empty($modelNamePrefix)) { - $name = $modelNamePrefix . '_' . $name; - } - - if (is_string($modelNameSuffix) && !empty($modelNameSuffix)) { - $name = $name . '_' . $modelNameSuffix; - } - } - - // camelize the model name - // phone_number => PhoneNumber - return self::camelize($name); - } -} diff --git a/samples/server/petstore/php-slim4/lib/Utils/StringUtilsTrait.php b/samples/server/petstore/php-slim4/lib/Utils/StringUtilsTrait.php deleted file mode 100644 index a56088aeb3d..00000000000 --- a/samples/server/petstore/php-slim4/lib/Utils/StringUtilsTrait.php +++ /dev/null @@ -1,129 +0,0 @@ - 0) { - $str .= strtoupper(substr($z, 0, 1)) . substr($z, 1); - } - } - $word = $str; - - // Uppercase the class name. - $p = '/(\.?)(\w)([^\.]*)$/'; - $word = preg_replace_callback($p, function ($matches) { - $rep = $matches[1] . strtoupper($matches[2]) . $matches[3]; - $rep = preg_replace('/\$/', '\\\$', $rep); - return $rep; - }, $word); - - // Remove all underscores (underscore_case to camelCase) - $p = '/(_)(.)/'; - while (preg_match($p, $word, $matches) === 1) { - $original = $matches[2][0]; - $upperCase = strtoupper($original); - if ($original === $upperCase) { - $word = preg_replace($p, '$2', $word); - } else { - $word = preg_replace($p, $upperCase, $word); - } - } - - // Remove all hyphens (hyphen-case to camelCase) - $p = '/(-)(.)/'; - while (preg_match($p, $word, $matches) === 1) { - $upperCase = strtoupper($matches[2][0]); - $word = preg_replace($p, $upperCase, $word); - } - - if ($lowercaseFirstLetter === true && strlen($word) > 0) { - $i = 0; - $charAt = substr($word, $i, 1); - while ( - $i + 1 < strlen($word) - && !( - ($charAt >= 'a' && $charAt <= 'z') - || ($charAt >= 'A' && $charAt <= 'Z') - ) - ) { - $i++; - $charAt = substr($word, $i, 1); - } - $i++; - $word = strtolower(substr($word, 0, $i)) . substr($word, $i); - } - - // remove all underscore - $word = str_replace('_', '', $word); - - return $word; - } - - /** - * Checks whether string is reserved php keyword. - * This is recreated method of @link modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java class. - * - * @param string $word Checked string - * - * @return bool - */ - public static function isReservedWord($word) - { - if (is_string($word) === false) { - return false; - } - // __halt_compiler is ommited because class names with underscores not allowed anyway - return in_array( - strtolower($word), - ['abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor'] - ); - } -} diff --git a/samples/server/petstore/php-slim4/phpunit.xml.dist b/samples/server/petstore/php-slim4/phpunit.xml.dist index 6af1442ee65..3efb4b45f4a 100644 --- a/samples/server/petstore/php-slim4/phpunit.xml.dist +++ b/samples/server/petstore/php-slim4/phpunit.xml.dist @@ -15,12 +15,14 @@ ./test/Api + ./test/BaseModelTest.php ./test/Model ./lib/Api + ./lib/BaseModel.php ./lib/Model diff --git a/samples/server/petstore/php-slim4/test/Api/AnotherFakeApiTest.php b/samples/server/petstore/php-slim4/test/Api/AnotherFakeApiTest.php deleted file mode 100644 index 14b6cf86da4..00000000000 --- a/samples/server/petstore/php-slim4/test/Api/AnotherFakeApiTest.php +++ /dev/null @@ -1,81 +0,0 @@ -markTestIncomplete( - 'Test of "call123TestSpecialTags" method has not been implemented yet.' - ); - } -} diff --git a/samples/server/petstore/php-slim4/test/Api/FakeApiTest.php b/samples/server/petstore/php-slim4/test/Api/FakeApiTest.php deleted file mode 100644 index edd9084c902..00000000000 --- a/samples/server/petstore/php-slim4/test/Api/FakeApiTest.php +++ /dev/null @@ -1,263 +0,0 @@ -markTestIncomplete( - 'Test of "createXmlItem" method has not been implemented yet.' - ); - } - - /** - * Test case for fakeOuterBooleanSerialize - * - * . - * - * @covers ::fakeOuterBooleanSerialize - */ - public function testFakeOuterBooleanSerialize() - { - $this->markTestIncomplete( - 'Test of "fakeOuterBooleanSerialize" method has not been implemented yet.' - ); - } - - /** - * Test case for fakeOuterCompositeSerialize - * - * . - * - * @covers ::fakeOuterCompositeSerialize - */ - public function testFakeOuterCompositeSerialize() - { - $this->markTestIncomplete( - 'Test of "fakeOuterCompositeSerialize" method has not been implemented yet.' - ); - } - - /** - * Test case for fakeOuterNumberSerialize - * - * . - * - * @covers ::fakeOuterNumberSerialize - */ - public function testFakeOuterNumberSerialize() - { - $this->markTestIncomplete( - 'Test of "fakeOuterNumberSerialize" method has not been implemented yet.' - ); - } - - /** - * Test case for fakeOuterStringSerialize - * - * . - * - * @covers ::fakeOuterStringSerialize - */ - public function testFakeOuterStringSerialize() - { - $this->markTestIncomplete( - 'Test of "fakeOuterStringSerialize" method has not been implemented yet.' - ); - } - - /** - * Test case for testBodyWithFileSchema - * - * . - * - * @covers ::testBodyWithFileSchema - */ - public function testTestBodyWithFileSchema() - { - $this->markTestIncomplete( - 'Test of "testBodyWithFileSchema" method has not been implemented yet.' - ); - } - - /** - * Test case for testBodyWithQueryParams - * - * . - * - * @covers ::testBodyWithQueryParams - */ - public function testTestBodyWithQueryParams() - { - $this->markTestIncomplete( - 'Test of "testBodyWithQueryParams" method has not been implemented yet.' - ); - } - - /** - * Test case for testClientModel - * - * To test \"client\" model. - * - * @covers ::testClientModel - */ - public function testTestClientModel() - { - $this->markTestIncomplete( - 'Test of "testClientModel" method has not been implemented yet.' - ); - } - - /** - * Test case for testEndpointParameters - * - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트. - * - * @covers ::testEndpointParameters - */ - public function testTestEndpointParameters() - { - $this->markTestIncomplete( - 'Test of "testEndpointParameters" method has not been implemented yet.' - ); - } - - /** - * Test case for testEnumParameters - * - * To test enum parameters. - * - * @covers ::testEnumParameters - */ - public function testTestEnumParameters() - { - $this->markTestIncomplete( - 'Test of "testEnumParameters" method has not been implemented yet.' - ); - } - - /** - * Test case for testGroupParameters - * - * Fake endpoint to test group parameters (optional). - * - * @covers ::testGroupParameters - */ - public function testTestGroupParameters() - { - $this->markTestIncomplete( - 'Test of "testGroupParameters" method has not been implemented yet.' - ); - } - - /** - * Test case for testInlineAdditionalProperties - * - * test inline additionalProperties. - * - * @covers ::testInlineAdditionalProperties - */ - public function testTestInlineAdditionalProperties() - { - $this->markTestIncomplete( - 'Test of "testInlineAdditionalProperties" method has not been implemented yet.' - ); - } - - /** - * Test case for testJsonFormData - * - * test json serialization of form data. - * - * @covers ::testJsonFormData - */ - public function testTestJsonFormData() - { - $this->markTestIncomplete( - 'Test of "testJsonFormData" method has not been implemented yet.' - ); - } - - /** - * Test case for testQueryParameterCollectionFormat - * - * . - * - * @covers ::testQueryParameterCollectionFormat - */ - public function testTestQueryParameterCollectionFormat() - { - $this->markTestIncomplete( - 'Test of "testQueryParameterCollectionFormat" method has not been implemented yet.' - ); - } -} diff --git a/samples/server/petstore/php-slim4/test/Api/FakeClassnameTags123ApiTest.php b/samples/server/petstore/php-slim4/test/Api/FakeClassnameTags123ApiTest.php deleted file mode 100644 index b65dbc6fa80..00000000000 --- a/samples/server/petstore/php-slim4/test/Api/FakeClassnameTags123ApiTest.php +++ /dev/null @@ -1,81 +0,0 @@ -markTestIncomplete( - 'Test of "testClassname" method has not been implemented yet.' - ); - } -} diff --git a/samples/server/petstore/php-slim4/test/Api/PetApiTest.php b/samples/server/petstore/php-slim4/test/Api/PetApiTest.php index 3e70bd0fc13..2eaed45a504 100644 --- a/samples/server/petstore/php-slim4/test/Api/PetApiTest.php +++ b/samples/server/petstore/php-slim4/test/Api/PetApiTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -176,18 +176,4 @@ class PetApiTest extends TestCase 'Test of "uploadFile" method has not been implemented yet.' ); } - - /** - * Test case for uploadFileWithRequiredFile - * - * uploads an image (required). - * - * @covers ::uploadFileWithRequiredFile - */ - public function testUploadFileWithRequiredFile() - { - $this->markTestIncomplete( - 'Test of "uploadFileWithRequiredFile" method has not been implemented yet.' - ); - } } diff --git a/samples/server/petstore/php-slim4/test/Api/StoreApiTest.php b/samples/server/petstore/php-slim4/test/Api/StoreApiTest.php index 9dc0458710a..b6d114045d8 100644 --- a/samples/server/petstore/php-slim4/test/Api/StoreApiTest.php +++ b/samples/server/petstore/php-slim4/test/Api/StoreApiTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/samples/server/petstore/php-slim4/test/Api/UserApiTest.php b/samples/server/petstore/php-slim4/test/Api/UserApiTest.php index dff950e444a..cee6da4398f 100644 --- a/samples/server/petstore/php-slim4/test/Api/UserApiTest.php +++ b/samples/server/petstore/php-slim4/test/Api/UserApiTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/samples/server/petstore/php-slim4/test/BaseModelTest.php b/samples/server/petstore/php-slim4/test/BaseModelTest.php new file mode 100644 index 00000000000..935b758b03c --- /dev/null +++ b/samples/server/petstore/php-slim4/test/BaseModelTest.php @@ -0,0 +1,599 @@ +assertEquals($expectedJson, json_encode($item->getData())); + } + + public function provideClassesAndDefaultData() + { + return [ + 'boolean model' => [BasicBooleanTestClass::class, json_encode(null)], + 'integer model' => [BasicIntegerTestClass::class, json_encode(null)], + 'number model' => [BasicNumberTestClass::class, json_encode(null)], + 'string model' => [BasicStringTestClass::class, json_encode(null)], + 'array model' => [BasicArrayTestClass::class, json_encode([])], + 'object model' => [BasicObjectTestClass::class, json_encode(new StdClass())], + 'missing type model' => [MissingTypeTestClass::class, json_encode(null)], + ]; + } + + /** + * @covers ::__construct + * @covers ::validateModelType + * @dataProvider provideInvalidClasses + */ + public function testConstructorWithInvalidTypes($className) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + } + + public function provideInvalidClasses() + { + return [ + 'unknown type model' => [UnknownTypeTestClass::class], + ]; + } + + /** + * @covers ::getOpenApiSchema + */ + public function testGetOpenApiSchema() + { + foreach ( + [ + BaseModel::getOpenApiSchema(), + CatRefTestClass::getOpenApiSchema(), + DogRefTestClass::getOpenApiSchema(), + BasicArrayTestClass::getOpenApiSchema(), + BasicBooleanTestClass::getOpenApiSchema(), + BasicIntegerTestClass::getOpenApiSchema(), + BasicNumberTestClass::getOpenApiSchema(), + BasicObjectTestClass::getOpenApiSchema(), + BasicStringTestClass::getOpenApiSchema(), + ] as $schema + ) { + $this->assertTrue(is_array($schema) || is_object($schema)); + } + } + + /** + * @covers ::createFromData + * @covers ::__set + * @covers ::__get + * @dataProvider provideCreateFromDataArguments + */ + public function testCreateFromData($modelClass, $data) + { + $item = $modelClass::createFromData($data); + $this->assertInstanceOf($modelClass, $item); + $this->assertInstanceOf(OpenApiModelInterface::class, $item); + foreach ($data as $propName => $propValue) { + $this->assertSame($propValue, $item->{$propName}); + } + } + + public function provideCreateFromDataArguments() + { + return [ + 'CatRefTestClass' => [ + CatRefTestClass::class, + [ + 'className' => 'cheshire', + 'color' => 'gray', + 'declawed' => true, + ], + ], + 'DogRefTestClass' => [ + DogRefTestClass::class, + [ + 'className' => 'bulldog', + 'color' => 'black', + 'declawed' => false, + ], + ], + ]; + } + + /** + * @covers ::setData + * @covers ::getData + * @dataProvider provideScalarModels + */ + public function testSetDataScalar($className, array $setDataValues, array $expectedDataValues) + { + $item = new $className(); + for ($i = 0; $i < count($setDataValues); $i++) { + if ($i > 0) { + // value should be previous + $this->assertSame($expectedDataValues[$i - 1], $item->getData()); + } else { + // initial value should be null + $this->assertNull($item->getData()); + } + $item->setData($setDataValues[$i]); + // values should be overwritten + $this->assertSame($expectedDataValues[$i], $item->getData()); + } + } + + public function provideScalarModels() + { + return [ + 'boolean model' => [ + BasicBooleanTestClass::class, + [false, true, false], + [false, true, false], + ], + 'integer model' => [ + BasicIntegerTestClass::class, + [-50, 322, 100500, -1000, 0], + [-50, 322, 100500, -1000, 0], + ], + 'number model' => [ + BasicNumberTestClass::class, + [-50.324, 322.756, 100500.09, -1000.43, 0], + [-50.324, 322.756, 100500.09, -1000.43, 0], + ], + 'string model' => [ + BasicStringTestClass::class, + ['foobar', 'hello world', '100', '-56', 'true', 'null', 'false'], + ['foobar', 'hello world', '100', '-56', 'true', 'null', 'false'], + ], + ]; + } + + /** + * @covers ::setData + * @covers ::getData + */ + public function testSetDataOfArray() + { + $basic = new BasicArrayTestClass(); + $data = ['foo', 'bar', 'baz']; + $basic->setData($data); + $this->assertEquals($data, $basic->getData()); + } + + /** + * @covers ::setData + * @dataProvider provideInvalidDataForArrayModel + */ + public function testSetDataOfArrayWithInvalidData($className, $data) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + $item->setData($data); + } + + public function provideInvalidDataForArrayModel() + { + $obj = new StdClass(); + $obj->foo = 'bar'; + $obj->baz = 'baf'; + $arr = []; + $arr[5] = 'foo'; + $arr[6] = 'bar'; + return [ + 'array with spaced indexes data' => [ + BasicArrayTestClass::class, + $arr, + ], + 'assoc array data' => [ + BasicArrayTestClass::class, + ['foo' => 'bar', 'baz' => 'baf'], + ], + 'object data' => [ + BasicArrayTestClass::class, + $obj, + ], + ]; + } + + /** + * @covers ::setData + * @covers ::getData + */ + public function testSetDataOfObject() + { + $basic = new BasicObjectTestClass(); + $data = ['foo' => 'bar']; + $basic->setData($data); + $this->assertSame('bar', $basic->foo); + } + + /** + * @covers ::getData + */ + public function testGetDataOfObject() + { + $catItem = new CatRefTestClass(); + $catItem->setData([ + 'color' => 'grey', + 'declawed' => false, + ]); + $data = $catItem->getData(); + $this->assertInstanceOf(StdClass::class, $data); + $this->assertSame('grey', $data->color); + $this->assertSame(false, $data->declawed); + } + + /** + * @covers ::__set + * @covers ::__get + */ + public function testSetter() + { + $item = new CatRefTestClass(); + $item->className = 'cheshire'; + $item->color = 'black'; + $item->declawed = false; + $this->assertSame('cheshire', $item->className); + $this->assertSame('black', $item->color); + $this->assertSame(false, $item->declawed); + } + + /** + * @covers ::__set + * @dataProvider provideScalarsAndArray + */ + public function testSetterOfScalarAndArray($className) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + $item->foo = 'bar'; + } + + public function provideScalarsAndArray() + { + return [ + 'boolean model' => [BasicBooleanTestClass::class], + 'integer model' => [BasicIntegerTestClass::class], + 'number model' => [BasicNumberTestClass::class], + 'string model' => [BasicStringTestClass::class], + 'array model' => [BasicArrayTestClass::class], + ]; + } + + /** + * @covers ::__set + */ + public function testSetterWithUnknownProp() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf( + 'Cannot set unknownProp property of %s model because it doesn\'t exist in related OAS schema', + CatRefTestClass::class + ) + ); + $item = new CatRefTestClass(); + $item->unknownProp = 'foobar'; + } + + /** + * @covers ::__get + */ + public function testGetterWithUnknownProp() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + sprintf( + 'Cannot get unknownProp property of %s model because it doesn\'t exist in related OAS schema', + CatRefTestClass::class + ) + ); + $item = new CatRefTestClass(); + $unknownProp = $item->unknownProp; + } + + /** + * @covers ::__get + * @dataProvider provideScalarsAndArray + */ + public function testGetterOfScalarAndArray($className) + { + $this->expectException(InvalidArgumentException::class); + $item = new $className(); + $bar = $item->foo; + } + + /** + * @covers ::__set + * @covers ::__get + */ + public function testSetterAndGetterOfBasicObject() + { + $item = new BasicObjectTestClass(); + $item->unknown = 'foo'; + $this->assertEquals('foo', $item->unknown); + } + + /** + * @covers ::jsonSerialize + * @dataProvider provideJsonSerializeArguments + */ + public function testJsonSerialize($className, $data, $expectedJson) + { + $item = $className::createFromData($data); + $this->assertEquals($expectedJson, json_encode($item)); + } + + public function provideJsonSerializeArguments() + { + return [ + 'model with all props' => [ + CatRefTestClass::class, + [ + 'className' => 'cheshire', + 'color' => 'black', + 'declawed' => false, + ], + json_encode([ + 'className' => 'cheshire', + 'color' => 'black', + 'declawed' => false, + ]), + ], + 'model with required props' => [ + CatRefTestClass::class, + [ + 'className' => 'cheshire', + ], + json_encode([ + 'className' => 'cheshire', + ]), + ], + 'model with missed required prop' => [ + CatRefTestClass::class, + [ + 'color' => 'black', + ], + json_encode([ + 'className' => null, + 'color' => 'black', + ]), + ], + 'model with schema serialized as assoc array' => [ + DogRefTestClass::class, + [ + 'className' => 'bulldog', + 'color' => 'gray', + 'declawed' => false, + ], + json_encode([ + 'className' => 'bulldog', + 'color' => 'gray', + 'declawed' => false, + ]), + ], + 'model of basic array' => [ + BasicArrayTestClass::class, + ['hello', 'world'], + json_encode(['hello', 'world']), + ], + 'model of basic boolean' => [ + BasicBooleanTestClass::class, + false, + json_encode(false), + ], + 'model of basic integer' => [ + BasicIntegerTestClass::class, + -500, + json_encode(-500), + ], + 'model of basic number' => [ + BasicNumberTestClass::class, + -3.1434, + json_encode(-3.1434), + ], + 'model of basic object' => [ + BasicObjectTestClass::class, + new \StdClass(), + json_encode(new \StdClass()), + ], + 'model of basic string' => [ + BasicStringTestClass::class, + 'foobar', + json_encode('foobar'), + ], + ]; + } + + /** + * @covers ::getModelsNamespace + * @dataProvider provideTestClasses + */ + public function testGetModelsNamespace($classname) + { + $this->assertTrue(method_exists($classname, 'getModelsNamespace')); + $getModelsNamespace = $classname . '::getModelsNamespace'; + $namespace = $getModelsNamespace(); + $this->assertIsString($namespace); + } + + public function provideTestClasses() + { + return [ + [BasicArrayTestClass::class], + [BasicBooleanTestClass::class], + [BasicIntegerTestClass::class], + [BasicNumberTestClass::class], + [BasicObjectTestClass::class], + [BasicStringTestClass::class], + [CatRefTestClass::class], + [DogRefTestClass::class], + ]; + } +} + +// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses +class BasicArrayTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "array" +} +SCHEMA; +} + +class BasicBooleanTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "boolean" +} +SCHEMA; +} + +class BasicIntegerTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "integer" +} +SCHEMA; +} + +class BasicNumberTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "number" +} +SCHEMA; +} + +class BasicObjectTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "object" +} +SCHEMA; +} + +class BasicStringTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "string" +} +SCHEMA; +} + +class CatRefTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "required" : [ "className" ], + "type" : "object", + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "type" : "string", + "default" : "red" + }, + "declawed" : { + "type" : "boolean" + } + }, + "discriminator" : { + "propertyName" : "className" + } +} +SCHEMA; +} + +class ClassWithoutGetSchemaMethod +{ + +} + +class DogRefTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "required" : [ "className" ], + "type" : "object", + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "type" : "string", + "default" : "black" + }, + "declawed" : { + "type" : "boolean" + } + }, + "discriminator" : { + "propertyName" : "className" + } +} +SCHEMA; +} + +class MissingTypeTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{} +SCHEMA; +} + +class UnknownTypeTestClass extends BaseModel +{ + protected const MODEL_SCHEMA = <<<'SCHEMA' +{ + "type" : "foobar" +} +SCHEMA; +} diff --git a/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerMiddlewareTest.php b/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerMiddlewareTest.php deleted file mode 100644 index 88ec0405126..00000000000 --- a/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerMiddlewareTest.php +++ /dev/null @@ -1,270 +0,0 @@ -assertInstanceOf(OpenApiDataMockerMiddleware::class, $middleware); - $this->assertNotNull($middleware); - } - - public function provideConstructCorrectArguments() - { - $getMockResponseCallback = function () { - return false; - }; - $afterCallback = function () { - return false; - }; - return [ - [new OpenApiDataMocker(), [], null, null], - [new OpenApiDataMocker(), [], $getMockResponseCallback, $afterCallback], - ]; - } - - /** - * @covers ::__construct - * @dataProvider provideConstructInvalidArguments - * @expectedException \InvalidArgumentException - * @expectedException \TypeError - */ - public function testConstructorWithInvalidArguments( - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback - ) { - $middleware = new OpenApiDataMockerMiddleware($mocker, $responses, $getMockResponseCallback, $afterCallback); - } - - public function provideConstructInvalidArguments() - { - return [ - 'getMockResponseCallback not callable' => [ - new OpenApiDataMocker(), [], 'foobar', null, - ], - 'afterCallback not callable' => [ - new OpenApiDataMocker(), [], null, 'foobar', - ], - ]; - } - - /** - * @covers ::process - * @dataProvider provideProcessArguments - */ - public function testProcess( - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback, - $request, - $expectedStatusCode, - $expectedHeaders, - $notExpectedHeaders, - $expectedBody - ) { - - // Create a stub for the RequestHandlerInterface interface. - $handler = $this->createMock(RequestHandlerInterface::class); - $handler->method('handle') - ->willReturn(AppFactory::determineResponseFactory()->createResponse()); - - $middleware = new OpenApiDataMockerMiddleware( - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback - ); - $response = $middleware->process($request, $handler); - - // check status code - $this->assertSame($expectedStatusCode, $response->getStatusCode()); - - // check http headers in request - foreach ($expectedHeaders as $expectedHeader => $expectedHeaderValue) { - $this->assertTrue($response->hasHeader($expectedHeader)); - if ($expectedHeaderValue !== '*') { - $this->assertSame($expectedHeaderValue, $response->getHeader($expectedHeader)[0]); - } - } - foreach ($notExpectedHeaders as $notExpectedHeader) { - $this->assertFalse($response->hasHeader($notExpectedHeader)); - } - - // check body - if (is_array($expectedBody)) { - // random values, check keys only - foreach ($expectedBody as $attribute => $value) { - $this->assertObjectHasAttribute($attribute, json_decode((string) $response->getBody(), false)); - } - } else { - $this->assertEquals($expectedBody, (string) $response->getBody()); - } - } - - public function provideProcessArguments() - { - $mocker = new OpenApiDataMocker(); - $isMockResponseRequired = function (ServerRequestInterface $request) { - $mockHttpHeader = 'X-OpenAPIServer-Mock'; - return $request->hasHeader($mockHttpHeader) - && $request->getHeader($mockHttpHeader)[0] === 'ping'; - }; - - $getMockResponseCallback = function (ServerRequestInterface $request, array $responses) use ($isMockResponseRequired) { - if ($isMockResponseRequired($request)) { - if (array_key_exists('default', $responses)) { - return $responses['default']; - } - - // return first response - return $responses[array_key_first($responses)]; - } - - return false; - }; - - $afterCallback = function ($request, $response) use ($isMockResponseRequired) { - if ($isMockResponseRequired($request)) { - $response = $response->withHeader('X-OpenAPIServer-Mock', 'pong'); - } - - return $response; - }; - - $responses = [ - '400' => [ - 'code' => 400, - 'jsonSchema' => json_encode([ - 'description' => 'Bad Request Response', - 'content' => new StdClass(), - ]), - ], - 'default' => [ - 'code' => 201, - 'jsonSchema' => json_encode([ - 'description' => 'Success Response', - 'headers' => [ - 'X-Location' => ['schema' => ['type' => 'string']], - 'X-Created-Id' => ['schema' => ['type' => 'integer']], - ], - 'content' => [ - 'application/json;encoding=utf-8' => ['schema' => ['type' => 'object', 'properties' => ['id' => ['type' => 'integer'], 'className' => ['type' => 'string'], 'declawed' => ['type' => 'boolean']]]], - ], - ]), - ], - ]; - - $responsesXmlOnly = [ - 'default' => [ - 'code' => 201, - 'jsonSchema' => json_encode([ - 'description' => 'Success Response', - 'content' => [ - 'application/xml' => [ - 'schema' => [ - 'type' => 'string', - ], - ], - ], - ]), - ], - ]; - - $requestFactory = ServerRequestCreatorFactory::create(); - - return [ - 'callbacks null' => [ - $mocker, - $responses, - null, - null, - $requestFactory->createServerRequestFromGlobals(), - 200, - [], - ['X-OpenAPIServer-Mock', 'x-location', 'x-created-id'], - '', - ], - 'xml not supported' => [ - $mocker, - $responsesXmlOnly, - $getMockResponseCallback, - $afterCallback, - $requestFactory - ->createServerRequestFromGlobals() - ->withHeader('X-OpenAPIServer-Mock', 'ping'), - 201, - ['X-OpenAPIServer-Mock' => 'pong', 'content-type' => '*/*'], - ['x-location', 'x-created-id'], - 'Mock feature supports only "application/json" content-type!', - ], - 'mock response default schema' => [ - $mocker, - $responses, - $getMockResponseCallback, - $afterCallback, - $requestFactory - ->createServerRequestFromGlobals() - ->withHeader('X-OpenAPIServer-Mock', 'ping'), - 201, - ['X-OpenAPIServer-Mock' => 'pong', 'content-type' => 'application/json', 'x-location' => '*', 'x-created-id' => '*'], - [], - [ - 'id' => 1, - 'className' => 'cat', - 'declawed' => false, - ], - ], - ]; - } -} diff --git a/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerTest.php b/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerTest.php deleted file mode 100644 index 9b387c0d9e9..00000000000 --- a/samples/server/petstore/php-slim4/test/Mock/OpenApiDataMockerTest.php +++ /dev/null @@ -1,1245 +0,0 @@ -mock($dataType, $dataFormat, $options); - $this->assertInternalType($expectedType, $data); - } - - public function provideMockCorrectArguments() - { - return [ - [IMocker::DATA_TYPE_INTEGER, null, null, IsType::TYPE_INT], - [IMocker::DATA_TYPE_NUMBER, null, null, IsType::TYPE_FLOAT], - [IMocker::DATA_TYPE_STRING, null, null, IsType::TYPE_STRING], - [IMocker::DATA_TYPE_BOOLEAN, null, null, IsType::TYPE_BOOL], - [IMocker::DATA_TYPE_ARRAY, null, [ - 'items' => [ - 'type' => IMocker::DATA_TYPE_INTEGER, - ], - ], IsType::TYPE_ARRAY], - [IMocker::DATA_TYPE_OBJECT, null, [ - 'properties' => [ - 'username' => [ - 'type' => IMocker::DATA_TYPE_INTEGER, - ], - ], - ], IsType::TYPE_OBJECT], - ]; - } - - /** - * @covers ::mock - * @dataProvider provideMockInvalidArguments - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage "dataType" must be one of integer, number, string, boolean, array, object - */ - public function testMockInvalidArguments($dataType, $dataFormat, $options) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mock($dataType, $dataFormat, $options); - } - - public function provideMockInvalidArguments() - { - return [ - ['foobar', null, null], - [3.14, null, null], - [null, null, null], - ]; - } - - /** - * @covers ::mock - */ - public function testMockWithStringEnumOptions() - { - $mocker = new OpenApiDataMocker(); - $string = $mocker->mock(IMocker::DATA_TYPE_STRING, null, [ - 'enum' => ['foobar', 'foobaz', 'helloworld'], - ]); - $this->assertContains($string, ['foobar', 'foobaz', 'helloworld']); - } - - /** - * @dataProvider provideMockIntegerCorrectArguments - * @covers ::mockInteger - */ - public function testMockIntegerWithCorrectArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - $mocker = new OpenApiDataMocker(); - $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - - $this->internalAssertNumber( - $integer, - $minimum, - $maximum, - $exclusiveMinimum, - $exclusiveMaximum, - $matchingInternalTypes, - $notMatchingInternalTypes - ); - } - - public function provideMockIntegerCorrectArguments() - { - $types = [ - IsType::TYPE_INT, - IsType::TYPE_NUMERIC, - IsType::TYPE_SCALAR, - ]; - $notTypes = [ - IsType::TYPE_ARRAY, - IsType::TYPE_BOOL, - IsType::TYPE_FLOAT, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_STRING, - IsType::TYPE_CALLABLE, - ]; - - return [ - [null, -100, 100, false, false, $types, $notTypes], - [null, -100, null, false, false, $types, $notTypes], - [null, null, 100, false, false, $types, $notTypes], - [null, -99.5, null, true, false, $types, $notTypes], - [null, null, 99.5, false, true, $types, $notTypes], - [null, -99.5, 99.5, true, true, $types, $notTypes], - ]; - } - - /** - * @dataProvider provideMockIntegerInvalidArguments - * @covers ::mockInteger - * @expectedException \InvalidArgumentException - */ - public function testMockIntegerWithInvalidArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - $mocker = new OpenApiDataMocker(); - $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - } - - public function provideMockIntegerInvalidArguments() - { - return [ - [null, 'foo', null, false, false], - [null, null, false, false, false], - [null, null, null, true, false], - [null, null, null, false, true], - [null, 100, -100, false, false], - ]; - } - - /** - * @covers ::mockInteger - * @dataProvider provideMockIntegerFormats - */ - public function testMockIntegerWithFormats( - $dataFormat, - $minimum, - $maximum, - $expectedMin, - $expectedMax - ) { - $mocker = new OpenApiDataMocker(); - $integer = $mocker->mockInteger($dataFormat, $minimum, $maximum); - $this->assertGreaterThanOrEqual($expectedMin, $integer); - $this->assertLessThanOrEqual($expectedMax, $integer); - } - - public function provideMockIntegerFormats() - { - return [ - [IMocker::DATA_FORMAT_INT32, -2147483648, 2147483648, -2147483647, 2147483647], - [IMocker::DATA_FORMAT_INT64, '-9223372036854775808', '9223372036854775808', -9223372036854775807, 9223372036854775807], - [IMocker::DATA_FORMAT_INT32, -10, 10, -10, 10], - [IMocker::DATA_FORMAT_INT64, -10, 10, -10, 10], - [IMocker::DATA_FORMAT_INT32, -9223372036854775807, 9223372036854775807, -2147483647, 2147483647], - [strtoupper(IMocker::DATA_FORMAT_INT32), -2147483648, 2147483648, -2147483647, 2147483647], - [strtoupper(IMocker::DATA_FORMAT_INT64), '-9223372036854775808', '9223372036854775808', -9223372036854775807, 9223372036854775807], - ]; - } - - /** - * @dataProvider provideMockNumberCorrectArguments - * @covers ::mockNumber - */ - public function testMockNumberWithCorrectArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - $mocker = new OpenApiDataMocker(); - $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - - $this->internalAssertNumber( - $number, - $minimum, - $maximum, - $exclusiveMinimum, - $exclusiveMaximum, - $matchingInternalTypes, - $notMatchingInternalTypes - ); - } - - public function provideMockNumberCorrectArguments() - { - $types = [ - IsType::TYPE_SCALAR, - IsType::TYPE_NUMERIC, - IsType::TYPE_FLOAT, - ]; - $notTypes = [ - IsType::TYPE_INT, - IsType::TYPE_ARRAY, - IsType::TYPE_BOOL, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_STRING, - IsType::TYPE_CALLABLE, - ]; - - return [ - [null, -100, 100, false, false, $types, $notTypes], - [null, -100, null, false, false, $types, $notTypes], - [null, null, 100, false, false, $types, $notTypes], - [null, -99.5, null, true, false, $types, $notTypes], - [null, null, 99.5, false, true, $types, $notTypes], - [null, -99.5, 99.5, true, true, $types, $notTypes], - ]; - } - - /** - * @dataProvider provideMockNumberInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockNumber - */ - public function testMockNumberWithInvalidArguments( - $dataFormat = null, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false - ) { - $mocker = new OpenApiDataMocker(); - $number = $mocker->mockNumber($dataFormat, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - } - - public function provideMockNumberInvalidArguments() - { - return [ - [null, 'foo', null, false, false], - [null, null, false, false, false], - [null, null, null, true, false], - [null, null, null, false, true], - [null, 100, -100, false, false], - ]; - } - - /** - * @dataProvider provideMockStringCorrectArguments - * @covers ::mockString - */ - public function testMockStringWithCorrectArguments( - $dataFormat = null, - $minLength = 0, - $maxLength = null, - $enum = null, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); - - $this->internalAssertString( - $str, - $minLength, - $maxLength, - $enum, - $matchingInternalTypes, - $notMatchingInternalTypes - ); - } - - public function provideMockStringCorrectArguments() - { - $types = [ - IsType::TYPE_SCALAR, - IsType::TYPE_STRING, - ]; - $notTypes = [ - IsType::TYPE_FLOAT, - IsType::TYPE_INT, - IsType::TYPE_ARRAY, - IsType::TYPE_BOOL, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_CALLABLE, - ]; - - return [ - [null, 0, null, null, $types, $notTypes], - [null, 10, null, null, $types, $notTypes], - [null, 0, 100, null, $types, $notTypes], - [null, 10, 50, null, $types, $notTypes], - [null, 10, 10, null, $types, $notTypes], - [null, 0, 0, null, $types, $notTypes], - [null, null, null, null, $types, $notTypes], - [null, null, null, ['foobar', 'foobaz', 'hello world'], $types, $notTypes], - [null, null, null, ['foobar'], $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 0, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 10, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 0, 100, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 10, 50, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 10, 10, null, $types, $notTypes], - [IMocker::DATA_FORMAT_PASSWORD, 0, 0, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, null, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 10, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 10, 10, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, null, 8, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 16, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 25, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 25, 25, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, null, 20, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 30, null, null, $types, $notTypes], - [IMocker::DATA_FORMAT_EMAIL, 1, 1, null, $types, $notTypes], - ]; - } - - /** - * @dataProvider provideMockStringInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockString - */ - public function testMockStringWithInvalidArguments( - $dataFormat = null, - $minLength = 0, - $maxLength = null, - $enum = null - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength, $enum); - } - - public function provideMockStringInvalidArguments() - { - return [ - 'negative minLength' => [null, -10, null], - 'negative maxLength' => [null, 0, -10], - 'both minLength maxLength negative' => [null, -10, -10], - 'decimal minLength and maxLength' => [null, 0.5, 0.5], - 'string minLength' => [null, '10', null], - 'string maxLength' => [null, 0, '50'], - 'string minLength and maxLength' => [null, '10', '50'], - 'maxLength less than minLength' => [null, 50, 10], - 'enum is string' => [null, null, null, 'foobar'], - 'enum is empty array' => [null, null, null, []], - 'enum array is not unique' => [null, null, null, ['foobar', 'foobaz', 'foobar']], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringByteFormatArguments - */ - public function testMockStringWithByteFormat( - $dataFormat, - $minLength, - $maxLength - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, $dataFormat, ['minLength' => $minLength, 'maxLength' => $maxLength]); - $base64pattern = '/^[\w\+\/\=]*$/'; - $this->assertRegExp($base64pattern, $str); - $this->assertRegExp($base64pattern, $str2); - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str)); - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str)); - $this->assertLessThanOrEqual($maxLength, mb_strlen($str2)); - } - } - - public function provideMockStringByteFormatArguments() - { - return [ - [IMocker::DATA_FORMAT_BYTE, null, null], - [IMocker::DATA_FORMAT_BYTE, 10, null], - [IMocker::DATA_FORMAT_BYTE, 10, 10], - [IMocker::DATA_FORMAT_BYTE, null, 12], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringBinaryFormatArguments - */ - public function testMockStringWithBinaryFormat( - $dataFormat, - $minLength, - $maxLength - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, $dataFormat, ['minLength' => $minLength, 'maxLength' => $maxLength]); - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, strlen($str)); - $this->assertGreaterThanOrEqual($minLength, strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, strlen($str)); - $this->assertLessThanOrEqual($maxLength, strlen($str2)); - } - } - - public function provideMockStringBinaryFormatArguments() - { - return [ - [IMocker::DATA_FORMAT_BINARY, 0, null], - [IMocker::DATA_FORMAT_BINARY, 10, null], - [IMocker::DATA_FORMAT_BINARY, 0, 100], - [IMocker::DATA_FORMAT_BINARY, 10, 50], - [IMocker::DATA_FORMAT_BINARY, 10, 10], - [IMocker::DATA_FORMAT_BINARY, 0, 0], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringDateFormatArguments - */ - public function testMockStringWithDateAndDateTimeFormat( - $dataFormat, - $minLength, - $maxLength, - $dtFormat - ) { - $mocker = new OpenApiDataMocker(); - $str = $mocker->mockString($dataFormat, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, $dataFormat, ['minLength' => $minLength, 'maxLength' => $maxLength]); - - if ($dtFormat !== null) { - $date = DateTime::createFromFormat($dtFormat, $str); - $date2 = DateTime::createFromFormat($dtFormat, $str2); - $this->assertInstanceOf(DateTime::class, $date); - $this->assertInstanceOf(DateTime::class, $date2); - } - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str)); - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str)); - $this->assertLessThanOrEqual($maxLength, mb_strlen($str2)); - } - } - - public function provideMockStringDateFormatArguments() - { - return [ - [IMocker::DATA_FORMAT_DATE, null, null, 'Y-m-d'], - [IMocker::DATA_FORMAT_DATE, 10, null, 'Y-m-d'], - [IMocker::DATA_FORMAT_DATE, 10, 10, 'Y-m-d'], - [IMocker::DATA_FORMAT_DATE, null, 8, null], - [IMocker::DATA_FORMAT_DATE, 16, null, null], - [IMocker::DATA_FORMAT_DATE_TIME, null, null, 'Y-m-d\TH:i:sP'], - [IMocker::DATA_FORMAT_DATE_TIME, 25, null, 'Y-m-d\TH:i:sP'], - [IMocker::DATA_FORMAT_DATE_TIME, 25, 25, 'Y-m-d\TH:i:sP'], - [IMocker::DATA_FORMAT_DATE_TIME, null, 20, null], - [IMocker::DATA_FORMAT_DATE_TIME, 30, null, null], - ]; - } - - /** - * @covers ::mock - * @covers ::mockString - * @dataProvider provideMockStringUuidFormatArguments - */ - public function testMockStringWithUuidFormat( - $minLength, - $maxLength - ) { - $mocker = new OpenApiDataMocker(); - $arr = []; - $arr2 = []; - $hexPattern = '/^[a-f0-9]*$/'; - - while (count($arr) < 100 && count($arr2) < 100) { - $str = $mocker->mockString(IMocker::DATA_FORMAT_UUID, $minLength, $maxLength); - $str2 = $mocker->mock(IMocker::DATA_TYPE_STRING, IMocker::DATA_FORMAT_UUID, ['minLength' => $minLength, 'maxLength' => $maxLength]); - $arr[] = $str; - $arr2[] = $str2; - - $this->assertRegExp($hexPattern, $str); - $this->assertRegExp($hexPattern, $str2); - - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str)); - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str2)); - } - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str)); - $this->assertLessThanOrEqual($maxLength, mb_strlen($str2)); - } - } - } - - public function provideMockStringUuidFormatArguments() - { - return [ - [null, null], - [10, null], - [10, 10], - [null, 8], - [16, null], - [null, null], - [25, null], - [25, 25], - [null, 20], - [30, null], - [1, 1], - ]; - } - - /** - * @covers ::mockBoolean - */ - public function testMockBoolean() - { - $mocker = new OpenApiDataMocker(); - $bool = $mocker->mockBoolean(); - - $matchingInternalTypes = [ - IsType::TYPE_SCALAR, - IsType::TYPE_BOOL, - ]; - - foreach ($matchingInternalTypes as $matchType) { - $this->assertInternalType($matchType, $bool); - } - - $notMatchingInternalTypes = [ - IsType::TYPE_NUMERIC, - IsType::TYPE_FLOAT, - IsType::TYPE_INT, - IsType::TYPE_ARRAY, - IsType::TYPE_STRING, - IsType::TYPE_NULL, - IsType::TYPE_OBJECT, - IsType::TYPE_RESOURCE, - IsType::TYPE_CALLABLE, - ]; - - foreach ($notMatchingInternalTypes as $notMatchType) { - $this->assertNotInternalType($notMatchType, $bool); - } - } - - private function internalAssertNumber( - $number, - $minimum = null, - $maximum = null, - $exclusiveMinimum = false, - $exclusiveMaximum = false, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - foreach ($matchingInternalTypes as $matchType) { - $this->assertInternalType($matchType, $number); - } - - foreach ($notMatchingInternalTypes as $notMatchType) { - $this->assertNotInternalType($notMatchType, $number); - } - - if ($minimum !== null) { - if ($exclusiveMinimum) { - $this->assertGreaterThan($minimum, $number); - } else { - $this->assertGreaterThanOrEqual($minimum, $number); - } - } - - if ($maximum !== null) { - if ($exclusiveMaximum) { - $this->assertLessThan($maximum, $number); - } else { - $this->assertLessThanOrEqual($maximum, $number); - } - } - } - - private function internalAssertString( - $str, - $minLength = null, - $maxLength = null, - $enum = null, - $matchingInternalTypes = [], - $notMatchingInternalTypes = [] - ) { - foreach ($matchingInternalTypes as $matchType) { - $this->assertInternalType($matchType, $str); - } - - foreach ($notMatchingInternalTypes as $notMatchType) { - $this->assertNotInternalType($notMatchType, $str); - } - - if ($minLength !== null) { - $this->assertGreaterThanOrEqual($minLength, mb_strlen($str, 'UTF-8')); - } - - if ($maxLength !== null) { - $this->assertLessThanOrEqual($maxLength, mb_strlen($str, 'UTF-8')); - } - - if (is_array($enum) && !empty($enum)) { - $this->assertContains($str, $enum); - } - } - - /** - * @dataProvider provideMockArrayCorrectArguments - * @covers ::mockArray - */ - public function testMockArrayFlattenWithCorrectArguments( - $items, - $minItems, - $maxItems, - $uniqueItems, - $expectedItemsType = null, - $expectedArraySize = null - ) { - $mocker = new OpenApiDataMocker(); - $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); - - $this->assertIsArray($arr); - if ($expectedArraySize !== null) { - $this->assertCount($expectedArraySize, $arr); - } - if ($expectedItemsType && $expectedArraySize > 0) { - $this->assertContainsOnly($expectedItemsType, $arr, true); - } - - if (is_array($items)) { - $dataType = $items['type']; - $dataFormat = $items['dataFormat'] ?? null; - - // items field numeric properties - $minimum = $items['minimum'] ?? null; - $maximum = $items['maximum'] ?? null; - $exclusiveMinimum = $items['exclusiveMinimum'] ?? null; - $exclusiveMaximum = $items['exclusiveMaximum'] ?? null; - - // items field string properties - $minLength = $items['minLength'] ?? null; - $maxLength = $items['maxLength'] ?? null; - $enum = $items['enum'] ?? null; - $pattern = $items['pattern'] ?? null; - - // items field array properties - $subItems = $items['items'] ?? null; - $subMinItems = $items['minItems'] ?? null; - $subMaxItems = $items['maxItems'] ?? null; - $subUniqueItems = $items['uniqueItems'] ?? null; - } else { - // is object - $dataType = $items->type; - $dataFormat = $items->dataFormat ?? null; - - // items field numeric properties - $minimum = $items->minimum ?? null; - $maximum = $items->maximum ?? null; - $exclusiveMinimum = $items->exclusiveMinimum ?? null; - $exclusiveMaximum = $items->exclusiveMaximum ?? null; - - // items field string properties - $minLength = $items->minLength ?? null; - $maxLength = $items->maxLength ?? null; - $enum = $items->enum ?? null; - $pattern = $items->pattern ?? null; - - // items field array properties - $subItems = $items->items ?? null; - $subMinItems = $items->minItems ?? null; - $subMaxItems = $items->maxItems ?? null; - $subUniqueItems = $items->uniqueItems ?? null; - } - - - foreach ($arr as $item) { - switch ($dataType) { - case IMocker::DATA_TYPE_INTEGER: - $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - break; - case IMocker::DATA_TYPE_NUMBER: - $this->internalAssertNumber($item, $minimum, $maximum, $exclusiveMinimum, $exclusiveMaximum); - break; - case IMocker::DATA_TYPE_STRING: - $this->internalAssertString($item, $minLength, $maxLength); - break; - case IMocker::DATA_TYPE_BOOLEAN: - $this->assertInternalType(IsType::TYPE_BOOL, $item); - break; - case IMocker::DATA_TYPE_ARRAY: - $this->testMockArrayFlattenWithCorrectArguments($subItems, $subMinItems, $subMaxItems, $subUniqueItems); - break; - } - } - } - - public function provideMockArrayCorrectArguments() - { - $intItems = ['type' => IMocker::DATA_TYPE_INTEGER, 'minimum' => 5, 'maximum' => 10]; - $floatItems = ['type' => IMocker::DATA_TYPE_NUMBER, 'minimum' => -32.4, 'maximum' => 88.6, 'exclusiveMinimum' => true, 'exclusiveMaximum' => true]; - $strItems = ['type' => IMocker::DATA_TYPE_STRING, 'minLength' => 20, 'maxLength' => 50]; - $boolItems = (object) ['type' => IMocker::DATA_TYPE_BOOLEAN]; - $arrayItems = (object) ['type' => IMocker::DATA_TYPE_ARRAY, 'items' => ['type' => IMocker::DATA_TYPE_STRING, 'minItems' => 3, 'maxItems' => 10]]; - $objectItems = (object) ['type' => IMocker::DATA_TYPE_OBJECT, 'properties' => (object)['username' => ['type' => IMocker::DATA_TYPE_STRING]]]; - $expectedInt = IsType::TYPE_INT; - $expectedFloat = IsType::TYPE_FLOAT; - $expectedStr = IsType::TYPE_STRING; - $expectedBool = IsType::TYPE_BOOL; - $expectedArray = IsType::TYPE_ARRAY; - $expectedObject = IsType::TYPE_OBJECT; - - return [ - 'empty array' => [ - $strItems, null, 0, false, null, 0, - ], - 'empty array, limit zero' => [ - $strItems, 0, 0, false, null, 0, - ], - 'array of one string as default size' => [ - $strItems, null, null, false, $expectedStr, 1, - ], - 'array of one string, limit one' => [ - $strItems, 1, 1, false, $expectedStr, 1, - ], - 'array of two strings' => [ - $strItems, 2, null, false, $expectedStr, 2, - ], - 'array of five strings, limit ten' => [ - $strItems, 5, 10, false, $expectedStr, 5, - ], - 'array of five strings, limit five' => [ - $strItems, 5, 5, false, $expectedStr, 5, - ], - 'array of one string, limit five' => [ - $strItems, null, 5, false, $expectedStr, 1, - ], - 'array of one integer' => [ - $intItems, null, null, false, $expectedInt, 1, - ], - 'array of one float' => [ - $floatItems, null, null, false, $expectedFloat, 1, - ], - 'array of one boolean' => [ - $boolItems, null, null, false, $expectedBool, 1, - ], - 'array of one array of strings' => [ - $arrayItems, null, null, false, $expectedArray, 1, - ], - 'array of one object' => [ - $objectItems, null, null, false, $expectedObject, 1 - ], - ]; - } - - /** - * @dataProvider provideMockArrayInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockArray - */ - public function testMockArrayWithInvalidArguments( - $items, - $minItems, - $maxItems, - $uniqueItems - ) { - $mocker = new OpenApiDataMocker(); - $arr = $mocker->mockArray($items, $minItems, $maxItems, $uniqueItems); - } - - public function provideMockArrayInvalidArguments() - { - $intItems = ['type' => IMocker::DATA_TYPE_INTEGER]; - - return [ - 'items is nor array' => [ - 'foobar', null, null, false, - ], - 'items doesnt have "type" key' => [ - ['foobar' => 'foobaz'], null, null, false, - ], - 'minItems is not integer' => [ - $intItems, 3.12, null, false, - ], - 'minItems is negative' => [ - $intItems, -10, null, false, - ], - 'minItems is not number' => [ - $intItems, '1', null, false, - ], - 'maxItems is not integer' => [ - $intItems, null, 3.12, false, - ], - 'maxItems is negative' => [ - $intItems, null, -10, false, - ], - 'maxItems is not number' => [ - $intItems, null, 'foobaz', false, - ], - 'maxItems less than minItems' => [ - $intItems, 5, 2, false, - ], - 'items with ref to unknown class' => [ - ['$ref' => '#/components/schemas/UnknownClass'], null, null, false, - ], - 'items with ref to class without getOpenApiSchema method' => [ - ['$ref' => '#/components/schemas/ClassWithoutGetSchemaMethod'], null, null, false, - ], - ]; - } - - /** - * @dataProvider provideMockArrayWithRefArguments - * @covers ::mockArray - */ - public function testMockArrayWithRef($items, $expectedStructure) - { - $mocker = new OpenApiDataMocker(); - $arr = $mocker->mockArray($items); - $this->assertIsArray($arr); - $this->assertCount(1, $arr); - foreach ($arr as $item) { - // TODO: replace with assertInstanceOf assertion - $this->assertInternalType(IsType::TYPE_OBJECT, $item); - foreach ($expectedStructure as $expectedProp => $expectedType) { - $this->assertInternalType($expectedType, $item->$expectedProp); - } - } - } - - public function provideMockArrayWithRefArguments() - { - return [ - 'items with ref to CatRefTestClass' => [ - ['$ref' => '#/components/schemas/CatRefTestClass'], - [ - 'className' => IsType::TYPE_STRING, - 'color' => IsType::TYPE_STRING, - 'declawed' => IsType::TYPE_BOOL, - ], - ], - ]; - } - - /** - * @dataProvider provideMockObjectCorrectArguments - * @covers ::mockObject - */ - public function testMockObjectWithCorrectArguments( - $properties, - $minProperties, - $maxProperties, - $additionalProperties, - $required, - $expectedKeys - ) { - $mocker = new OpenApiDataMocker(); - $obj = $mocker->mockObject( - $properties, - $minProperties, - $maxProperties, - $additionalProperties, - $required - ); - - $this->assertInternalType(IsType::TYPE_OBJECT, $obj); - $this->assertSame($expectedKeys, array_keys(get_object_vars($obj))); - } - - public function provideMockObjectCorrectArguments() - { - $additionProps = [ - 'extra' => [ - 'type' => IMocker::DATA_TYPE_STRING, - ], - ]; - return [ - 'empty object' => [ - [], 1, 10, true, null, [], - ], - 'empty object from StdClass' => [ - new StdClass(), 1, 5, false, null, [], - ], - 'object with username property' => [ - [ - 'username' => [ - 'type' => IMocker::DATA_TYPE_STRING, - ], - ], 0, 5, $additionProps, null, ['username'], - ], - 'object with foobar property' => [ - (object) [ - 'foobar' => [ - 'type' => IMocker::DATA_TYPE_INTEGER, - ], - ], 1, 1, (object) $additionProps, null, ['foobar'], - ], - ]; - } - - /** - * @dataProvider provideMockObjectInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockObject - */ - public function testMockObjectWithInvalidArguments( - $properties, - $minProperties, - $maxProperties, - $additionalProperties, - $required - ) { - $mocker = new OpenApiDataMocker(); - $obj = $mocker->mockObject($properties, $minProperties, $maxProperties, $additionalProperties, $required); - } - - public function provideMockObjectInvalidArguments() - { - return [ - 'properties cannot be null' => [ - null, 0, 10, false, null, - ], - 'properties cannot be a string' => [ - 'foobar', 0, 10, false, null, - ], - 'property value cannot be a string' => [ - ['username' => 'foobar'], 0, 10, false, null, - ], - 'minProperties is not integer' => [ - [], 3.12, null, false, null, - ], - 'minProperties is negative' => [ - [], -10, null, false, null, - ], - 'minProperties is not number' => [ - [], '1', null, false, null, - ], - 'maxProperties is not integer' => [ - [], null, 3.12, false, null, - ], - 'maxProperties is negative' => [ - [], null, -10, false, null, - ], - 'maxProperties is not number' => [ - [], null, 'foobaz', false, null, - ], - 'maxProperties less than minProperties' => [ - [], 5, 2, false, null, - ], - 'additionalProperties is not object|array|boolean' => [ - [], null, null, 'foobar', null, - ], - 'required is object, not array' => [ - [], null, null, null, new StdClass(), - ], - 'required is not array' => [ - [], null, null, null, 'foobar', - ], - 'required array with duplicates' => [ - [], null, null, null, ['username', 'username'], - ], - 'required array of non-strings' => [ - [], null, null, null, [1, 2, 3], - ], - ]; - } - - /** - * @covers ::mockObject - */ - public function testMockObjectWithReferencedProps() - { - $mocker = new OpenApiDataMocker(); - $obj = $mocker->mockObject( - (object) [ - 'cat' => [ - '$ref' => '#/components/schemas/CatRefTestClass', - ], - ] - ); - $this->assertInternalType(IsType::TYPE_OBJECT, $obj->cat); - $this->assertInternalType(IsType::TYPE_STRING, $obj->cat->className); - $this->assertInternalType(IsType::TYPE_STRING, $obj->cat->color); - $this->assertInternalType(IsType::TYPE_BOOL, $obj->cat->declawed); - } - - /** - * @dataProvider provideMockFromSchemaCorrectArguments - * @covers ::mockFromSchema - */ - public function testMockFromSchemaWithCorrectArguments($schema, $expectedType) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromSchema($schema); - $this->assertInternalType($expectedType, $data); - } - - public function provideMockFromSchemaCorrectArguments() - { - return [ - 'string from object' => [ - (object) ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'string from array' => [ - ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'integer from object' => [ - (object) ['type' => IMocker::DATA_TYPE_INTEGER], - IsType::TYPE_INT, - ], - 'integer from array' => [ - ['type' => IMocker::DATA_TYPE_INTEGER], - IsType::TYPE_INT, - ], - 'number from object' => [ - (object) ['type' => IMocker::DATA_TYPE_NUMBER], - IsType::TYPE_FLOAT, - ], - 'number from array' => [ - ['type' => IMocker::DATA_TYPE_NUMBER], - IsType::TYPE_FLOAT, - ], - 'string from object' => [ - (object) ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'string from array' => [ - ['type' => IMocker::DATA_TYPE_STRING], - IsType::TYPE_STRING, - ], - 'boolean from object' => [ - (object) ['type' => IMocker::DATA_TYPE_BOOLEAN], - IsType::TYPE_BOOL, - ], - 'boolean from array' => [ - ['type' => IMocker::DATA_TYPE_BOOLEAN], - IsType::TYPE_BOOL, - ], - 'array of strings from object' => [ - (object) [ - 'type' => IMocker::DATA_TYPE_ARRAY, - 'items' => ['type' => IMocker::DATA_TYPE_STRING], - ], - IsType::TYPE_ARRAY, - ], - 'array of strings from array' => [ - [ - 'type' => IMocker::DATA_TYPE_ARRAY, - 'items' => ['type' => IMocker::DATA_TYPE_STRING], - ], - IsType::TYPE_ARRAY, - ], - 'object with username prop from object' => [ - (object) [ - 'type' => IMocker::DATA_TYPE_OBJECT, - 'properties' => ['username' => ['type' => IMocker::DATA_TYPE_STRING]], - ], - IsType::TYPE_OBJECT, - ], - 'object with username prop from array' => [ - [ - 'type' => IMocker::DATA_TYPE_OBJECT, - 'properties' => ['username' => ['type' => IMocker::DATA_TYPE_STRING]], - ], - IsType::TYPE_OBJECT, - ], - 'referenced class' => [ - ['$ref' => '#/components/schemas/CatRefTestClass'], - IsType::TYPE_OBJECT, - ], - ]; - } - - /** - * @dataProvider provideMockFromSchemaInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockFromSchema - */ - public function testMockFromSchemaWithInvalidArguments($schema) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromSchema($schema); - } - - - public function provideMockFromSchemaInvalidArguments() - { - return [ - 'null' => [null], - 'numeric' => [3.14], - 'empty array' => [[]], - 'empty object' => [(object) []], - 'string' => ['foobar'], - 'DateTime object' => [new DateTime()], - ]; - } - - /** - * @dataProvider provideMockFromRefCorrectArguments - * @covers ::mockFromRef - */ - public function testMockFromRefWithCorrectArguments($ref, $expectedStructure) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromRef($ref); - foreach ($expectedStructure as $expectedProp => $expectedType) { - $this->assertInternalType($expectedType, $data->$expectedProp); - } - } - - public function provideMockFromRefCorrectArguments() - { - return [ - 'CatRefTestClass model' => [ - '#/components/schemas/CatRefTestClass', - [ - 'className' => IsType::TYPE_STRING, - 'color' => IsType::TYPE_STRING, - 'declawed' => IsType::TYPE_BOOL, - ] - ], - ]; - } - - /** - * @dataProvider provideMockFromRefInvalidArguments - * @expectedException \InvalidArgumentException - * @covers ::mockFromRef - */ - public function testMockFromRefWithInvalidArguments($ref) - { - $mocker = new OpenApiDataMocker(); - $data = $mocker->mockFromRef($ref); - } - - public function provideMockFromRefInvalidArguments() - { - return [ - 'ref to unknown class' => ['#/components/schemas/UnknownClass'], - 'ref to class without getOpenApiSchema method' => ['#/components/schemas/ClassWithoutGetSchemaMethod'], - ]; - } -} - -namespace OpenAPIServer\Model; - -// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses -final class CatRefTestClass -{ - private const MODEL_SCHEMA = <<<'SCHEMA' -{ - "required" : [ "className" ], - "type" : "object", - "properties" : { - "className" : { - "type" : "string" - }, - "color" : { - "type" : "string", - "default" : "red" - }, - "declawed" : { - "type" : "boolean" - } - }, - "discriminator" : { - "propertyName" : "className" - } -} -SCHEMA; - - public static function getOpenApiSchema() - { - return json_decode(static::MODEL_SCHEMA, true); - } -} - -final class ClassWithoutGetSchemaMethod -{ -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesAnyTypeTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesAnyTypeTest.php deleted file mode 100644 index f1b10207256..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesAnyTypeTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesAnyType" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "AdditionalPropertiesAnyType" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesAnyType::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesAnyType::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesArrayTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesArrayTest.php deleted file mode 100644 index f00f52a9d4f..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesArrayTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesArray" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "AdditionalPropertiesArray" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesArray::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesArray::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesBooleanTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesBooleanTest.php deleted file mode 100644 index aa045267f42..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesBooleanTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesBoolean" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "AdditionalPropertiesBoolean" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesBoolean::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesBoolean::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesClassTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesClassTest.php deleted file mode 100644 index 03125132976..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesClassTest.php +++ /dev/null @@ -1,200 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapString" - */ - public function testPropertyMapString() - { - $this->markTestIncomplete( - 'Test of "mapString" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapNumber" - */ - public function testPropertyMapNumber() - { - $this->markTestIncomplete( - 'Test of "mapNumber" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapInteger" - */ - public function testPropertyMapInteger() - { - $this->markTestIncomplete( - 'Test of "mapInteger" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapBoolean" - */ - public function testPropertyMapBoolean() - { - $this->markTestIncomplete( - 'Test of "mapBoolean" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapArrayInteger" - */ - public function testPropertyMapArrayInteger() - { - $this->markTestIncomplete( - 'Test of "mapArrayInteger" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapArrayAnytype" - */ - public function testPropertyMapArrayAnytype() - { - $this->markTestIncomplete( - 'Test of "mapArrayAnytype" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapMapString" - */ - public function testPropertyMapMapString() - { - $this->markTestIncomplete( - 'Test of "mapMapString" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapMapAnytype" - */ - public function testPropertyMapMapAnytype() - { - $this->markTestIncomplete( - 'Test of "mapMapAnytype" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "anytype1" - */ - public function testPropertyAnytype1() - { - $this->markTestIncomplete( - 'Test of "anytype1" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "anytype2" - */ - public function testPropertyAnytype2() - { - $this->markTestIncomplete( - 'Test of "anytype2" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "anytype3" - */ - public function testPropertyAnytype3() - { - $this->markTestIncomplete( - 'Test of "anytype3" property in "AdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesClass::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesClass::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesIntegerTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesIntegerTest.php deleted file mode 100644 index c2c34445396..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesIntegerTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesInteger" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "AdditionalPropertiesInteger" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesInteger::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesInteger::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesNumberTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesNumberTest.php deleted file mode 100644 index a5e439ce98f..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesNumberTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesNumber" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "AdditionalPropertiesNumber" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesNumber::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesNumber::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesObjectTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesObjectTest.php deleted file mode 100644 index 5f03164b5ed..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesObjectTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesObject" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "AdditionalPropertiesObject" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesObject::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesObject::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesStringTest.php b/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesStringTest.php deleted file mode 100644 index 438bcafe84e..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AdditionalPropertiesStringTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "AdditionalPropertiesString" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "AdditionalPropertiesString" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = AdditionalPropertiesString::getOpenApiSchema(); - $schemaArr = AdditionalPropertiesString::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/AnimalTest.php b/samples/server/petstore/php-slim4/test/Model/AnimalTest.php deleted file mode 100644 index 4ca0be03ef4..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/AnimalTest.php +++ /dev/null @@ -1,110 +0,0 @@ -markTestIncomplete( - 'Test of "Animal" model has not been implemented yet.' - ); - } - - /** - * Test attribute "className" - */ - public function testPropertyClassName() - { - $this->markTestIncomplete( - 'Test of "className" property in "Animal" model has not been implemented yet.' - ); - } - - /** - * Test attribute "color" - */ - public function testPropertyColor() - { - $this->markTestIncomplete( - 'Test of "color" property in "Animal" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = Animal::getOpenApiSchema(); - $schemaArr = Animal::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/ApiResponseTest.php b/samples/server/petstore/php-slim4/test/Model/ApiResponseTest.php index b62fc2f3252..0190bd0490a 100644 --- a/samples/server/petstore/php-slim4/test/Model/ApiResponseTest.php +++ b/samples/server/petstore/php-slim4/test/Model/ApiResponseTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -71,6 +71,12 @@ class ApiResponseTest extends TestCase public function testApiResponse() { $testApiResponse = new ApiResponse(); + $namespacedClassname = ApiResponse::getModelsNamespace() . '\\ApiResponse'; + $this->assertSame('\\' . ApiResponse::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( 'Test of "ApiResponse" model has not been implemented yet.' ); @@ -112,9 +118,7 @@ class ApiResponseTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = ApiResponse::getOpenApiSchema(); - $schemaArr = ApiResponse::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = ApiResponse::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/ArrayOfArrayOfNumberOnlyTest.php b/samples/server/petstore/php-slim4/test/Model/ArrayOfArrayOfNumberOnlyTest.php deleted file mode 100644 index 040882180ec..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ArrayOfArrayOfNumberOnlyTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "ArrayOfArrayOfNumberOnly" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayArrayNumber" - */ - public function testPropertyArrayArrayNumber() - { - $this->markTestIncomplete( - 'Test of "arrayArrayNumber" property in "ArrayOfArrayOfNumberOnly" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = ArrayOfArrayOfNumberOnly::getOpenApiSchema(); - $schemaArr = ArrayOfArrayOfNumberOnly::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/ArrayOfNumberOnlyTest.php b/samples/server/petstore/php-slim4/test/Model/ArrayOfNumberOnlyTest.php deleted file mode 100644 index b77b2634067..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ArrayOfNumberOnlyTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "ArrayOfNumberOnly" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayNumber" - */ - public function testPropertyArrayNumber() - { - $this->markTestIncomplete( - 'Test of "arrayNumber" property in "ArrayOfNumberOnly" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = ArrayOfNumberOnly::getOpenApiSchema(); - $schemaArr = ArrayOfNumberOnly::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/ArrayTestTest.php b/samples/server/petstore/php-slim4/test/Model/ArrayTestTest.php deleted file mode 100644 index 6f49e40e2ec..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ArrayTestTest.php +++ /dev/null @@ -1,120 +0,0 @@ -markTestIncomplete( - 'Test of "ArrayTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayOfString" - */ - public function testPropertyArrayOfString() - { - $this->markTestIncomplete( - 'Test of "arrayOfString" property in "ArrayTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayArrayOfInteger" - */ - public function testPropertyArrayArrayOfInteger() - { - $this->markTestIncomplete( - 'Test of "arrayArrayOfInteger" property in "ArrayTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayArrayOfModel" - */ - public function testPropertyArrayArrayOfModel() - { - $this->markTestIncomplete( - 'Test of "arrayArrayOfModel" property in "ArrayTest" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = ArrayTest::getOpenApiSchema(); - $schemaArr = ArrayTest::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/BigCatAllOfTest.php b/samples/server/petstore/php-slim4/test/Model/BigCatAllOfTest.php deleted file mode 100644 index 4b4f1667f6c..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/BigCatAllOfTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "BigCatAllOf" model has not been implemented yet.' - ); - } - - /** - * Test attribute "kind" - */ - public function testPropertyKind() - { - $this->markTestIncomplete( - 'Test of "kind" property in "BigCatAllOf" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = BigCatAllOf::getOpenApiSchema(); - $schemaArr = BigCatAllOf::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/BigCatTest.php b/samples/server/petstore/php-slim4/test/Model/BigCatTest.php deleted file mode 100644 index cd8bf23092c..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/BigCatTest.php +++ /dev/null @@ -1,130 +0,0 @@ -markTestIncomplete( - 'Test of "BigCat" model has not been implemented yet.' - ); - } - - /** - * Test attribute "className" - */ - public function testPropertyClassName() - { - $this->markTestIncomplete( - 'Test of "className" property in "BigCat" model has not been implemented yet.' - ); - } - - /** - * Test attribute "color" - */ - public function testPropertyColor() - { - $this->markTestIncomplete( - 'Test of "color" property in "BigCat" model has not been implemented yet.' - ); - } - - /** - * Test attribute "declawed" - */ - public function testPropertyDeclawed() - { - $this->markTestIncomplete( - 'Test of "declawed" property in "BigCat" model has not been implemented yet.' - ); - } - - /** - * Test attribute "kind" - */ - public function testPropertyKind() - { - $this->markTestIncomplete( - 'Test of "kind" property in "BigCat" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = BigCat::getOpenApiSchema(); - $schemaArr = BigCat::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/CapitalizationTest.php b/samples/server/petstore/php-slim4/test/Model/CapitalizationTest.php deleted file mode 100644 index 692eb56d209..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/CapitalizationTest.php +++ /dev/null @@ -1,150 +0,0 @@ -markTestIncomplete( - 'Test of "Capitalization" model has not been implemented yet.' - ); - } - - /** - * Test attribute "smallCamel" - */ - public function testPropertySmallCamel() - { - $this->markTestIncomplete( - 'Test of "smallCamel" property in "Capitalization" model has not been implemented yet.' - ); - } - - /** - * Test attribute "capitalCamel" - */ - public function testPropertyCapitalCamel() - { - $this->markTestIncomplete( - 'Test of "capitalCamel" property in "Capitalization" model has not been implemented yet.' - ); - } - - /** - * Test attribute "smallSnake" - */ - public function testPropertySmallSnake() - { - $this->markTestIncomplete( - 'Test of "smallSnake" property in "Capitalization" model has not been implemented yet.' - ); - } - - /** - * Test attribute "capitalSnake" - */ - public function testPropertyCapitalSnake() - { - $this->markTestIncomplete( - 'Test of "capitalSnake" property in "Capitalization" model has not been implemented yet.' - ); - } - - /** - * Test attribute "sCAETHFlowPoints" - */ - public function testPropertySCAETHFlowPoints() - { - $this->markTestIncomplete( - 'Test of "sCAETHFlowPoints" property in "Capitalization" model has not been implemented yet.' - ); - } - - /** - * Test attribute "aTTNAME" - */ - public function testPropertyATTNAME() - { - $this->markTestIncomplete( - 'Test of "aTTNAME" property in "Capitalization" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = Capitalization::getOpenApiSchema(); - $schemaArr = Capitalization::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/CatAllOfTest.php b/samples/server/petstore/php-slim4/test/Model/CatAllOfTest.php deleted file mode 100644 index 81957f4c253..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/CatAllOfTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "CatAllOf" model has not been implemented yet.' - ); - } - - /** - * Test attribute "declawed" - */ - public function testPropertyDeclawed() - { - $this->markTestIncomplete( - 'Test of "declawed" property in "CatAllOf" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = CatAllOf::getOpenApiSchema(); - $schemaArr = CatAllOf::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/CatTest.php b/samples/server/petstore/php-slim4/test/Model/CatTest.php deleted file mode 100644 index cae780deb23..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/CatTest.php +++ /dev/null @@ -1,120 +0,0 @@ -markTestIncomplete( - 'Test of "Cat" model has not been implemented yet.' - ); - } - - /** - * Test attribute "className" - */ - public function testPropertyClassName() - { - $this->markTestIncomplete( - 'Test of "className" property in "Cat" model has not been implemented yet.' - ); - } - - /** - * Test attribute "color" - */ - public function testPropertyColor() - { - $this->markTestIncomplete( - 'Test of "color" property in "Cat" model has not been implemented yet.' - ); - } - - /** - * Test attribute "declawed" - */ - public function testPropertyDeclawed() - { - $this->markTestIncomplete( - 'Test of "declawed" property in "Cat" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = Cat::getOpenApiSchema(); - $schemaArr = Cat::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/CategoryTest.php b/samples/server/petstore/php-slim4/test/Model/CategoryTest.php index b494919f769..e951b3673d3 100644 --- a/samples/server/petstore/php-slim4/test/Model/CategoryTest.php +++ b/samples/server/petstore/php-slim4/test/Model/CategoryTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -71,6 +71,12 @@ class CategoryTest extends TestCase public function testCategory() { $testCategory = new Category(); + $namespacedClassname = Category::getModelsNamespace() . '\\Category'; + $this->assertSame('\\' . Category::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( 'Test of "Category" model has not been implemented yet.' ); @@ -102,9 +108,7 @@ class CategoryTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = Category::getOpenApiSchema(); - $schemaArr = Category::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = Category::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/ClassModelTest.php b/samples/server/petstore/php-slim4/test/Model/ClassModelTest.php deleted file mode 100644 index 44549d3378f..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ClassModelTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "ClassModel" model has not been implemented yet.' - ); - } - - /** - * Test attribute "class" - */ - public function testPropertyClass() - { - $this->markTestIncomplete( - 'Test of "class" property in "ClassModel" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = ClassModel::getOpenApiSchema(); - $schemaArr = ClassModel::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/ClientTest.php b/samples/server/petstore/php-slim4/test/Model/ClientTest.php deleted file mode 100644 index 2ba029877d0..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ClientTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "Client" model has not been implemented yet.' - ); - } - - /** - * Test attribute "client" - */ - public function testPropertyClient() - { - $this->markTestIncomplete( - 'Test of "client" property in "Client" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = Client::getOpenApiSchema(); - $schemaArr = Client::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/DogAllOfTest.php b/samples/server/petstore/php-slim4/test/Model/DogAllOfTest.php deleted file mode 100644 index b9a102b409e..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/DogAllOfTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "DogAllOf" model has not been implemented yet.' - ); - } - - /** - * Test attribute "breed" - */ - public function testPropertyBreed() - { - $this->markTestIncomplete( - 'Test of "breed" property in "DogAllOf" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = DogAllOf::getOpenApiSchema(); - $schemaArr = DogAllOf::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/DogTest.php b/samples/server/petstore/php-slim4/test/Model/DogTest.php deleted file mode 100644 index 96845d82673..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/DogTest.php +++ /dev/null @@ -1,120 +0,0 @@ -markTestIncomplete( - 'Test of "Dog" model has not been implemented yet.' - ); - } - - /** - * Test attribute "className" - */ - public function testPropertyClassName() - { - $this->markTestIncomplete( - 'Test of "className" property in "Dog" model has not been implemented yet.' - ); - } - - /** - * Test attribute "color" - */ - public function testPropertyColor() - { - $this->markTestIncomplete( - 'Test of "color" property in "Dog" model has not been implemented yet.' - ); - } - - /** - * Test attribute "breed" - */ - public function testPropertyBreed() - { - $this->markTestIncomplete( - 'Test of "breed" property in "Dog" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = Dog::getOpenApiSchema(); - $schemaArr = Dog::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/EnumArraysTest.php b/samples/server/petstore/php-slim4/test/Model/EnumArraysTest.php deleted file mode 100644 index 4375e9a7c30..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/EnumArraysTest.php +++ /dev/null @@ -1,110 +0,0 @@ -markTestIncomplete( - 'Test of "EnumArrays" model has not been implemented yet.' - ); - } - - /** - * Test attribute "justSymbol" - */ - public function testPropertyJustSymbol() - { - $this->markTestIncomplete( - 'Test of "justSymbol" property in "EnumArrays" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayEnum" - */ - public function testPropertyArrayEnum() - { - $this->markTestIncomplete( - 'Test of "arrayEnum" property in "EnumArrays" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = EnumArrays::getOpenApiSchema(); - $schemaArr = EnumArrays::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/EnumClassTest.php b/samples/server/petstore/php-slim4/test/Model/EnumClassTest.php deleted file mode 100644 index 9a226bf7077..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/EnumClassTest.php +++ /dev/null @@ -1,90 +0,0 @@ -markTestIncomplete( - 'Test of "EnumClass" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = EnumClass::getOpenApiSchema(); - $schemaArr = EnumClass::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/EnumTestTest.php b/samples/server/petstore/php-slim4/test/Model/EnumTestTest.php deleted file mode 100644 index 96142f7e665..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/EnumTestTest.php +++ /dev/null @@ -1,140 +0,0 @@ -markTestIncomplete( - 'Test of "EnumTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "enumString" - */ - public function testPropertyEnumString() - { - $this->markTestIncomplete( - 'Test of "enumString" property in "EnumTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "enumStringRequired" - */ - public function testPropertyEnumStringRequired() - { - $this->markTestIncomplete( - 'Test of "enumStringRequired" property in "EnumTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "enumInteger" - */ - public function testPropertyEnumInteger() - { - $this->markTestIncomplete( - 'Test of "enumInteger" property in "EnumTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "enumNumber" - */ - public function testPropertyEnumNumber() - { - $this->markTestIncomplete( - 'Test of "enumNumber" property in "EnumTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "outerEnum" - */ - public function testPropertyOuterEnum() - { - $this->markTestIncomplete( - 'Test of "outerEnum" property in "EnumTest" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = EnumTest::getOpenApiSchema(); - $schemaArr = EnumTest::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/FileTest.php b/samples/server/petstore/php-slim4/test/Model/FileTest.php deleted file mode 100644 index 22d5778585f..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/FileTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "File" model has not been implemented yet.' - ); - } - - /** - * Test attribute "sourceURI" - */ - public function testPropertySourceURI() - { - $this->markTestIncomplete( - 'Test of "sourceURI" property in "File" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = File::getOpenApiSchema(); - $schemaArr = File::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/FormatTestTest.php b/samples/server/petstore/php-slim4/test/Model/FormatTestTest.php deleted file mode 100644 index bd01053d801..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/FormatTestTest.php +++ /dev/null @@ -1,230 +0,0 @@ -markTestIncomplete( - 'Test of "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "integer" - */ - public function testPropertyInteger() - { - $this->markTestIncomplete( - 'Test of "integer" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "int32" - */ - public function testPropertyInt32() - { - $this->markTestIncomplete( - 'Test of "int32" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "int64" - */ - public function testPropertyInt64() - { - $this->markTestIncomplete( - 'Test of "int64" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "number" - */ - public function testPropertyNumber() - { - $this->markTestIncomplete( - 'Test of "number" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "float" - */ - public function testPropertyFloat() - { - $this->markTestIncomplete( - 'Test of "float" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "double" - */ - public function testPropertyDouble() - { - $this->markTestIncomplete( - 'Test of "double" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "string" - */ - public function testPropertyString() - { - $this->markTestIncomplete( - 'Test of "string" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "byte" - */ - public function testPropertyByte() - { - $this->markTestIncomplete( - 'Test of "byte" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "binary" - */ - public function testPropertyBinary() - { - $this->markTestIncomplete( - 'Test of "binary" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "date" - */ - public function testPropertyDate() - { - $this->markTestIncomplete( - 'Test of "date" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "dateTime" - */ - public function testPropertyDateTime() - { - $this->markTestIncomplete( - 'Test of "dateTime" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "uuid" - */ - public function testPropertyUuid() - { - $this->markTestIncomplete( - 'Test of "uuid" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "password" - */ - public function testPropertyPassword() - { - $this->markTestIncomplete( - 'Test of "password" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "bigDecimal" - */ - public function testPropertyBigDecimal() - { - $this->markTestIncomplete( - 'Test of "bigDecimal" property in "FormatTest" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = FormatTest::getOpenApiSchema(); - $schemaArr = FormatTest::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/HasOnlyReadOnlyTest.php b/samples/server/petstore/php-slim4/test/Model/HasOnlyReadOnlyTest.php deleted file mode 100644 index c691248c370..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/HasOnlyReadOnlyTest.php +++ /dev/null @@ -1,110 +0,0 @@ -markTestIncomplete( - 'Test of "HasOnlyReadOnly" model has not been implemented yet.' - ); - } - - /** - * Test attribute "bar" - */ - public function testPropertyBar() - { - $this->markTestIncomplete( - 'Test of "bar" property in "HasOnlyReadOnly" model has not been implemented yet.' - ); - } - - /** - * Test attribute "foo" - */ - public function testPropertyFoo() - { - $this->markTestIncomplete( - 'Test of "foo" property in "HasOnlyReadOnly" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = HasOnlyReadOnly::getOpenApiSchema(); - $schemaArr = HasOnlyReadOnly::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/FileSchemaTestClassTest.php b/samples/server/petstore/php-slim4/test/Model/InlineObject1Test.php similarity index 58% rename from samples/server/petstore/php-slim4/test/Model/FileSchemaTestClassTest.php rename to samples/server/petstore/php-slim4/test/Model/InlineObject1Test.php index 656891ee583..c70074021a0 100644 --- a/samples/server/petstore/php-slim4/test/Model/FileSchemaTestClassTest.php +++ b/samples/server/petstore/php-slim4/test/Model/InlineObject1Test.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -23,18 +23,18 @@ namespace OpenAPIServer\Model; use PHPUnit\Framework\TestCase; -use OpenAPIServer\Model\FileSchemaTestClass; +use OpenAPIServer\Model\InlineObject1; /** - * FileSchemaTestClassTest Class Doc Comment + * InlineObject1Test Class Doc Comment * * @package OpenAPIServer\Model * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator * - * @coversDefaultClass \OpenAPIServer\Model\FileSchemaTestClass + * @coversDefaultClass \OpenAPIServer\Model\InlineObject1 */ -class FileSchemaTestClassTest extends TestCase +class InlineObject1Test extends TestCase { /** @@ -66,13 +66,29 @@ class FileSchemaTestClassTest extends TestCase } /** - * Test "FileSchemaTestClass" + * Test "InlineObject1" */ - public function testFileSchemaTestClass() + public function testInlineObject1() { - $testFileSchemaTestClass = new FileSchemaTestClass(); + $testInlineObject1 = new InlineObject1(); + $namespacedClassname = InlineObject1::getModelsNamespace() . '\\InlineObject1'; + $this->assertSame('\\' . InlineObject1::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( - 'Test of "FileSchemaTestClass" model has not been implemented yet.' + 'Test of "InlineObject1" model has not been implemented yet.' + ); + } + + /** + * Test attribute "additionalMetadata" + */ + public function testPropertyAdditionalMetadata() + { + $this->markTestIncomplete( + 'Test of "additionalMetadata" property in "InlineObject1" model has not been implemented yet.' ); } @@ -82,17 +98,7 @@ class FileSchemaTestClassTest extends TestCase public function testPropertyFile() { $this->markTestIncomplete( - 'Test of "file" property in "FileSchemaTestClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "files" - */ - public function testPropertyFiles() - { - $this->markTestIncomplete( - 'Test of "files" property in "FileSchemaTestClass" model has not been implemented yet.' + 'Test of "file" property in "InlineObject1" model has not been implemented yet.' ); } @@ -102,9 +108,7 @@ class FileSchemaTestClassTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = FileSchemaTestClass::getOpenApiSchema(); - $schemaArr = FileSchemaTestClass::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = InlineObject1::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/Model200ResponseTest.php b/samples/server/petstore/php-slim4/test/Model/InlineObjectTest.php similarity index 59% rename from samples/server/petstore/php-slim4/test/Model/Model200ResponseTest.php rename to samples/server/petstore/php-slim4/test/Model/InlineObjectTest.php index 7c4478be005..0651084a62d 100644 --- a/samples/server/petstore/php-slim4/test/Model/Model200ResponseTest.php +++ b/samples/server/petstore/php-slim4/test/Model/InlineObjectTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -23,18 +23,18 @@ namespace OpenAPIServer\Model; use PHPUnit\Framework\TestCase; -use OpenAPIServer\Model\Model200Response; +use OpenAPIServer\Model\InlineObject; /** - * Model200ResponseTest Class Doc Comment + * InlineObjectTest Class Doc Comment * * @package OpenAPIServer\Model * @author OpenAPI Generator team * @link https://github.com/openapitools/openapi-generator * - * @coversDefaultClass \OpenAPIServer\Model\Model200Response + * @coversDefaultClass \OpenAPIServer\Model\InlineObject */ -class Model200ResponseTest extends TestCase +class InlineObjectTest extends TestCase { /** @@ -66,13 +66,19 @@ class Model200ResponseTest extends TestCase } /** - * Test "Model200Response" + * Test "InlineObject" */ - public function testModel200Response() + public function testInlineObject() { - $testModel200Response = new Model200Response(); + $testInlineObject = new InlineObject(); + $namespacedClassname = InlineObject::getModelsNamespace() . '\\InlineObject'; + $this->assertSame('\\' . InlineObject::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( - 'Test of "Model200Response" model has not been implemented yet.' + 'Test of "InlineObject" model has not been implemented yet.' ); } @@ -82,17 +88,17 @@ class Model200ResponseTest extends TestCase public function testPropertyName() { $this->markTestIncomplete( - 'Test of "name" property in "Model200Response" model has not been implemented yet.' + 'Test of "name" property in "InlineObject" model has not been implemented yet.' ); } /** - * Test attribute "class" + * Test attribute "status" */ - public function testPropertyClass() + public function testPropertyStatus() { $this->markTestIncomplete( - 'Test of "class" property in "Model200Response" model has not been implemented yet.' + 'Test of "status" property in "InlineObject" model has not been implemented yet.' ); } @@ -102,9 +108,7 @@ class Model200ResponseTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = Model200Response::getOpenApiSchema(); - $schemaArr = Model200Response::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = InlineObject::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/MapTestTest.php b/samples/server/petstore/php-slim4/test/Model/MapTestTest.php deleted file mode 100644 index a430539ee2b..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/MapTestTest.php +++ /dev/null @@ -1,130 +0,0 @@ -markTestIncomplete( - 'Test of "MapTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapMapOfString" - */ - public function testPropertyMapMapOfString() - { - $this->markTestIncomplete( - 'Test of "mapMapOfString" property in "MapTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "mapOfEnumString" - */ - public function testPropertyMapOfEnumString() - { - $this->markTestIncomplete( - 'Test of "mapOfEnumString" property in "MapTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "directMap" - */ - public function testPropertyDirectMap() - { - $this->markTestIncomplete( - 'Test of "directMap" property in "MapTest" model has not been implemented yet.' - ); - } - - /** - * Test attribute "indirectMap" - */ - public function testPropertyIndirectMap() - { - $this->markTestIncomplete( - 'Test of "indirectMap" property in "MapTest" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = MapTest::getOpenApiSchema(); - $schemaArr = MapTest::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php b/samples/server/petstore/php-slim4/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php deleted file mode 100644 index 62a43f1288b..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/MixedPropertiesAndAdditionalPropertiesClassTest.php +++ /dev/null @@ -1,120 +0,0 @@ -markTestIncomplete( - 'Test of "MixedPropertiesAndAdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "uuid" - */ - public function testPropertyUuid() - { - $this->markTestIncomplete( - 'Test of "uuid" property in "MixedPropertiesAndAdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "dateTime" - */ - public function testPropertyDateTime() - { - $this->markTestIncomplete( - 'Test of "dateTime" property in "MixedPropertiesAndAdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test attribute "map" - */ - public function testPropertyMap() - { - $this->markTestIncomplete( - 'Test of "map" property in "MixedPropertiesAndAdditionalPropertiesClass" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = MixedPropertiesAndAdditionalPropertiesClass::getOpenApiSchema(); - $schemaArr = MixedPropertiesAndAdditionalPropertiesClass::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/ModelListTest.php b/samples/server/petstore/php-slim4/test/Model/ModelListTest.php deleted file mode 100644 index c1b1b98c9c0..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ModelListTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "ModelList" model has not been implemented yet.' - ); - } - - /** - * Test attribute "_123list" - */ - public function testProperty123list() - { - $this->markTestIncomplete( - 'Test of "_123list" property in "ModelList" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = ModelList::getOpenApiSchema(); - $schemaArr = ModelList::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/ModelReturnTest.php b/samples/server/petstore/php-slim4/test/Model/ModelReturnTest.php deleted file mode 100644 index 5de9db5c901..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ModelReturnTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "ModelReturn" model has not been implemented yet.' - ); - } - - /** - * Test attribute "return" - */ - public function testPropertyReturn() - { - $this->markTestIncomplete( - 'Test of "return" property in "ModelReturn" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = ModelReturn::getOpenApiSchema(); - $schemaArr = ModelReturn::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/NameTest.php b/samples/server/petstore/php-slim4/test/Model/NameTest.php deleted file mode 100644 index b663eaea7b5..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/NameTest.php +++ /dev/null @@ -1,130 +0,0 @@ -markTestIncomplete( - 'Test of "Name" model has not been implemented yet.' - ); - } - - /** - * Test attribute "name" - */ - public function testPropertyName() - { - $this->markTestIncomplete( - 'Test of "name" property in "Name" model has not been implemented yet.' - ); - } - - /** - * Test attribute "snakeCase" - */ - public function testPropertySnakeCase() - { - $this->markTestIncomplete( - 'Test of "snakeCase" property in "Name" model has not been implemented yet.' - ); - } - - /** - * Test attribute "property" - */ - public function testPropertyProperty() - { - $this->markTestIncomplete( - 'Test of "property" property in "Name" model has not been implemented yet.' - ); - } - - /** - * Test attribute "_123number" - */ - public function testProperty123number() - { - $this->markTestIncomplete( - 'Test of "_123number" property in "Name" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = Name::getOpenApiSchema(); - $schemaArr = Name::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/NumberOnlyTest.php b/samples/server/petstore/php-slim4/test/Model/NumberOnlyTest.php deleted file mode 100644 index e8140c6ee3f..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/NumberOnlyTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "NumberOnly" model has not been implemented yet.' - ); - } - - /** - * Test attribute "justNumber" - */ - public function testPropertyJustNumber() - { - $this->markTestIncomplete( - 'Test of "justNumber" property in "NumberOnly" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = NumberOnly::getOpenApiSchema(); - $schemaArr = NumberOnly::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/OrderTest.php b/samples/server/petstore/php-slim4/test/Model/OrderTest.php index d8f2cfde082..4275ab148c7 100644 --- a/samples/server/petstore/php-slim4/test/Model/OrderTest.php +++ b/samples/server/petstore/php-slim4/test/Model/OrderTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -71,6 +71,12 @@ class OrderTest extends TestCase public function testOrder() { $testOrder = new Order(); + $namespacedClassname = Order::getModelsNamespace() . '\\Order'; + $this->assertSame('\\' . Order::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( 'Test of "Order" model has not been implemented yet.' ); @@ -142,9 +148,7 @@ class OrderTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = Order::getOpenApiSchema(); - $schemaArr = Order::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = Order::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/OuterCompositeTest.php b/samples/server/petstore/php-slim4/test/Model/OuterCompositeTest.php deleted file mode 100644 index dbc2ec630c3..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/OuterCompositeTest.php +++ /dev/null @@ -1,120 +0,0 @@ -markTestIncomplete( - 'Test of "OuterComposite" model has not been implemented yet.' - ); - } - - /** - * Test attribute "myNumber" - */ - public function testPropertyMyNumber() - { - $this->markTestIncomplete( - 'Test of "myNumber" property in "OuterComposite" model has not been implemented yet.' - ); - } - - /** - * Test attribute "myString" - */ - public function testPropertyMyString() - { - $this->markTestIncomplete( - 'Test of "myString" property in "OuterComposite" model has not been implemented yet.' - ); - } - - /** - * Test attribute "myBoolean" - */ - public function testPropertyMyBoolean() - { - $this->markTestIncomplete( - 'Test of "myBoolean" property in "OuterComposite" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = OuterComposite::getOpenApiSchema(); - $schemaArr = OuterComposite::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/OuterEnumTest.php b/samples/server/petstore/php-slim4/test/Model/OuterEnumTest.php deleted file mode 100644 index fd9eec6c375..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/OuterEnumTest.php +++ /dev/null @@ -1,90 +0,0 @@ -markTestIncomplete( - 'Test of "OuterEnum" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = OuterEnum::getOpenApiSchema(); - $schemaArr = OuterEnum::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/PetTest.php b/samples/server/petstore/php-slim4/test/Model/PetTest.php index 7f1ae6b2075..d1ef40bc9d2 100644 --- a/samples/server/petstore/php-slim4/test/Model/PetTest.php +++ b/samples/server/petstore/php-slim4/test/Model/PetTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -71,6 +71,12 @@ class PetTest extends TestCase public function testPet() { $testPet = new Pet(); + $namespacedClassname = Pet::getModelsNamespace() . '\\Pet'; + $this->assertSame('\\' . Pet::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( 'Test of "Pet" model has not been implemented yet.' ); @@ -142,9 +148,7 @@ class PetTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = Pet::getOpenApiSchema(); - $schemaArr = Pet::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = Pet::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/ReadOnlyFirstTest.php b/samples/server/petstore/php-slim4/test/Model/ReadOnlyFirstTest.php deleted file mode 100644 index b3b34eaf5ca..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/ReadOnlyFirstTest.php +++ /dev/null @@ -1,110 +0,0 @@ -markTestIncomplete( - 'Test of "ReadOnlyFirst" model has not been implemented yet.' - ); - } - - /** - * Test attribute "bar" - */ - public function testPropertyBar() - { - $this->markTestIncomplete( - 'Test of "bar" property in "ReadOnlyFirst" model has not been implemented yet.' - ); - } - - /** - * Test attribute "baz" - */ - public function testPropertyBaz() - { - $this->markTestIncomplete( - 'Test of "baz" property in "ReadOnlyFirst" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = ReadOnlyFirst::getOpenApiSchema(); - $schemaArr = ReadOnlyFirst::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/SpecialModelNameTest.php b/samples/server/petstore/php-slim4/test/Model/SpecialModelNameTest.php deleted file mode 100644 index fe84830c2c5..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/SpecialModelNameTest.php +++ /dev/null @@ -1,100 +0,0 @@ -markTestIncomplete( - 'Test of "SpecialModelName" model has not been implemented yet.' - ); - } - - /** - * Test attribute "specialPropertyName" - */ - public function testPropertySpecialPropertyName() - { - $this->markTestIncomplete( - 'Test of "specialPropertyName" property in "SpecialModelName" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = SpecialModelName::getOpenApiSchema(); - $schemaArr = SpecialModelName::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/TagTest.php b/samples/server/petstore/php-slim4/test/Model/TagTest.php index 2790c8ba4db..e5bf71c6221 100644 --- a/samples/server/petstore/php-slim4/test/Model/TagTest.php +++ b/samples/server/petstore/php-slim4/test/Model/TagTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -71,6 +71,12 @@ class TagTest extends TestCase public function testTag() { $testTag = new Tag(); + $namespacedClassname = Tag::getModelsNamespace() . '\\Tag'; + $this->assertSame('\\' . Tag::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( 'Test of "Tag" model has not been implemented yet.' ); @@ -102,9 +108,7 @@ class TagTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = Tag::getOpenApiSchema(); - $schemaArr = Tag::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = Tag::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/TypeHolderDefaultTest.php b/samples/server/petstore/php-slim4/test/Model/TypeHolderDefaultTest.php deleted file mode 100644 index 63ec0b433a9..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/TypeHolderDefaultTest.php +++ /dev/null @@ -1,140 +0,0 @@ -markTestIncomplete( - 'Test of "TypeHolderDefault" model has not been implemented yet.' - ); - } - - /** - * Test attribute "stringItem" - */ - public function testPropertyStringItem() - { - $this->markTestIncomplete( - 'Test of "stringItem" property in "TypeHolderDefault" model has not been implemented yet.' - ); - } - - /** - * Test attribute "numberItem" - */ - public function testPropertyNumberItem() - { - $this->markTestIncomplete( - 'Test of "numberItem" property in "TypeHolderDefault" model has not been implemented yet.' - ); - } - - /** - * Test attribute "integerItem" - */ - public function testPropertyIntegerItem() - { - $this->markTestIncomplete( - 'Test of "integerItem" property in "TypeHolderDefault" model has not been implemented yet.' - ); - } - - /** - * Test attribute "boolItem" - */ - public function testPropertyBoolItem() - { - $this->markTestIncomplete( - 'Test of "boolItem" property in "TypeHolderDefault" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayItem" - */ - public function testPropertyArrayItem() - { - $this->markTestIncomplete( - 'Test of "arrayItem" property in "TypeHolderDefault" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = TypeHolderDefault::getOpenApiSchema(); - $schemaArr = TypeHolderDefault::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/TypeHolderExampleTest.php b/samples/server/petstore/php-slim4/test/Model/TypeHolderExampleTest.php deleted file mode 100644 index 39f547c5b5f..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/TypeHolderExampleTest.php +++ /dev/null @@ -1,150 +0,0 @@ -markTestIncomplete( - 'Test of "TypeHolderExample" model has not been implemented yet.' - ); - } - - /** - * Test attribute "stringItem" - */ - public function testPropertyStringItem() - { - $this->markTestIncomplete( - 'Test of "stringItem" property in "TypeHolderExample" model has not been implemented yet.' - ); - } - - /** - * Test attribute "numberItem" - */ - public function testPropertyNumberItem() - { - $this->markTestIncomplete( - 'Test of "numberItem" property in "TypeHolderExample" model has not been implemented yet.' - ); - } - - /** - * Test attribute "floatItem" - */ - public function testPropertyFloatItem() - { - $this->markTestIncomplete( - 'Test of "floatItem" property in "TypeHolderExample" model has not been implemented yet.' - ); - } - - /** - * Test attribute "integerItem" - */ - public function testPropertyIntegerItem() - { - $this->markTestIncomplete( - 'Test of "integerItem" property in "TypeHolderExample" model has not been implemented yet.' - ); - } - - /** - * Test attribute "boolItem" - */ - public function testPropertyBoolItem() - { - $this->markTestIncomplete( - 'Test of "boolItem" property in "TypeHolderExample" model has not been implemented yet.' - ); - } - - /** - * Test attribute "arrayItem" - */ - public function testPropertyArrayItem() - { - $this->markTestIncomplete( - 'Test of "arrayItem" property in "TypeHolderExample" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = TypeHolderExample::getOpenApiSchema(); - $schemaArr = TypeHolderExample::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Model/UserTest.php b/samples/server/petstore/php-slim4/test/Model/UserTest.php index 8f755cc9370..563fbaae4a8 100644 --- a/samples/server/petstore/php-slim4/test/Model/UserTest.php +++ b/samples/server/petstore/php-slim4/test/Model/UserTest.php @@ -10,7 +10,7 @@ */ /** - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ @@ -71,6 +71,12 @@ class UserTest extends TestCase public function testUser() { $testUser = new User(); + $namespacedClassname = User::getModelsNamespace() . '\\User'; + $this->assertSame('\\' . User::class, $namespacedClassname); + $this->assertTrue( + class_exists($namespacedClassname), + sprintf('Assertion failed that "%s" class exists', $namespacedClassname) + ); $this->markTestIncomplete( 'Test of "User" model has not been implemented yet.' ); @@ -162,9 +168,7 @@ class UserTest extends TestCase */ public function testGetOpenApiSchema() { - $schemaObject = User::getOpenApiSchema(); - $schemaArr = User::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); + $schemaArr = User::getOpenApiSchema(); $this->assertIsArray($schemaArr); } } diff --git a/samples/server/petstore/php-slim4/test/Model/XmlItemTest.php b/samples/server/petstore/php-slim4/test/Model/XmlItemTest.php deleted file mode 100644 index 699ea8db344..00000000000 --- a/samples/server/petstore/php-slim4/test/Model/XmlItemTest.php +++ /dev/null @@ -1,380 +0,0 @@ -markTestIncomplete( - 'Test of "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "attributeString" - */ - public function testPropertyAttributeString() - { - $this->markTestIncomplete( - 'Test of "attributeString" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "attributeNumber" - */ - public function testPropertyAttributeNumber() - { - $this->markTestIncomplete( - 'Test of "attributeNumber" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "attributeInteger" - */ - public function testPropertyAttributeInteger() - { - $this->markTestIncomplete( - 'Test of "attributeInteger" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "attributeBoolean" - */ - public function testPropertyAttributeBoolean() - { - $this->markTestIncomplete( - 'Test of "attributeBoolean" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "wrappedArray" - */ - public function testPropertyWrappedArray() - { - $this->markTestIncomplete( - 'Test of "wrappedArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "nameString" - */ - public function testPropertyNameString() - { - $this->markTestIncomplete( - 'Test of "nameString" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "nameNumber" - */ - public function testPropertyNameNumber() - { - $this->markTestIncomplete( - 'Test of "nameNumber" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "nameInteger" - */ - public function testPropertyNameInteger() - { - $this->markTestIncomplete( - 'Test of "nameInteger" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "nameBoolean" - */ - public function testPropertyNameBoolean() - { - $this->markTestIncomplete( - 'Test of "nameBoolean" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "nameArray" - */ - public function testPropertyNameArray() - { - $this->markTestIncomplete( - 'Test of "nameArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "nameWrappedArray" - */ - public function testPropertyNameWrappedArray() - { - $this->markTestIncomplete( - 'Test of "nameWrappedArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixString" - */ - public function testPropertyPrefixString() - { - $this->markTestIncomplete( - 'Test of "prefixString" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixNumber" - */ - public function testPropertyPrefixNumber() - { - $this->markTestIncomplete( - 'Test of "prefixNumber" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixInteger" - */ - public function testPropertyPrefixInteger() - { - $this->markTestIncomplete( - 'Test of "prefixInteger" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixBoolean" - */ - public function testPropertyPrefixBoolean() - { - $this->markTestIncomplete( - 'Test of "prefixBoolean" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixArray" - */ - public function testPropertyPrefixArray() - { - $this->markTestIncomplete( - 'Test of "prefixArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixWrappedArray" - */ - public function testPropertyPrefixWrappedArray() - { - $this->markTestIncomplete( - 'Test of "prefixWrappedArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "namespaceString" - */ - public function testPropertyNamespaceString() - { - $this->markTestIncomplete( - 'Test of "namespaceString" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "namespaceNumber" - */ - public function testPropertyNamespaceNumber() - { - $this->markTestIncomplete( - 'Test of "namespaceNumber" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "namespaceInteger" - */ - public function testPropertyNamespaceInteger() - { - $this->markTestIncomplete( - 'Test of "namespaceInteger" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "namespaceBoolean" - */ - public function testPropertyNamespaceBoolean() - { - $this->markTestIncomplete( - 'Test of "namespaceBoolean" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "namespaceArray" - */ - public function testPropertyNamespaceArray() - { - $this->markTestIncomplete( - 'Test of "namespaceArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "namespaceWrappedArray" - */ - public function testPropertyNamespaceWrappedArray() - { - $this->markTestIncomplete( - 'Test of "namespaceWrappedArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixNsString" - */ - public function testPropertyPrefixNsString() - { - $this->markTestIncomplete( - 'Test of "prefixNsString" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixNsNumber" - */ - public function testPropertyPrefixNsNumber() - { - $this->markTestIncomplete( - 'Test of "prefixNsNumber" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixNsInteger" - */ - public function testPropertyPrefixNsInteger() - { - $this->markTestIncomplete( - 'Test of "prefixNsInteger" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixNsBoolean" - */ - public function testPropertyPrefixNsBoolean() - { - $this->markTestIncomplete( - 'Test of "prefixNsBoolean" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixNsArray" - */ - public function testPropertyPrefixNsArray() - { - $this->markTestIncomplete( - 'Test of "prefixNsArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test attribute "prefixNsWrappedArray" - */ - public function testPropertyPrefixNsWrappedArray() - { - $this->markTestIncomplete( - 'Test of "prefixNsWrappedArray" property in "XmlItem" model has not been implemented yet.' - ); - } - - /** - * Test getOpenApiSchema static method - * @covers ::getOpenApiSchema - */ - public function testGetOpenApiSchema() - { - $schemaObject = XmlItem::getOpenApiSchema(); - $schemaArr = XmlItem::getOpenApiSchema(true); - $this->assertIsObject($schemaObject); - $this->assertIsArray($schemaArr); - } -} diff --git a/samples/server/petstore/php-slim4/test/Utils/ModelUtilsTraitTest.php b/samples/server/petstore/php-slim4/test/Utils/ModelUtilsTraitTest.php deleted file mode 100644 index f9611ad65df..00000000000 --- a/samples/server/petstore/php-slim4/test/Utils/ModelUtilsTraitTest.php +++ /dev/null @@ -1,99 +0,0 @@ -assertSame($expectedRef, ModelUtils::getSimpleRef($ref)); - } - - public function provideRefs() - { - return [ - 'Reference Object OAS 3.0' => [ - '#/components/schemas/Pet', 'Pet', - ], - 'Reference Object Swagger 2.0' => [ - '#/definitions/Pet', 'Pet', - ], - 'Underscored classname' => [ - '#/components/schemas/_foobar_Objects', '_foobar_Objects', - ], - 'Relative Documents With Embedded Schema' => [ - 'definitions.json#/Pet', null, - ], - 'null as argument' => [ - null, null, - ], - 'number as argument' => [ - 156, null, - ], - ]; - } - - /** - * @covers ::toModelName - * @dataProvider provideModelNames - */ - public function testToModelName($name, $prefix, $suffix, $expectedModel) - { - $this->assertSame($expectedModel, ModelUtils::toModelName($name, $prefix, $suffix)); - } - - public function provideModelNames() - { - return [ - // fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java - ['abcd', null, null, 'Abcd'], - ['some-value', null, null, 'SomeValue'], - ['some_value', null, null, 'SomeValue'], - ['$type', null, null, 'Type'], - ['123', null, null, 'Model123'], - ['$123', null, null, 'Model123'], - ['return', null, null, 'ModelReturn'], - ['200Response', null, null, 'Model200Response'], - ['abcd', 'SuperModel', null, 'SuperModelAbcd'], - ['abcd', null, 'WithEnd', 'AbcdWithEnd'], - ['abcd', 'WithStart', 'AndEnd', 'WithStartAbcdAndEnd'], - ['_foobar_Objects', null, null, 'FoobarObjects'], - [null, null, null, null], - ]; - } -} diff --git a/samples/server/petstore/php-slim4/test/Utils/StringUtilsTraitTest.php b/samples/server/petstore/php-slim4/test/Utils/StringUtilsTraitTest.php deleted file mode 100644 index 5cd52756e80..00000000000 --- a/samples/server/petstore/php-slim4/test/Utils/StringUtilsTraitTest.php +++ /dev/null @@ -1,96 +0,0 @@ -assertSame($expectedWord, StringUtils::camelize($word, $lowercaseFirstLetter)); - } - - public function provideWordsForCamelizeTest() - { - return [ - // fixtures from modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/StringUtilsTest.java - ['openApiServer/model/pet', null, 'OpenApiServerModelPet'], - ['abcd', null, 'Abcd'], - ['some-value', null, 'SomeValue'], - ['some-Value', null, 'SomeValue'], - ['some_value', null, 'SomeValue'], - ['some_Value', null, 'SomeValue'], - ['$type', null, '$Type'], - - ['abcd', true, 'abcd'], - ['some-value', true, 'someValue'], - ['some_value', true, 'someValue'], - ['Abcd', true, 'abcd'], - ['$type', true, '$type'], - - ['123', true, '123'], - ['$123', true, '$123'], - ]; - } - - /** - * @covers ::isReservedWord - * @dataProvider provideWordsForIsReservedTest - */ - public function testisReservedWord($word, $expected) - { - $this->assertSame($expected, StringUtils::isReservedWord($word)); - } - - public function provideWordsForIsReservedTest() - { - return [ - ['return', true], - ['switch', true], - ['class', true], - ['interface', true], - ['ABSTRACT', true], - ['Trait', true], - ['final', true], - ['foobar', false], - ['DateTime', false], - ['Pet', false], - [123, false], - [null, false], - ]; - } -}