From fee5ddbb5c59d1fbc22758db426f85e9cf2be67e Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Wed, 9 Oct 2024 23:26:36 +0200 Subject: [PATCH 1/3] fix(clients): remove all client side validation expect null check --- .../codegen/AlgoliaCSharpGenerator.java | 1 - .../codegen/AlgoliaSwiftGenerator.java | 1 - scripts/pre-gen/removeExistingCodegen.ts | 2 +- templates/csharp/modelOneOf.mustache | 2 +- templates/go/api.mustache | 34 -------- templates/php/api.mustache | 38 --------- templates/php/model_generic.mustache | 79 ------------------- templates/ruby/api.mustache | 70 ---------------- templates/ruby/partial_model_generic.mustache | 75 ------------------ templates/swift/modelObject.mustache | 12 --- 10 files changed, 2 insertions(+), 312 deletions(-) diff --git a/generators/src/main/java/com/algolia/codegen/AlgoliaCSharpGenerator.java b/generators/src/main/java/com/algolia/codegen/AlgoliaCSharpGenerator.java index e9586802ca3..110ec590941 100644 --- a/generators/src/main/java/com/algolia/codegen/AlgoliaCSharpGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/AlgoliaCSharpGenerator.java @@ -46,7 +46,6 @@ public void processOpts() { additionalProperties.put("netCoreProjectFile", true); additionalProperties.put("targetFramework", "netstandard2.1;netstandard2.0"); additionalProperties.put("isSearchClient", CLIENT.equals("search")); - additionalProperties.put("validatable", false); additionalProperties.put("apiPackageName", getClientName(CLIENT)); additionalProperties.put("equatable", false); additionalProperties.put("disallowAdditionalPropertiesIfNotPresent", true); diff --git a/generators/src/main/java/com/algolia/codegen/AlgoliaSwiftGenerator.java b/generators/src/main/java/com/algolia/codegen/AlgoliaSwiftGenerator.java index af9c867aeac..c4bc5b7e596 100644 --- a/generators/src/main/java/com/algolia/codegen/AlgoliaSwiftGenerator.java +++ b/generators/src/main/java/com/algolia/codegen/AlgoliaSwiftGenerator.java @@ -183,7 +183,6 @@ public void processOpts() { additionalProperties.put(SWIFT_PACKAGE_PATH, "Sources" + File.separator + getClientName(CLIENT)); additionalProperties.put(OBJC_COMPATIBLE, false); additionalProperties.put(USE_BACKTICK_ESCAPES, true); - additionalProperties.put(VALIDATABLE, false); additionalProperties.put("hashableModels", true); additionalProperties.put("lambda.type-to-name", (Mustache.Lambda) (fragment, writer) -> writer.write(typeToName(fragment.execute()))); diff --git a/scripts/pre-gen/removeExistingCodegen.ts b/scripts/pre-gen/removeExistingCodegen.ts index 0f06ad0e561..77df986f51c 100644 --- a/scripts/pre-gen/removeExistingCodegen.ts +++ b/scripts/pre-gen/removeExistingCodegen.ts @@ -66,7 +66,7 @@ export async function removeExistingCodegen({ language, client, output }: Genera baseApiFolder = 'algoliasearch'; break; case 'ruby': - clientModel = clientName.toLowerCase(); + clientModel = client; clientApi = `${toSnakeCase(clientName)}_client.rb`; break; case 'scala': diff --git a/templates/csharp/modelOneOf.mustache b/templates/csharp/modelOneOf.mustache index 76d285ecc62..ff4196d3bd6 100644 --- a/templates/csharp/modelOneOf.mustache +++ b/templates/csharp/modelOneOf.mustache @@ -11,7 +11,7 @@ {{^vendorExtensions.x-has-child-generic}} [JsonConverter(typeof({{classname}}JsonConverter))] {{/vendorExtensions.x-has-child-generic}} - {{> visibility}} partial class {{classname}}{{#vendorExtensions.x-has-child-generic}}{{/vendorExtensions.x-has-child-generic}} : {{#lambda.joinWithComma}}AbstractSchema {{#parent}}{{{.}}} {{/parent}}{{#equatable}}IEquatable<{{classname}}> {{/equatable}}{{#validatable}}IValidatableObject {{/validatable}}{{/lambda.joinWithComma}} + {{> visibility}} partial class {{classname}}{{#vendorExtensions.x-has-child-generic}}{{/vendorExtensions.x-has-child-generic}} : {{#lambda.joinWithComma}}AbstractSchema {{#parent}}{{{.}}} {{/parent}}{{#equatable}}IEquatable<{{classname}}> {{/equatable}}{{/lambda.joinWithComma}} { {{#isNullable}} /// diff --git a/templates/go/api.mustache b/templates/go/api.mustache index 0955ae7e896..c5b644b7dcd 100644 --- a/templates/go/api.mustache +++ b/templates/go/api.mustache @@ -378,40 +378,6 @@ func (c *APIClient) {{nickname}}WithHTTPInfo({{#hasParams}}r {{#structPrefix}}{{ if r.{{paramName}} == nil { return nil, nil, reportError("Parameter `{{paramName}}` is required when calling `{{operationId}}`.") }{{/isEnumRef}}{{/isMap}}{{/isContainer}}{{/isPrimitiveType}} - {{#minItems}} - if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minItems}} { - return nil, nil, reportError("{{paramName}} must have at least {{minItems}} elements") - } - {{/minItems}} - {{#maxItems}} - if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxItems}} { - return nil, nil, reportError("{{paramName}} must have less than {{maxItems}} elements") - } - {{/maxItems}} - {{#minLength}} - if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) < {{minLength}} { - return nil, nil, reportError("{{paramName}} must have at least {{minLength}} elements") - } - {{/minLength}} - {{#maxLength}} - if len({{^isPathParam}}*{{/isPathParam}}r.{{paramName}}) > {{maxLength}} { - return nil, nil, reportError("{{paramName}} must have less than {{maxLength}} elements") - } - {{/maxLength}} - {{#minimum}} - {{^isString}} - if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} < {{minimum}} { - {{/isString}} - return nil, nil, reportError("{{paramName}} must be greater than {{minimum}}") - } - {{/minimum}} - {{#maximum}} - {{^isString}} - if {{^isPathParam}}*{{/isPathParam}}r.{{paramName}} > {{maximum}} { - {{/isString}} - return nil, nil, reportError("{{paramName}} must be less than {{maximum}}") - } - {{/maximum}} {{/required}} {{/allParams}} diff --git a/templates/php/api.mustache b/templates/php/api.mustache index 0bd978c8e23..4c02e8dc7c6 100644 --- a/templates/php/api.mustache +++ b/templates/php/api.mustache @@ -214,44 +214,6 @@ use Algolia\AlgoliaSearch\Exceptions\NotFoundException; ); } {{/required}} - {{#hasValidation}} - {{#maxLength}} - if ({{^required}}${{paramName}} !== null && {{/required}}strlen(${{paramName}}) > {{maxLength}}) { - throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); - } - {{/maxLength}} - {{#minLength}} - if ({{^required}}${{paramName}} !== null && {{/required}}strlen(${{paramName}}) < {{minLength}}) { - throw new \InvalidArgumentException('invalid length for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); - } - {{/minLength}} - {{#maximum}} - if ({{^required}}${{paramName}} !== null && {{/required}}${{paramName}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); - } - {{/maximum}} - {{#minimum}} - if ({{^required}}${{paramName}} !== null && {{/required}}${{paramName}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); - } - {{/minimum}} - {{#pattern}} - if ({{^required}}${{paramName}} !== null && {{/required}}!preg_match("{{{pattern}}}", ${{paramName}})) { - throw new \InvalidArgumentException("invalid value for \"{{paramName}}\" when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); - } - {{/pattern}} - {{#maxItems}} - if ({{^required}}${{paramName}} !== null && {{/required}}count(${{paramName}}) > {{maxItems}}) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); - } - {{/maxItems}} - {{#minItems}} - if ({{^required}}${{paramName}} !== null && {{/required}}count(${{paramName}}) < {{minItems}}) { - throw new \InvalidArgumentException('invalid value for "${{paramName}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); - } - {{/minItems}} - - {{/hasValidation}} {{/allParams}} $resourcePath = '{{{path}}}'; diff --git a/templates/php/model_generic.mustache b/templates/php/model_generic.mustache index 6ec9357d2e9..32eb4935c8f 100644 --- a/templates/php/model_generic.mustache +++ b/templates/php/model_generic.mustache @@ -178,50 +178,6 @@ class {{classname}} extends AbstractModel implements ModelInterface, \ArrayAcces {{/isContainer}} {{/isEnum}} - {{#hasValidation}} - {{#maxLength}} - if ({{^required}}isset($this->container['{{name}}']) && {{/required}}(mb_strlen($this->container['{{name}}']) > {{maxLength}})) { - $invalidProperties[] = "invalid value for '{{name}}', the character length must be smaller than or equal to {{{maxLength}}}."; - } - - {{/maxLength}} - {{#minLength}} - if ({{^required}}isset($this->container['{{name}}']) && {{/required}}(mb_strlen($this->container['{{name}}']) < {{minLength}})) { - $invalidProperties[] = "invalid value for '{{name}}', the character length must be bigger than or equal to {{{minLength}}}."; - } - - {{/minLength}} - {{#maximum}} - if ({{^required}}isset($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { - $invalidProperties[] = "invalid value for '{{name}}', must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}."; - } - - {{/maximum}} - {{#minimum}} - if ({{^required}}isset($this->container['{{name}}']) && {{/required}}($this->container['{{name}}'] <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { - $invalidProperties[] = "invalid value for '{{name}}', must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}."; - } - - {{/minimum}} - {{#pattern}} - if ({{^required}}isset($this->container['{{name}}']) && {{/required}}!preg_match("{{{pattern}}}", $this->container['{{name}}'])) { - $invalidProperties[] = "invalid value for '{{name}}', must be conform to the pattern {{{pattern}}}."; - } - - {{/pattern}} - {{#maxItems}} - if ({{^required}}isset($this->container['{{name}}']) && {{/required}}(count($this->container['{{name}}']) > {{maxItems}})) { - $invalidProperties[] = "invalid value for '{{name}}', number of items must be less than or equal to {{{maxItems}}}."; - } - - {{/maxItems}} - {{#minItems}} - if ({{^required}}isset($this->container['{{name}}']) && {{/required}}(count($this->container['{{name}}']) < {{minItems}})) { - $invalidProperties[] = "invalid value for '{{name}}', number of items must be greater than or equal to {{{minItems}}}."; - } - - {{/minItems}} - {{/hasValidation}} {{/vars}} return $invalidProperties; } @@ -288,41 +244,6 @@ class {{classname}} extends AbstractModel implements ModelInterface, \ArrayAcces } {{/isContainer}} {{/isEnum}} - {{#hasValidation}} - {{#maxLength}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(mb_strlen(${{name}}) > {{maxLength}})) { - throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than or equal to {{maxLength}}.'); - }{{/maxLength}} - {{#minLength}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(mb_strlen(${{name}}) < {{minLength}})) { - throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than or equal to {{minLength}}.'); - } - {{/minLength}} - {{#maximum}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(${{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{maximum}}.'); - } - {{/maximum}} - {{#minimum}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(${{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must be bigger than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{minimum}}.'); - } - {{/minimum}} - {{#pattern}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(!preg_match("{{{pattern}}}", ${{name}}))) { - throw new \InvalidArgumentException("invalid value for ${{name}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); - } - {{/pattern}} - {{#maxItems}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(count(${{name}}) > {{maxItems}})) { - throw new \InvalidArgumentException('invalid value for ${{name}} when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{maxItems}}.'); - }{{/maxItems}} - {{#minItems}} - if ({{^required}}!is_null(${{name}}) && {{/required}}(count(${{name}}) < {{minItems}})) { - throw new \InvalidArgumentException('invalid length for ${{name}} when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{minItems}}.'); - } - {{/minItems}} - {{/hasValidation}} $this->container['{{name}}'] = ${{name}}; return $this; diff --git a/templates/ruby/api.mustache b/templates/ruby/api.mustache index a1d2bf5f57c..2717e4cc019 100644 --- a/templates/ruby/api.mustache +++ b/templates/ruby/api.mustache @@ -97,78 +97,8 @@ module {{moduleName}} if @api_client.config.client_side_validation && {{{paramName}}}.nil? raise ArgumentError, "Parameter `{{paramName}}` is required when calling `{{operationId}}`." end - {{#isEnum}} - {{^isContainer}} - # verify enum value - allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}] - if @api_client.config.client_side_validation && !allowable_values.include?({{{paramName}}}) - raise ArgumentError, "invalid value for \"{{{paramName}}}\", must be one of #{allowable_values}" - end - {{/isContainer}} - {{/isEnum}} {{/required}} {{/isNullable}} - {{^required}} - {{#isEnum}} - {{#collectionFormat}} - allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}] - if @api_client.config.client_side_validation && !{{paramName}}.nil? && !{{{paramName}}}.all? { |item| allowable_values.include?(item) } - raise ArgumentError, "invalid value for \"{{{paramName}}}\", must include one of #{allowable_values}" - end - {{/collectionFormat}} - {{^collectionFormat}} - allowable_values = [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}] - if @api_client.config.client_side_validation && !{{paramName}}.nil? && !allowable_values.include?({{{paramName}}}) - raise ArgumentError, "invalid value for \"{{{paramName}}}\", must be one of #{allowable_values}" - end - {{/collectionFormat}} - {{/isEnum}} - {{/required}} - {{#hasValidation}} - {{#maxLength}} - if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}{{/required}}.to_s.length > {{{maxLength}}} - raise ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}"{{{paramName}}}"{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be smaller than or equal to {{{maxLength}}}.' - end - - {{/maxLength}} - {{#minLength}} - if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}{{/required}}.to_s.length < {{{minLength}}} - raise ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}"{{{paramName}}}"{{/required}}" when calling {{classname}}.{{operationId}}, the character length must be great than or equal to {{{minLength}}}.' - end - - {{/minLength}} - {{#maximum}} - if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}{{/required}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} - raise ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}"{{{paramName}}}"{{/required}}" when calling {{classname}}.{{operationId}}, must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.' - end - - {{/maximum}} - {{#minimum}} - if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}{{/required}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} - raise ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}"{{{paramName}}}"{{/required}}" when calling {{classname}}.{{operationId}}, must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.' - end - - {{/minimum}} - {{#pattern}} - pattern = {{{pattern}}} - if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}{{/required}} !~ pattern - raise ArgumentError, "invalid value for '{{#required}}{{{paramName}}}{{/required}}{{^required}}\"{{{paramName}}}\"{{/required}}' when calling {{classname}}.{{operationId}}, must conform to the pattern #{pattern}." - end - - {{/pattern}} - {{#maxItems}} - if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}{{/required}}.length > {{{maxItems}}} - raise ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}"{{{paramName}}}"{{/required}}" when calling {{classname}}.{{operationId}}, number of items must be less than or equal to {{{maxItems}}}.' - end - - {{/maxItems}} - {{#minItems}} - if @api_client.config.client_side_validation && {{^required}}!{{{paramName}}}.nil? && {{/required}}{{#required}}{{{paramName}}}{{/required}}{{^required}}{{{paramName}}}{{/required}}.length < {{{minItems}}} - raise ArgumentError, 'invalid value for "{{#required}}{{{paramName}}}{{/required}}{{^required}}"{{{paramName}}}"{{/required}}" when calling {{classname}}.{{operationId}}, number of items must be greater than or equal to {{{minItems}}}.' - end - - {{/minItems}} - {{/hasValidation}} {{/allParams}} {{#vendorExtensions}} path = '{{{path}}}'{{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{#x-is-custom-request}}{{paramName}}.to_s{{/x-is-custom-request}}{{^x-is-custom-request}}Transport.encode_uri({{paramName}}.to_s){{/x-is-custom-request}}){{/pathParams}} diff --git a/templates/ruby/partial_model_generic.mustache b/templates/ruby/partial_model_generic.mustache index a1fbfb3d2e4..1999b87cd7e 100644 --- a/templates/ruby/partial_model_generic.mustache +++ b/templates/ruby/partial_model_generic.mustache @@ -138,81 +138,6 @@ {{/getAdditionalPropertiesIsAnyType}} end - {{#vars}} - {{#isEnum}} - {{^isContainer}} - # Custom attribute writer method checking allowed values (enum). - # @param [Object] {{{name}}} Object to be assigned - def {{{name}}}=({{{name}}}) - validator = EnumAttributeValidator.new('{{{dataType}}}', [{{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}}]) - unless validator.valid?({{{name}}}) - raise ArgumentError, "invalid value for \"{{{name}}}\", must be one of #{validator.allowable_values}." - end - @{{{name}}} = {{{name}}} - end - - {{/isContainer}} - {{/isEnum}} - {{^isEnum}} - {{#hasValidation}} - # Custom attribute writer method with validation - # @param [Object] {{{name}}} Value to be assigned - def {{{name}}}=({{{name}}}) - {{^isNullable}} - if {{{name}}}.nil? - raise ArgumentError, '{{{name}}} cannot be nil' - end - - {{/isNullable}} - {{#maxLength}} - if {{#isNullable}}!{{{name}}}.nil? && {{/isNullable}}{{{name}}}.to_s.length > {{{maxLength}}} - raise ArgumentError, 'invalid value for "{{{name}}}", the character length must be smaller than or equal to {{{maxLength}}}.' - end - - {{/maxLength}} - {{#minLength}} - if {{#isNullable}}!{{{name}}}.nil? && {{/isNullable}}{{{name}}}.to_s.length < {{{minLength}}} - raise ArgumentError, 'invalid value for "{{{name}}}", the character length must be great than or equal to {{{minLength}}}.' - end - - {{/minLength}} - {{#maximum}} - if {{#isNullable}}!{{{name}}}.nil? && {{/isNullable}}{{{name}}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{{maximum}}} - raise ArgumentError, 'invalid value for "{{{name}}}", must be smaller than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}{{{maximum}}}.' - end - - {{/maximum}} - {{#minimum}} - if {{#isNullable}}!{{{name}}}.nil? && {{/isNullable}}{{{name}}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{{minimum}}} - raise ArgumentError, 'invalid value for "{{{name}}}", must be greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}{{{minimum}}}.' - end - - {{/minimum}} - {{#pattern}} - pattern = {{{pattern}}} - if {{#isNullable}}!{{{name}}}.nil? && {{/isNullable}}{{{name}}} !~ pattern - raise ArgumentError, "invalid value for \"{{{name}}}\", must conform to the pattern #{pattern}." - end - - {{/pattern}} - {{#maxItems}} - if {{#isNullable}}!{{{name}}}.nil? && {{/isNullable}}{{{name}}}.length > {{{maxItems}}} - raise ArgumentError, 'invalid value for "{{{name}}}", number of items must be less than or equal to {{{maxItems}}}.' - end - - {{/maxItems}} - {{#minItems}} - if {{#isNullable}}!{{{name}}}.nil? && {{/isNullable}}{{{name}}}.length < {{{minItems}}} - raise ArgumentError, 'invalid value for "{{{name}}}", number of items must be greater than or equal to {{{minItems}}}.' - end - - {{/minItems}} - @{{{name}}} = {{{name}}} - end - - {{/hasValidation}} - {{/isEnum}} - {{/vars}} # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(other) diff --git a/templates/swift/modelObject.mustache b/templates/swift/modelObject.mustache index fe467f0c365..d26fca206ff 100644 --- a/templates/swift/modelObject.mustache +++ b/templates/swift/modelObject.mustache @@ -10,18 +10,6 @@ {{/isEnum}} {{/vars}} {{#vars}} -{{#validatable}} -{{#hasValidation}} -{{#isString}} - static let {{{name}}}Rule = StringRule(minLength: {{#minLength}}{{{.}}}{{/minLength}}{{^minLength}}nil{{/minLength}}, maxLength: {{#maxLength}}{{{.}}}{{/maxLength}}{{^maxLength}}nil{{/maxLength}}, pattern: {{#pattern}}"{{{.}}}"{{/pattern}}{{^pattern}}nil{{/pattern}}) -{{/isString}} -{{#isNumeric}} - static let {{{name}}}Rule = NumericRule<{{{dataType}}}>(minimum: {{#minimum}}{{{.}}}{{/minimum}}{{^minimum}}nil{{/minimum}}, exclusiveMinimum: {{#exclusiveMinimum}}true{{/exclusiveMinimum}}{{^exclusiveMinimum}}false{{/exclusiveMinimum}}, maximum: {{#maximum}}{{{.}}}{{/maximum}}{{^maximum}}nil{{/maximum}}, exclusiveMaximum: {{#exclusiveMaximum}}true{{/exclusiveMaximum}}{{^exclusiveMaximum}}false{{/exclusiveMaximum}}, multipleOf: {{#multipleOf}}{{{.}}}{{/multipleOf}}{{^multipleOf}}nil{{/multipleOf}}) -{{/isNumeric}} -{{/hasValidation}} -{{/validatable}} -{{/vars}} -{{#vars}} {{#isEnum}} {{#description}}/** {{{.}}} */ {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.") From 1b4fcae58e6b6ffb1c64acb0d201b002fad17aa3 Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Wed, 9 Oct 2024 23:43:49 +0200 Subject: [PATCH 2/3] remove swift validator --- .../Sources/Core/Helpers/Validation.swift | 150 ------------------ templates/swift/tests/client/tests.mustache | 6 +- tests/output/swift/Tests/Utils/Utils.swift | 6 + 3 files changed, 8 insertions(+), 154 deletions(-) delete mode 100644 clients/algoliasearch-client-swift/Sources/Core/Helpers/Validation.swift diff --git a/clients/algoliasearch-client-swift/Sources/Core/Helpers/Validation.swift b/clients/algoliasearch-client-swift/Sources/Core/Helpers/Validation.swift deleted file mode 100644 index d2c96d41e7a..00000000000 --- a/clients/algoliasearch-client-swift/Sources/Core/Helpers/Validation.swift +++ /dev/null @@ -1,150 +0,0 @@ -// Validation.swift -// -// Created by Algolia on 08/01/2024 -// - -import Foundation - -public struct StringRule { - public init(minLength: Int? = nil, maxLength: Int? = nil, pattern: String? = nil) { - self.minLength = minLength - self.maxLength = maxLength - self.pattern = pattern - } - - public var minLength: Int? - public var maxLength: Int? - public var pattern: String? -} - -public struct NumericRule { - public init( - minimum: T? = nil, exclusiveMinimum: Bool = false, maximum: T? = nil, - exclusiveMaximum: Bool = false, multipleOf: T? = nil - ) { - self.minimum = minimum - self.exclusiveMinimum = exclusiveMinimum - self.maximum = maximum - self.exclusiveMaximum = exclusiveMaximum - self.multipleOf = multipleOf - } - - public var minimum: T? - public var exclusiveMinimum = false - public var maximum: T? - public var exclusiveMaximum = false - public var multipleOf: T? -} - -public enum StringValidationErrorKind: Error { - case minLength - case maxLength - case pattern -} - -public enum NumericValidationErrorKind: Error { - case minimum - case maximum - case multipleOf -} - -public struct ValidationError: Error { - public fileprivate(set) var kinds: Set -} - -public enum Validator { - /// Validate a string against a rule. - /// - Parameter string: The String you wish to validate. - /// - Parameter rule: The StringRule you wish to use for validation. - /// - Returns: A validated string. - /// - Throws: `ValidationError` if the string is invalid against the rule, - /// `NSError` if the rule.pattern is invalid. - public static func validate(_ string: String, against rule: StringRule) throws -> String { - var error = ValidationError(kinds: []) - if let minLength = rule.minLength, !(minLength <= string.count) { - error.kinds.insert(.minLength) - } - if let maxLength = rule.maxLength, !(string.count <= maxLength) { - error.kinds.insert(.maxLength) - } - if let pattern = rule.pattern { - let matches = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) - .matches(in: string, range: .init(location: 0, length: string.utf16.count)) - if matches.isEmpty { - error.kinds.insert(.pattern) - } - } - guard error.kinds.isEmpty else { - throw error - } - return string - } - - /// Validate a integer against a rule. - /// - Parameter numeric: The integer you wish to validate. - /// - Parameter rule: The NumericRule you wish to use for validation. - /// - Returns: A validated integer. - /// - Throws: `ValidationError` if the numeric is invalid against the rule. - public static func validate( - _ numeric: T, against rule: NumericRule - ) throws -> T { - var error = ValidationError(kinds: []) - if let minium = rule.minimum { - if !rule.exclusiveMinimum, minium > numeric { - error.kinds.insert(.minimum) - } - if rule.exclusiveMinimum, minium >= numeric { - error.kinds.insert(.minimum) - } - } - if let maximum = rule.maximum { - if !rule.exclusiveMaximum, numeric > maximum { - error.kinds.insert(.maximum) - } - if rule.exclusiveMaximum, numeric >= maximum { - error.kinds.insert(.maximum) - } - } - if let multipleOf = rule.multipleOf, !numeric.isMultiple(of: multipleOf) { - error.kinds.insert(.multipleOf) - } - guard error.kinds.isEmpty else { - throw error - } - return numeric - } - - /// Validate a fractional number against a rule. - /// - Parameter numeric: The fractional number you wish to validate. - /// - Parameter rule: The NumericRule you wish to use for validation. - /// - Returns: A validated fractional number. - /// - Throws: `ValidationError` if the numeric is invalid against the rule. - public static func validate( - _ numeric: T, against rule: NumericRule - ) throws -> T { - var error = ValidationError(kinds: []) - if let minium = rule.minimum { - if !rule.exclusiveMinimum, minium > numeric { - error.kinds.insert(.minimum) - } - if rule.exclusiveMinimum, minium >= numeric { - error.kinds.insert(.minimum) - } - } - if let maximum = rule.maximum { - if !rule.exclusiveMaximum, numeric > maximum { - error.kinds.insert(.maximum) - } - if rule.exclusiveMaximum, numeric >= maximum { - error.kinds.insert(.maximum) - } - } - if let multipleOf = rule.multipleOf, numeric.remainder(dividingBy: multipleOf) != 0 { - error.kinds.insert(.multipleOf) - } - guard error.kinds.isEmpty else { - throw error - } - return numeric - } -} diff --git a/templates/swift/tests/client/tests.mustache b/templates/swift/tests/client/tests.mustache index 90292177591..72a90668c32 100644 --- a/templates/swift/tests/client/tests.mustache +++ b/templates/swift/tests/client/tests.mustache @@ -29,16 +29,14 @@ {{/shouldScope}} {{#dynamicTemplate}}{{/dynamicTemplate}} {{#testUserAgent}} - - let pattern = "{{#lambda.escapeSlash}}{{{match.value}}}{{/lambda.escapeSlash}}" - let rule = StringRule(pattern: pattern) let userAgent = try XCTUnwrap(echoResponse.headers?["User-Agent"]) guard let userAgent = userAgent else { XCTFail("Expected user-agent header") return } - XCTAssertNoThrow(try Validator.validate(userAgent, against: rule), "Expected " + userAgent + " to match the following regex: " + pattern); + let pattern = "{{#lambda.escapeSlash}}{{{match.value}}}{{/lambda.escapeSlash}}" + XCTAssertNoThrow(try regexMatch(userAgent, against: pattern), "Expected " + userAgent + " to match the following regex: " + pattern); {{/testUserAgent}} {{#testTimeouts}} XCTAssertEqual(TimeInterval({{{matchResponseTimeout}}} / 1000), echoResponse.timeout); diff --git a/tests/output/swift/Tests/Utils/Utils.swift b/tests/output/swift/Tests/Utils/Utils.swift index f7051568d1c..9b32f210fda 100644 --- a/tests/output/swift/Tests/Utils/Utils.swift +++ b/tests/output/swift/Tests/Utils/Utils.swift @@ -95,3 +95,9 @@ public func union(expected: Any?, received: Any?) -> Any? { return received } + +public func regexMatch(_ received: String, against: String) -> Bool { + let regex = try! NSRegularExpression(pattern: against) + let range = NSRange(received.startIndex ..< received.endIndex, in: received) + return regex.firstMatch(in: received, options: [], range: range) != nil +} From cf50003dcc153d6a339c328f1f54ace862d1e19a Mon Sep 17 00:00:00 2001 From: Pierre Millot Date: Wed, 9 Oct 2024 23:46:58 +0200 Subject: [PATCH 3/3] simpler regex --- tests/output/swift/Tests/Utils/Utils.swift | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/output/swift/Tests/Utils/Utils.swift b/tests/output/swift/Tests/Utils/Utils.swift index 9b32f210fda..00f854ef46f 100644 --- a/tests/output/swift/Tests/Utils/Utils.swift +++ b/tests/output/swift/Tests/Utils/Utils.swift @@ -97,7 +97,6 @@ public func union(expected: Any?, received: Any?) -> Any? { } public func regexMatch(_ received: String, against: String) -> Bool { - let regex = try! NSRegularExpression(pattern: against) - let range = NSRange(received.startIndex ..< received.endIndex, in: received) - return regex.firstMatch(in: received, options: [], range: range) != nil + let matches = try! NSRegularExpression(pattern: against).matches(in: received, range: .init(location: 0, length: received.utf16.count)) + return !matches.isEmpty }