From 28e822d8705d28c1e17d6c6672cd488fd865dbe0 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 18 Jul 2023 13:10:21 +0800 Subject: [PATCH] remove php slim generator (deprecated) (#16108) --- docs/generators.md | 1 - docs/generators/php-slim-deprecated.md | 268 ----------------- .../languages/PhpSlimServerCodegen.java | 281 ------------------ .../org.openapitools.codegen.CodegenConfig | 1 - .../main/resources/php-slim-server/.htaccess | 6 - .../resources/php-slim-server/README.mustache | 170 ----------- .../php-slim-server/SlimRouter.mustache | 281 ------------------ .../abstract_authenticator.mustache | 117 -------- .../resources/php-slim-server/api.mustache | 130 -------- .../php-slim-server/api_test.mustache | 92 ------ .../php-slim-server/composer.mustache | 38 --- .../main/resources/php-slim-server/gitignore | 17 -- .../resources/php-slim-server/index.mustache | 111 ------- .../resources/php-slim-server/model.mustache | 36 --- .../php-slim-server/model_test.mustache | 98 ------ .../php-slim-server/phpcs.xml.mustache | 31 -- .../php-slim-server/phpunit.xml.mustache | 30 -- .../slim/PhpSlimServerCodegenTest.java | 89 ------ .../slim/PhpSlimServerOptionsTest.java | 53 ---- 19 files changed, 1850 deletions(-) delete mode 100644 docs/generators/php-slim-deprecated.md delete mode 100644 modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/.htaccess delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/README.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/abstract_authenticator.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/api.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/composer.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/gitignore delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/index.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/model.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/model_test.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/phpcs.xml.mustache delete mode 100644 modules/openapi-generator/src/main/resources/php-slim-server/phpunit.xml.mustache delete mode 100644 modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerCodegenTest.java delete mode 100644 modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java diff --git a/docs/generators.md b/docs/generators.md index ca61ed840c4..a964a33934b 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -119,7 +119,6 @@ The following generators are available: * [php-laravel](generators/php-laravel.md) * [php-lumen](generators/php-lumen.md) * [php-mezzio-ph](generators/php-mezzio-ph.md) -* [php-slim-deprecated (deprecated)](generators/php-slim-deprecated.md) * [php-slim4](generators/php-slim4.md) * [php-symfony](generators/php-symfony.md) * [python-aiohttp](generators/python-aiohttp.md) diff --git a/docs/generators/php-slim-deprecated.md b/docs/generators/php-slim-deprecated.md deleted file mode 100644 index e2527f1ce12..00000000000 --- a/docs/generators/php-slim-deprecated.md +++ /dev/null @@ -1,268 +0,0 @@ ---- -title: Documentation for the php-slim-deprecated Generator ---- - -## METADATA - -| Property | Value | Notes | -| -------- | ----- | ----- | -| generator name | php-slim-deprecated | pass this to the generate command after -g | -| generator stability | DEPRECATED | | -| generator type | SERVER | | -| generator language | PHP | | -| generator default templating engine | mustache | | -| helpTxt | Generates a PHP Slim Framework server library. IMPORTANT NOTE: this generator (Slim 3.x) is no longer actively maintained so please use 'php-slim4' generator instead. | | - -## CONFIG OPTIONS -These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. - -| Option | Description | Values | Default | -| ------ | ----------- | ------ | ------- | -|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| -|apiPackage|package for generated api classes| |null| -|artifactUrl|artifact URL in generated pom.xml| |null| -|artifactVersion|The version to use in the composer package version field. e.g. 1.2.3| |null| -|composerPackageName|The name to use in the composer package name field. e.g. `vendor/project` (must be lowercase and consist of words separated by `-`, `.` or `_`).| |null| -|developerOrganization|developer organization in generated pom.xml| |null| -|developerOrganizationUrl|developer organization URL in generated pom.xml| |null| -|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
**false**
The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
**true**
Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true| -|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| -|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|
**false**
No changes to the enum's are made, this is the default option.
**true**
With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false| -|invokerPackage|The main namespace to use for all classes. e.g. Yay\Pets| |null| -|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| -|licenseName|The name of the license| |null| -|modelPackage|package for generated models| |null| -|packageName|The main package name for classes. e.g. GeneratedPetstore| |null| -|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| -|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| -|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| -|srcBasePath|The directory to serve as source root.| |null| -|variableNamingConvention|naming convention of variable name, e.g. camelCase.| |camelCase| - -## IMPORT MAPPING - -| Type/Alias | Imports | -| ---------- | ------- | - - -## INSTANTIATION TYPES - -| Type/Alias | Instantiated By | -| ---------- | --------------- | -|array|array| -|map|array| - - -## LANGUAGE PRIMITIVES - - - -## RESERVED WORDS - - - -## FEATURE SET - - -### Client Modification Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|BasePath|✗|ToolingExtension -|Authorizations|✗|ToolingExtension -|UserAgent|✗|ToolingExtension -|MockServer|✗|ToolingExtension - -### Data Type Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Custom|✗|OAS2,OAS3 -|Int32|✓|OAS2,OAS3 -|Int64|✓|OAS2,OAS3 -|Float|✓|OAS2,OAS3 -|Double|✓|OAS2,OAS3 -|Decimal|✓|ToolingExtension -|String|✓|OAS2,OAS3 -|Byte|✓|OAS2,OAS3 -|Binary|✓|OAS2,OAS3 -|Boolean|✓|OAS2,OAS3 -|Date|✓|OAS2,OAS3 -|DateTime|✓|OAS2,OAS3 -|Password|✓|OAS2,OAS3 -|File|✓|OAS2 -|Uuid|✗| -|Array|✓|OAS2,OAS3 -|Null|✗|OAS3 -|AnyType|✗|OAS2,OAS3 -|Object|✓|OAS2,OAS3 -|Maps|✓|ToolingExtension -|CollectionFormat|✓|OAS2 -|CollectionFormatMulti|✓|OAS2 -|Enum|✓|OAS2,OAS3 -|ArrayOfEnum|✓|ToolingExtension -|ArrayOfModel|✓|ToolingExtension -|ArrayOfCollectionOfPrimitives|✓|ToolingExtension -|ArrayOfCollectionOfModel|✓|ToolingExtension -|ArrayOfCollectionOfEnum|✓|ToolingExtension -|MapOfEnum|✓|ToolingExtension -|MapOfModel|✓|ToolingExtension -|MapOfCollectionOfPrimitives|✓|ToolingExtension -|MapOfCollectionOfModel|✓|ToolingExtension -|MapOfCollectionOfEnum|✓|ToolingExtension - -### Documentation Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Readme|✓|ToolingExtension -|Model|✓|ToolingExtension -|Api|✓|ToolingExtension - -### Global Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Host|✓|OAS2,OAS3 -|BasePath|✓|OAS2,OAS3 -|Info|✓|OAS2,OAS3 -|Schemes|✗|OAS2,OAS3 -|PartialSchemes|✓|OAS2,OAS3 -|Consumes|✓|OAS2 -|Produces|✓|OAS2 -|ExternalDocumentation|✓|OAS2,OAS3 -|Examples|✓|OAS2,OAS3 -|XMLStructureDefinitions|✗|OAS2,OAS3 -|MultiServer|✗|OAS3 -|ParameterizedServer|✗|OAS3 -|ParameterStyling|✗|OAS3 -|Callbacks|✗|OAS3 -|LinkObjects|✗|OAS3 - -### Parameter Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Path|✓|OAS2,OAS3 -|Query|✓|OAS2,OAS3 -|Header|✓|OAS2,OAS3 -|Body|✓|OAS2 -|FormUnencoded|✓|OAS2 -|FormMultipart|✓|OAS2 -|Cookie|✓|OAS3 - -### Schema Support Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|Simple|✓|OAS2,OAS3 -|Composite|✓|OAS2,OAS3 -|Polymorphism|✗|OAS2,OAS3 -|Union|✗|OAS3 -|allOf|✗|OAS2,OAS3 -|anyOf|✗|OAS3 -|oneOf|✗|OAS3 -|not|✗|OAS3 - -### Security Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|BasicAuth|✓|OAS2,OAS3 -|ApiKey|✓|OAS2,OAS3 -|OpenIDConnect|✗|OAS3 -|BearerToken|✓|OAS3 -|OAuth2_Implicit|✓|OAS2,OAS3 -|OAuth2_Password|✗|OAS2,OAS3 -|OAuth2_ClientCredentials|✗|OAS2,OAS3 -|OAuth2_AuthorizationCode|✗|OAS2,OAS3 -|SignatureAuth|✗|OAS3 - -### Wire Format Feature -| Name | Supported | Defined By | -| ---- | --------- | ---------- | -|JSON|✓|OAS2,OAS3 -|XML|✓|OAS2,OAS3 -|PROTOBUF|✗|ToolingExtension -|Custom|✗|OAS2,OAS3 diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java deleted file mode 100644 index b235705955b..00000000000 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) - * Copyright 2018 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openapitools.codegen.languages; - -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.security.SecurityScheme; -import io.swagger.v3.oas.models.servers.Server; -import org.apache.commons.text.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.openapitools.codegen.*; -import org.openapitools.codegen.meta.GeneratorMetadata; -import org.openapitools.codegen.meta.Stability; -import org.openapitools.codegen.meta.features.*; -import org.openapitools.codegen.model.ApiInfoMap; -import org.openapitools.codegen.model.ModelMap; -import org.openapitools.codegen.model.OperationMap; -import org.openapitools.codegen.model.OperationsMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.*; - -import static org.openapitools.codegen.utils.StringUtils.camelize; - -public class PhpSlimServerCodegen extends AbstractPhpCodegen { - private final Logger LOGGER = LoggerFactory.getLogger(PhpSlimServerCodegen.class); - - public static final String USER_CLASSNAME_KEY = "userClassname"; - - protected String groupId = "org.openapitools"; - protected String artifactId = "openapi-server"; - protected String authDirName = "Auth"; - protected String authPackage = ""; - - public PhpSlimServerCodegen() { - super(); - - modifyFeatureSet(features -> features - .includeDocumentationFeatures(DocumentationFeature.Readme) - .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) - .securityFeatures(EnumSet.of( - SecurityFeature.BasicAuth, - SecurityFeature.BearerToken, - SecurityFeature.ApiKey, - SecurityFeature.OAuth2_Implicit)) - .excludeGlobalFeatures( - GlobalFeature.XMLStructureDefinitions, - GlobalFeature.Callbacks, - GlobalFeature.LinkObjects, - GlobalFeature.ParameterStyling - ) - .excludeSchemaSupportFeatures( - SchemaSupportFeature.Polymorphism - ) - ); - - generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) - .stability(Stability.DEPRECATED) - .build(); - - // clear import mapping (from default generator) as slim does not use it - // at the moment - importMapping.clear(); - - variableNamingConvention = "camelCase"; - artifactVersion = "1.0.0"; - setInvokerPackage("OpenAPIServer"); - apiPackage = invokerPackage + "\\" + apiDirName; - modelPackage = invokerPackage + "\\" + modelDirName; - authPackage = invokerPackage + "\\" + authDirName; - outputFolder = "generated-code" + File.separator + "slim"; - - modelTestTemplateFiles.put("model_test.mustache", ".php"); - // no doc files - modelDocTemplateFiles.clear(); - apiDocTemplateFiles.clear(); - - embeddedTemplateDir = templateDir = "php-slim-server"; - - additionalProperties.put(CodegenConstants.GROUP_ID, groupId); - additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); - - // override cliOptions from AbstractPhpCodegen - for (CliOption co : cliOptions) { - if (AbstractPhpCodegen.VARIABLE_NAMING_CONVENTION.equals(co.getOpt())) { - co.setDescription("naming convention of variable name, e.g. camelCase."); - co.setDefault("camelCase"); - break; - } - } - } - - @Override - public CodegenType getTag() { - return CodegenType.SERVER; - } - - @Override - public String getName() { - return "php-slim-deprecated"; - } - - @Override - public String getHelp() { - return "Generates a PHP Slim Framework server library. IMPORTANT NOTE: this generator (Slim 3.x) is no longer actively maintained so please use 'php-slim4' generator instead."; - } - - @Override - public String apiFileFolder() { - if (apiPackage.startsWith(invokerPackage + "\\")) { - // need to strip out invokerPackage from path - return (outputFolder + File.separator + toSrcPath(StringUtils.removeStart(apiPackage, invokerPackage + "\\"), srcBasePath)); - } - return (outputFolder + File.separator + toSrcPath(apiPackage, srcBasePath)); - } - - @Override - public String modelFileFolder() { - if (modelPackage.startsWith(invokerPackage + "\\")) { - // need to strip out invokerPackage from path - return (outputFolder + File.separator + toSrcPath(StringUtils.removeStart(modelPackage, invokerPackage + "\\"), srcBasePath)); - } - return (outputFolder + File.separator + toSrcPath(modelPackage, srcBasePath)); - } - - @Override - public void processOpts() { - super.processOpts(); - - if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { - // Update the invokerPackage for the default authPackage - authPackage = invokerPackage + "\\" + authDirName; - } - - // make auth src path available in mustache template - additionalProperties.put("authPackage", authPackage); - additionalProperties.put("authSrcPath", "./" + toSrcPath(authPackage, srcBasePath)); - - supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("composer.mustache", "", "composer.json")); - supportingFiles.add(new SupportingFile("index.mustache", "", "index.php")); - supportingFiles.add(new SupportingFile(".htaccess", "", ".htaccess")); - supportingFiles.add(new SupportingFile("SlimRouter.mustache", toSrcPath(invokerPackage, srcBasePath), "SlimRouter.php")); - supportingFiles.add(new SupportingFile("phpunit.xml.mustache", "", "phpunit.xml.dist")); - supportingFiles.add(new SupportingFile("phpcs.xml.mustache", "", "phpcs.xml.dist")); - } - - @Override - public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { - OperationMap operations = objs.getOperations(); - List operationList = operations.getOperation(); - addUserClassnameToOperations(operations); - escapeMediaType(operationList); - return objs; - } - - @Override - public Map postProcessSupportingFileData(Map objs) { - ApiInfoMap apiInfo = (ApiInfoMap) objs.get("apiInfo"); - for (OperationsMap api : apiInfo.getApis()) { - List operationList = api.getOperations().getOperation(); - - // Sort operations to avoid static routes shadowing - // ref: https://github.com/nikic/FastRoute/blob/master/src/DataGenerator/RegexBasedAbstract.php#L92-L101 - operationList.sort((one, another) -> { - if (one.getHasPathParams() && !another.getHasPathParams()) return 1; - if (!one.getHasPathParams() && another.getHasPathParams()) return -1; - return 0; - }); - } - return objs; - } - - @Override - public List fromSecurity(Map securitySchemeMap) { - List codegenSecurities = super.fromSecurity(securitySchemeMap); - if (Boolean.FALSE.equals(codegenSecurities.isEmpty())) { - supportingFiles.add(new SupportingFile("abstract_authenticator.mustache", toSrcPath(authPackage, srcBasePath), toAbstractName("Authenticator") + ".php")); - } - return codegenSecurities; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return toAbstractName("DefaultApi"); - } - return toAbstractName(camelize(name) + "Api"); - } - - @Override - public String toApiTestFilename(String name) { - if (name.length() == 0) { - return "DefaultApiTest"; - } - return camelize(name) + "ApiTest"; - } - - /** - * Strips out abstract prefix and suffix from classname and puts it in "userClassname" property of operations object. - * - * @param operations codegen object with operations - */ - private void addUserClassnameToOperations(OperationMap operations) { - String classname = operations.getClassname(); - classname = classname.replaceAll("^" + abstractNamePrefix, ""); - classname = classname.replaceAll(abstractNameSuffix + "$", ""); - operations.put(USER_CLASSNAME_KEY, classname); - } - - @Override - public String encodePath(String input) { - if (input == null) { - return input; - } - - // from DefaultCodegen.java - // remove \t, \n, \r - // replace \ with \\ - // replace " with \" - // outer unescape to retain the original multi-byte characters - // finally escalate characters avoiding code injection - input = super.escapeUnsafeCharacters( - StringEscapeUtils.unescapeJava( - StringEscapeUtils.escapeJava(input) - .replace("\\/", "/")) - .replaceAll("[\\t\\n\\r]", " ") - .replace("\\", "\\\\")); - // .replace("\"", "\\\"")); - - // from AbstractPhpCodegen.java - // Trim the string to avoid leading and trailing spaces. - input = input.trim(); - try { - - input = URLEncoder.encode(input, "UTF-8") - .replaceAll("\\+", "%20") - .replaceAll("\\%2F", "/") - .replaceAll("\\%7B", "{") // keep { part of complex placeholders - .replaceAll("\\%7D", "}") // } part - .replaceAll("\\%5B", "[") // [ part - .replaceAll("\\%5D", "]") // ] part - .replaceAll("\\%3A", ":") // : part - .replaceAll("\\%2B", "+") // + part - .replaceAll("\\%5C\\%5Cd", "\\\\d"); // \d part - } catch (UnsupportedEncodingException e) { - // continue - LOGGER.error(e.getMessage(), e); - } - return input; - } - - @Override - public CodegenOperation fromOperation(String path, - String httpMethod, - Operation operation, - List servers) { - CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); - op.path = encodePath(path); - return op; - } - -} diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index 2667bc37c42..b709cc0bf14 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -92,7 +92,6 @@ org.openapitools.codegen.languages.PerlClientCodegen org.openapitools.codegen.languages.PhpClientCodegen org.openapitools.codegen.languages.PhpLaravelServerCodegen org.openapitools.codegen.languages.PhpLumenServerCodegen -org.openapitools.codegen.languages.PhpSlimServerCodegen org.openapitools.codegen.languages.PhpSlim4ServerCodegen org.openapitools.codegen.languages.PhpSymfonyServerCodegen org.openapitools.codegen.languages.PhpMezzioPathHandlerServerCodegen diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/.htaccess b/modules/openapi-generator/src/main/resources/php-slim-server/.htaccess deleted file mode 100644 index f6a2ceb3952..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/.htaccess +++ /dev/null @@ -1,6 +0,0 @@ - - RewriteEngine On - RewriteCond %{REQUEST_FILENAME} !-f - RewriteCond %{REQUEST_FILENAME} !-d - RewriteRule ^ index.php [QSA,L] - \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/README.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/README.mustache deleted file mode 100644 index b9353f3127c..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/README.mustache +++ /dev/null @@ -1,170 +0,0 @@ -# {{packageName}} - PHP Slim Server library for {{appName}} - -* [OpenAPI Generator](https://openapi-generator.tech) -* [Slim Framework Documentation](https://www.slimframework.com/docs/) - -## Requirements - -* Web server with URL rewriting -* PHP 7.0 or newer - -This package contains `.htaccess` for Apache configuration. -If you use another server(Nginx, HHVM, IIS, lighttpd) check out [Web Servers](https://www.slimframework.com/docs/v3/start/web-servers.html) doc. - -## Installation via [Composer](https://getcomposer.org/) - -Navigate into your project's root directory and execute the bash command shown below. -This command downloads the Slim Framework and its third-party dependencies into your project's `vendor/` directory. -```bash -$ composer install -``` - -## Start devserver - -Run the following command in terminal to start localhost web server, assuming `./php-slim-server/` is public-accessible directory with `index.php` file: -```bash -$ php -S localhost:8888 -t php-slim-server -``` -> **Warning** This web server was designed to aid application development. -> It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. -> It is not intended to be a full-featured web server. It should not be used on a public network. - -## Tests - -### PHPUnit - -This package uses PHPUnit 6 or 7(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). - -#### Run - -Command | Target ----- | ---- -`$ composer test` | All tests -`$ composer test-apis` | Apis tests -`$ composer test-models` | Models 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): - -> 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. - -### PHP CodeSniffer - -[PHP CodeSniffer Documentation](https://github.com/squizlabs/PHP_CodeSniffer/wiki). This tool helps to follow coding style and avoid common PHP coding mistakes. - -#### Run - -```bash -$ composer phpcs -``` - -#### Config - -Package contains fully functional config `./phpcs.xml.dist` file. It checks source code against PSR-1 and PSR-2 coding standards. -Create `./phpcs.xml` in root folder to override it. More info at [Using a Default Configuration File](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#using-a-default-configuration-file) - -### PHPLint - -[PHPLint Documentation](https://github.com/overtrue/phplint). Checks PHP syntax only. - -#### Run - -```bash -$ composer phplint -``` - -## Show errors - -Switch on option in `./index.php`: -```diff - /** - * When true, additional information about exceptions are displayed by the default - * error handler. - * Default: false - */ ---- // 'displayErrorDetails' => false, -+++ 'displayErrorDetails' => true, -``` - -{{#generateApiDocs}} -## API Endpoints - -All URIs are relative to *{{{basePath}}}* - -> Important! Do not modify abstract API controllers directly! Instead extend them by implementation classes like: - -```php -// src/Api/PetApi.php - -namespace {{apiPackage}}; - -use {{apiPackage}}\AbstractPetApi; - -class PetApi extends AbstractPetApi -{ - - public function addPet($request, $response, $args) - { - // your implementation of addPet method here - } -} -``` - -Place all your implementation classes in `./src` folder accordingly. -For instance, when abstract class located at `./lib/Api/AbstractPetApi.php` you need to create implementation class at `./src/Api/PetApi.php`. - -Class | Method | HTTP request | Description ------------- | ------------- | ------------- | ------------- -{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | **{{operationId}}** | **{{httpMethod}}** {{path}} | {{{summary}}} -{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} -{{/generateApiDocs}} - -{{#generateModelDocs}} -## Models - -{{#modelPackage}} -{{#models}}{{#model}}* {{{modelPackage}}}\{{{classname}}} -{{/model}}{{/models}} -{{/modelPackage}} -{{^modelPackage}} -No model defined in this package -{{/modelPackage}} -{{/generateModelDocs}} - -{{#hasAuthMethods}} -{{#authMethods}} -{{#-last}} -## Authentication - -{{/-last}} -{{/authMethods}} -{{#authMethods}} -{{#isBasicBasic}} -### Security schema `{{name}}` -> Important! To make Basic authentication work you need to extend [\{{authPackage}}\{{abstractNamePrefix}}Authenticator{{abstractNameSuffix}}]({{authSrcPath}}/{{abstractNamePrefix}}Authenticator{{abstractNameSuffix}}.php) class by [\{{authPackage}}\BasicAuthenticator](./src/Auth/BasicAuthenticator.php) class. - -{{/isBasicBasic}} -{{#isApiKey}} -### Security schema `{{name}}` -> Important! To make ApiKey authentication work you need to extend [\{{authPackage}}\{{abstractNamePrefix}}Authenticator{{abstractNameSuffix}}]({{authSrcPath}}/{{abstractNamePrefix}}Authenticator{{abstractNameSuffix}}.php) class by [\{{authPackage}}\ApiKeyAuthenticator](./src/Auth/ApiKeyAuthenticator.php) class. - -{{/isApiKey}} -{{#isOAuth}} -### Security schema `{{name}}` -> Important! To make OAuth authentication work you need to extend [\{{authPackage}}\{{abstractNamePrefix}}Authenticator{{abstractNameSuffix}}]({{authSrcPath}}/{{abstractNamePrefix}}Authenticator{{abstractNameSuffix}}.php) class by [\{{authPackage}}\OAuthAuthenticator](./src/Auth/OAuthAuthenticator.php) class. - -Scope list: -{{#scopes}} -* `{{scope}}`{{#description}} - {{.}}{{/description}} -{{/scopes}} - -{{/isOAuth}} -{{/authMethods}} -### Advanced middleware configuration -Ref to used Slim Token Middleware [dyorg/slim-token-authentication](https://github.com/dyorg/slim-token-authentication/tree/1.x#readme) -{{/hasAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache deleted file mode 100644 index dd73535a005..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/SlimRouter.mustache +++ /dev/null @@ -1,281 +0,0 @@ - '{{httpMethod}}', - 'basePathWithoutHost' => '{{{basePathWithoutHost}}}', - 'path' => '{{{path}}}', - 'apiPackage' => '{{apiPackage}}', - 'classname' => '{{classname}}', - 'userClassname' => '{{userClassname}}', - 'operationId' => '{{operationId}}', - 'authMethods' => [ - {{#hasAuthMethods}} - {{#authMethods}} - // {{type}} security schema named '{{name}}' - {{#isBasicBasic}} - [ - 'type' => '{{type}}', - 'isBasic' => true, - 'isBearer' => false, - 'isApiKey' => false, - 'isOAuth' => false, - ], - {{/isBasicBasic}} - {{#isBasicBearer}} - [ - 'type' => '{{type}}', - 'isBasic' => true, - 'isBearer' => true, - 'isApiKey' => false, - 'isOAuth' => false, - ], - {{/isBasicBearer}} - {{#isApiKey}} - [ - 'type' => '{{type}}', - 'isBasic' => false, - 'isBearer' => false, - 'isApiKey' => true, - 'isOAuth' => false, - 'keyParamName' => '{{keyParamName}}', - 'isKeyInHeader' => {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}}, - 'isKeyInQuery' => {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}}, - 'isKeyInCookie' => {{#isKeyInCookie}}true{{/isKeyInCookie}}{{^isKeyInCookie}}false{{/isKeyInCookie}}, - ], - {{/isApiKey}} - {{#isOAuth}} - [ - 'type' => '{{type}}', - 'isBasic' => false, - 'isBearer' => false, - 'isApiKey' => false, - 'isOAuth' => true, - 'scopes' => [ - {{#scopes}} - '{{scope}}',{{#description}} // {{.}}{{/description}} - {{/scopes}} - ], - ], - {{/isOAuth}} - {{/authMethods}} - {{/hasAuthMethods}} - ], - ], - {{/operation}} - {{/operations}} - {{/apis}} - ]; - - /** - * Class constructor - * - * @param ContainerInterface|array $settings Either a ContainerInterface or an associative array of app settings - * - * @throws InvalidArgumentException When no container is provided that implements ContainerInterface - * @throws Exception When implementation class doesn't exists - */ - public function __construct($settings = []) - { - $this->slimApp = new App($settings); - - // middlewares requires Psr\Container\ContainerInterface - $container = $this->slimApp->getContainer(); - - {{#hasAuthMethods}} - $authPackage = '{{authPackage}}'; - $basicAuthenticator = function (ServerRequestInterface &$request, TokenSearch $tokenSearch) use ($authPackage) { - $message = "How about extending {{abstractNamePrefix}}Authenticator{{abstractNameSuffix}} class by {$authPackage}\BasicAuthenticator?"; - throw new Exception($message); - }; - $apiKeyAuthenticator = function (ServerRequestInterface &$request, TokenSearch $tokenSearch) use ($authPackage) { - $message = "How about extending {{abstractNamePrefix}}Authenticator{{abstractNameSuffix}} class by {$authPackage}\ApiKeyAuthenticator?"; - throw new Exception($message); - }; - $oAuthAuthenticator = function (ServerRequestInterface &$request, TokenSearch $tokenSearch) use ($authPackage) { - $message = "How about extending {{abstractNamePrefix}}Authenticator{{abstractNameSuffix}} class by {$authPackage}\OAuthAuthenticator?"; - throw new Exception($message); - }; - {{/hasAuthMethods}} - - foreach ($this->operations as $operation) { - $callback = function ($request, $response, $arguments) use ($operation) { - $message = "How about extending {$operation['classname']} by {$operation['apiPackage']}\\{$operation['userClassname']} class implementing {$operation['operationId']} as a {$operation['httpMethod']} method?"; - throw new Exception($message); - return $response->withStatus(501)->write($message); - }; - $middlewares = []; - - if (class_exists("\\{$operation['apiPackage']}\\{$operation['userClassname']}")) { - $callback = "\\{$operation['apiPackage']}\\{$operation['userClassname']}:{$operation['operationId']}"; - } - - {{#hasAuthMethods}} - foreach ($operation['authMethods'] as $authMethod) { - switch ($authMethod['type']) { - case 'http': - $authenticatorClassname = "\\{$authPackage}\\BasicAuthenticator"; - if (class_exists($authenticatorClassname)) { - $basicAuthenticator = new $authenticatorClassname($container); - } - - $middlewares[] = new TokenAuthentication($this->getTokenAuthenticationOptions([ - 'authenticator' => $basicAuthenticator, - 'regex' => $authMethod['isBearer'] ? '/Bearer\s+(.*)$/i' : '/Basic\s+(.*)$/i', - 'header' => 'Authorization', - 'parameter' => null, - 'cookie' => null, - 'argument' => null, - ])); - break; - case 'apiKey': - $authenticatorClassname = "\\{$authPackage}\\ApiKeyAuthenticator"; - if (class_exists($authenticatorClassname)) { - $apiKeyAuthenticator = new $authenticatorClassname($container); - } - - $middlewares[] = new TokenAuthentication($this->getTokenAuthenticationOptions([ - 'authenticator' => $apiKeyAuthenticator, - 'regex' => '/^(.*)$/i', - 'header' => $authMethod['isKeyInHeader'] ? $authMethod['keyParamName'] : null, - 'parameter' => $authMethod['isKeyInQuery'] ? $authMethod['keyParamName'] : null, - 'cookie' => $authMethod['isKeyInCookie'] ? $authMethod['keyParamName'] : null, - 'argument' => null, - ])); - break; - case 'oauth2': - $authenticatorClassname = "\\{$authPackage}\\OAuthAuthenticator"; - if (class_exists($authenticatorClassname)) { - $oAuthAuthenticator = new $authenticatorClassname($container, $authMethod['scopes']); - } - - $middlewares[] = new TokenAuthentication($this->getTokenAuthenticationOptions([ - 'authenticator' => $oAuthAuthenticator, - 'regex' => '/Bearer\s+(.*)$/i', - 'header' => 'Authorization', - 'parameter' => null, - 'cookie' => null, - 'argument' => null, - ])); - break; - default: - throw new Exception('Unknown authorization schema type'); - } - } - {{/hasAuthMethods}} - - $this->addRoute( - [$operation['httpMethod']], - "{$operation['basePathWithoutHost']}{$operation['path']}", - $callback, - $middlewares - )->setName($operation['operationId']); - } - } - - /** - * Merges user defined options with dynamic params - * - * @param array $options Params which need to merge into user options - * - * @return array Merged array - */ - private function getTokenAuthenticationOptions(array $options) - { - if (is_array($this->slimApp->getContainer()['tokenAuthenticationOptions']) === false) { - return $options; - } - - return array_merge($this->slimApp->getContainer()['tokenAuthenticationOptions'], $options); - } - - /** - * Add route with multiple methods - * - * @param string[] $methods Numeric array of HTTP method names - * @param string $pattern The route URI pattern - * @param callable|string $callable The route callback routine - * @param array|null $middlewares List of middlewares - * - * @return RouteInterface - * - * @throws InvalidArgumentException If the route pattern isn't a string - */ - public function addRoute(array $methods, string $pattern, $callable, $middlewares = []) - { - $route = $this->slimApp->map($methods, $pattern, $callable); - foreach ($middlewares as $middleware) { - $route->add($middleware); - } - return $route; - } - - /** - * Returns Slim Framework instance - * - * @return App - */ - public function getSlimApp() - { - return $this->slimApp; - } -} -{{/apiInfo}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/abstract_authenticator.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/abstract_authenticator.mustache deleted file mode 100644 index 58d83f85bd5..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/abstract_authenticator.mustache +++ /dev/null @@ -1,117 +0,0 @@ -container = $container; - $this->requiredScope = $requiredScope; - } - - /** - * Makes the api key validation of your application - * - * Just an example of implementation. Override this method to fit your needs - * - * @param ServerRequestInterface $request HTTP request - * @param TokenSearch $tokenSearch Middleware instance which contains api key in token - * - * @return bool Must return either true or false - * @throws UnauthorizedExceptionInterface when cannot parse token - */ - public function __invoke(ServerRequestInterface &$request, TokenSearch $tokenSearch) - { - /** - * Try find authorization token via header, parameters, cookie or attribute - * If token not found, return response with status 401 (unauthorized) - */ - $token = $tokenSearch->getToken($request); - - /** - * Verify if token is valid on database - * If token isn't valid, expired or has insufficient scope must throw an UnauthorizedExceptionInterface - */ - $user = $this->getUserByToken($token); - - /** - * Set authenticated user at attributes - */ - $request = $request->withAttribute('authenticated_user', $user); - - return true; - } -} -{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/api.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/api.mustache deleted file mode 100644 index a8611e690db..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/api.mustache +++ /dev/null @@ -1,130 +0,0 @@ -container = $container; - } - - {{#operations}} - {{#operation}} - - /** - * {{httpMethod}} {{operationId}} - {{#summary}} - * Summary: {{.}} - {{/summary}} - {{#notes}} - * Notes: {{.}} - {{/notes}} - {{#hasProduces}} - * Output-Formats: [{{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}] - {{/hasProduces}} - * - * @param ServerRequestInterface $request Request - * @param ResponseInterface $response Response - * @param array|null $args Path arguments - * - * @return ResponseInterface - * @throws Exception to force implementation class to override this method - {{#isDeprecated}} - * @deprecated - {{/isDeprecated}} - */ - public function {{operationId}}(ServerRequestInterface $request, ResponseInterface $response, array $args) - { - {{#hasHeaderParams}} - $headers = $request->getHeaders(); - {{#headerParams}} - ${{paramName}} = $request->hasHeader('{{baseName}}') ? $headers['{{baseName}}'] : null; - {{/headerParams}} - {{/hasHeaderParams}} - {{#hasPathParams}} - {{#pathParams}} - ${{paramName}} = $args['{{baseName}}']; - {{/pathParams}} - {{/hasPathParams}} - {{#hasQueryParams}} - $queryParams = $request->getQueryParams(); - {{#queryParams}} - ${{paramName}} = $request->getQueryParam('{{baseName}}'); - {{/queryParams}} - {{/hasQueryParams}} - {{#hasFormParams}} - {{#formParams}} - {{^isFile}} - ${{paramName}} = $request->getParsedBodyParam('{{baseName}}'); - {{/isFile}} - {{#isFile}} - ${{paramName}} = (key_exists('{{baseName}}', $request->getUploadedFiles())) ? $request->getUploadedFiles()['{{baseName}}'] : null; - {{/isFile}} - {{/formParams}} - {{/hasFormParams}} - {{#hasBodyParam}} - $body = $request->getParsedBody(); - {{/hasBodyParam}} - $message = "How about implementing {{nickname}} as a {{httpMethod}} method in {{apiPackage}}\{{userClassname}} class?"; - throw new Exception($message); - - return $response->write($message)->withStatus(501); - } - {{/operation}} - {{/operations}} -} diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache deleted file mode 100644 index 47c7b57c496..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/api_test.mustache +++ /dev/null @@ -1,92 +0,0 @@ - '1.1', - - /** - * Size of each chunk read from the Response body when sending to the browser. - * Default: 4096 - */ - // 'responseChunkSize' => 4096, - - /** - * If false, then no output buffering is enabled. If 'append' or 'prepend', then - * any echo or print statements are captured and are either appended or prepended - * to the Response returned from the route callable. - * Default: 'append' - */ - // 'outputBuffering' => 'append', - - /** - * When true, the route is calculated before any middleware is executed. This - * means that you can inspect route parameters in middleware if you need to. - * Default: false - */ - // 'determineRouteBeforeAppMiddleware' => false, - - /** - * When true, additional information about exceptions are displayed by the default - * error handler. - * Default: false - */ - // 'displayErrorDetails' => false, - - /** - * When true, Slim will add a Content-Length header to the response. If you are using - * a runtime analytics tool, such as New Relic, then this should be disabled. - * Default: true - */ - // 'addContentLengthHeader' => true, - - /** - * Filename for caching the FastRoute routes. Must be set to a valid filename within - * a writeable directory. If the file does not exist, then it is created with the correct - * cache information on first run. - * Set to false to disable the FastRoute cache system. - * Default: false - */ - // 'routerCacheFile' => false, -]; - -/** - * Token Middleware 1.x Options - * Options `header`, `regex`, `parameter`, `cookie`, `attribute`, `path`, `except`, `authenticator` - * are handled by SlimRouter class. These options are ignored by app and they omitted from current - * example. - * Ref: https://github.com/dyorg/slim-token-authentication/tree/1.x - */ -$config['tokenAuthenticationOptions'] = [ - /** - * Tokens are essentially passwords. You should treat them as such and you should always - * use HTTPS. If the middleware detects insecure usage over HTTP it will return unauthorized - * with a message Required HTTPS for token authentication. This rule is relaxed for requests - * on localhost. To allow insecure usage you must enable it manually by setting secure to - * false. - * Default: true - */ - // 'secure' => true, - - /** - * Alternatively you can list your development host to have relaxed security. - * Default: ['localhost', '127.0.0.1'] - */ - // 'relaxed' => ['localhost', '127.0.0.1'], - - /** - * By default on occurred a fail on authentication, is sent a response on json format with a - * message (`Invalid Token` or `Not found Token`) and with the token (if found), with status - * `401 Unauthorized`. You can customize it by setting a callable function on error option. - * Default: null - */ - // 'error' => null, -]; - -$router = new SlimRouter($config); -$app = $router->getSlimApp(); -$app->run(); diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/model.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/model.mustache deleted file mode 100644 index 96b79f5a39a..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/model.mustache +++ /dev/null @@ -1,36 +0,0 @@ - - - PHP_CodeSniffer config for {{appName}} - - - ./ - - - ./vendor - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/php-slim-server/phpunit.xml.mustache b/modules/openapi-generator/src/main/resources/php-slim-server/phpunit.xml.mustache deleted file mode 100644 index b8852944a12..00000000000 --- a/modules/openapi-generator/src/main/resources/php-slim-server/phpunit.xml.mustache +++ /dev/null @@ -1,30 +0,0 @@ - - - - - {{apiTestPath}} - - - {{modelTestPath}} - - - - - {{apiSrcPath}} - {{modelSrcPath}} - - - - - - diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerCodegenTest.java deleted file mode 100644 index 1d772b92aa3..00000000000 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerCodegenTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openapitools.codegen.slim; - -import org.openapitools.codegen.languages.PhpSlimServerCodegen; -import org.testng.Assert; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.io.File; - -public class PhpSlimServerCodegenTest { - - @Test - public void testEncodePath() { - final PhpSlimServerCodegen codegen = new PhpSlimServerCodegen(); - - Assert.assertEquals(codegen.encodePath("/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r/fake"), "/%20%27%20%22%20%3Dend%20--%20%5C%5Cr%5C%5Cn%20%5C%5Cn%20%5C%5Cr/v2%20*_/%20%27%20%22%20%3Dend%20--%20%5C%5Cr%5C%5Cn%20%5C%5Cn%20%5C%5Cr/fake"); - Assert.assertEquals(codegen.encodePath("/o\'\"briens/v2/o\'\"henry/fake"), "/o%27%22briens/v2/o%27%22henry/fake"); - Assert.assertEquals(codegen.encodePath("/comedians/Chris D\'Elia"), "/comedians/Chris%20D%27Elia"); - Assert.assertEquals(codegen.encodePath("/разработчики/Юрий Беленко"), "/%D1%80%D0%B0%D0%B7%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8/%D0%AE%D1%80%D0%B8%D0%B9%20%D0%91%D0%B5%D0%BB%D0%B5%D0%BD%D0%BA%D0%BE"); - Assert.assertEquals(codegen.encodePath("/text with multilines \\\n\\\t\\\r"), "/text%20with%20multilines%20%5C%5C%20%5C%5C%20%5C%5C"); - Assert.assertEquals(codegen.encodePath("/path with argument {value}"), "/path%20with%20argument%20{value}"); - - // few examples from Slim documentation - Assert.assertEquals(codegen.encodePath("/users[/{id}]"), "/users[/{id}]"); - Assert.assertEquals(codegen.encodePath("/news[/{year}[/{month}]]"), "/news[/{year}[/{month}]]"); - Assert.assertEquals(codegen.encodePath("/news[/{params:.*}]"), "/news[/{params:.*}]"); - Assert.assertEquals(codegen.encodePath("/users/{id:[0-9]+}"), "/users/{id:[0-9]+}"); - - // from FastRoute\RouteParser\Std.php - Assert.assertEquals(codegen.encodePath("/user/{name}[/{id:[0-9]+}]"), "/user/{name}[/{id:[0-9]+}]"); - Assert.assertEquals(codegen.encodePath("/fixedRoutePart/{varName}[/moreFixed/{varName2:\\d+}]"), "/fixedRoutePart/{varName}[/moreFixed/{varName2:\\d+}]"); - } - - @Test(dataProvider = "modelFileFolderProvider") - public void modelFileFolder(String modelPackage, String invokerPackage, String expected) { - final PhpSlimServerCodegen codegen = new PhpSlimServerCodegen(); - codegen.setModelPackage(modelPackage); - codegen.setInvokerPackage(invokerPackage); - - Assert.assertEquals(codegen.modelFileFolder(), expected); - } - - @DataProvider(name = "modelFileFolderProvider") - public Object[][] modelFileFolderProvider() { - return new Object[][] { - // {modelPackage, invokerPackage, expected} - {"Model", "Invoker", "generated-code/slim/lib/Model".replace('/', File.separatorChar)}, - {"Petstore", "Petstore", "generated-code/slim/lib".replace('/', File.separatorChar)}, - {"Package\\SubPackage\\Model", "Package\\SubPackage", "generated-code/slim/lib/Model".replace('/', File.separatorChar)}, - {"Websupport\\InvoiceValidation\\Model", "Websupport\\InvoiceValidation", "generated-code/slim/lib/Model".replace('/', File.separatorChar)}, - }; - } - - @Test(dataProvider = "apiFileFolderProvider") - public void apiFileFolder(String modelPackage, String invokerPackage, String expected) { - final PhpSlimServerCodegen codegen = new PhpSlimServerCodegen(); - codegen.setApiPackage(modelPackage); - codegen.setInvokerPackage(invokerPackage); - - Assert.assertEquals(codegen.apiFileFolder(), expected); - } - - @DataProvider(name = "apiFileFolderProvider") - public Object[][] apiFileFolderProvider() { - return new Object[][] { - // {apiPackage, invokerPackage, expected} - {"Api", "Invoker", "generated-code/slim/lib/Api".replace('/', File.separatorChar)}, - {"Petstore", "Petstore", "generated-code/slim/lib".replace('/', File.separatorChar)}, - {"Package\\SubPackage\\Api", "Package\\SubPackage", "generated-code/slim/lib/Api".replace('/', File.separatorChar)}, - {"Websupport\\InvoiceValidation\\Api", "Websupport\\InvoiceValidation", "generated-code/slim/lib/Api".replace('/', File.separatorChar)}, - }; - } -} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java deleted file mode 100644 index e436efed1a3..00000000000 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/slim/PhpSlimServerOptionsTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) - * Copyright 2018 SmartBear Software - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openapitools.codegen.slim; - -import org.openapitools.codegen.AbstractOptionsTest; -import org.openapitools.codegen.CodegenConfig; -import org.openapitools.codegen.languages.PhpSlimServerCodegen; -import org.openapitools.codegen.options.PhpSlimServerOptionsProvider; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class PhpSlimServerOptionsTest extends AbstractOptionsTest { - private PhpSlimServerCodegen clientCodegen = mock(PhpSlimServerCodegen.class, mockSettings); - - public PhpSlimServerOptionsTest() { - super(new PhpSlimServerOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void verifyOptions() { - verify(clientCodegen).setModelPackage(PhpSlimServerOptionsProvider.MODEL_PACKAGE_VALUE); - verify(clientCodegen).setApiPackage(PhpSlimServerOptionsProvider.API_PACKAGE_VALUE); - verify(clientCodegen).setParameterNamingConvention(PhpSlimServerOptionsProvider.VARIABLE_NAMING_CONVENTION_VALUE); - verify(clientCodegen).setInvokerPackage(PhpSlimServerOptionsProvider.INVOKER_PACKAGE_VALUE); - verify(clientCodegen).setPackageName(PhpSlimServerOptionsProvider.PACKAGE_NAME_VALUE); - verify(clientCodegen).setSrcBasePath(PhpSlimServerOptionsProvider.SRC_BASE_PATH_VALUE); - verify(clientCodegen).setArtifactVersion(PhpSlimServerOptionsProvider.ARTIFACT_VERSION_VALUE); - verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(PhpSlimServerOptionsProvider.SORT_PARAMS_VALUE)); - verify(clientCodegen).setEnumUnknownDefaultCase(Boolean.parseBoolean(PhpSlimServerOptionsProvider.ENUM_UNKNOWN_DEFAULT_CASE_VALUE)); - } -}