Skip to content

Commit

Permalink
FIX: Validate each value in an array custom field separately (discour…
Browse files Browse the repository at this point in the history
  • Loading branch information
danielwaterworth authored Dec 7, 2023
1 parent bf48e14 commit 611acaa
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions app/models/concerns/has_custom_fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ def append_field(target, key, value)
end
end

def array_type?
Array === type
end

def validate(obj, name, value)
return if value.nil?

Expand All @@ -29,7 +33,7 @@ def validate(obj, name, value)
end

def serialize(value)
if value.is_a?(Hash) || type == :json || (Array === type && type[0] == :json)
if value.is_a?(Hash) || type == :json || (array_type? && type[0] == :json)
value.to_json
elsif TrueClass === value
"t"
Expand All @@ -45,7 +49,7 @@ def deserialize(key, value, return_array)

array = nil

if Array === type
if array_type?
type = type[0]
array = true if return_array
end
Expand Down Expand Up @@ -110,14 +114,15 @@ def append_custom_field(target, key, value)
def register_custom_field_type(name, type, max_length: nil)
max_length ||= DEFAULT_FIELD_DESCRIPTOR.max_length

if Array === type
descriptor = FieldDescriptor.new(type, max_length)
custom_field_meta_data[name] = descriptor

if descriptor.array_type?
Discourse.deprecate(
"Array types for custom fields are deprecated, use type :json instead",
drop_from: "3.3.0",
)
end

custom_field_meta_data[name] = FieldDescriptor.new(type, max_length)
end

def get_custom_field_descriptor(name)
Expand Down Expand Up @@ -273,7 +278,7 @@ def save_custom_fields(force = false)
descriptor = self.class.get_custom_field_descriptor(key)
field_type = descriptor.type

if Array === field_type || (field_type != :json && Array === value)
if descriptor.array_type? || (field_type != :json && Array === value)
value = Array(value || [])
value.compact!
sub_type = field_type[0]
Expand Down Expand Up @@ -344,7 +349,13 @@ def custom_fields_max_items

def custom_fields_value_length
custom_fields.each do |name, value|
self.class.get_custom_field_descriptor(name).validate(self, name, value)
descriptor = self.class.get_custom_field_descriptor(name)

if descriptor.array_type?
Array(value).each { |v| descriptor.validate(self, name, v) }
else
descriptor.validate(self, name, value)
end
end
end
end

0 comments on commit 611acaa

Please sign in to comment.