Property definitions

popcorn $ ValidationResult :: defaultinit
# Validation Result representation
#
# Can be convertted to a JsonObject so it can be reterned in a Json HttpResponse.
#
# Errors messages are grouped into *scopes*. A scope is a string that specify wich
# field or document the error message is related to.
class ValidationResult
	super Serializable

	# Object parsed during validation
	#
	# Can be used as a quick way to access the parsed JsonObject instead of
	# reparsing it during the answer.
	#
	# See `ObjectValidator`.
	var object: nullable JsonObject = null is writable

	# Array parsed during validation
	#
	# Can be used as a quick way to access the parsed JsonArray instead of
	# reparsing it during the answer.
	#
	# See `ArrayValidator`.
	var array: nullable JsonArray = null is writable

	# Errors found during validation
	#
	# Errors are grouped by scope.
	var errors = new HashMap[String, Array[String]]

	# Generate a new error `message` into `scope`
	fun add_error(scope, message: String) do
		if not errors.has_key(scope) then
			errors[scope] = new Array[String]
		end
		errors[scope].add message
	end

	# Get the errors for `scope`
	fun error(scope: String): Array[String] do
		if not errors.has_key(scope) then
			return new Array[String]
		end
		return errors[scope]
	end

	# Does `self` contains `errors`?
	fun has_error: Bool do return errors.not_empty

	redef fun core_serialize_to(v) do
		var errors = new JsonObject
		for k, e in self.errors do
			errors[k] = new JsonArray.from(e)
		end
		v.serialize_attribute("has_error", has_error)
		v.serialize_attribute("errors", errors)
	end

	# Returns the validation result as a pretty formated string
	fun to_pretty_string: String do
		var b = new Buffer
		if not has_error then
			b.append "Everything is correct\n"
		else
			b.append "There is errors\n\n"
			for k, v in errors do
				b.append "{k}:\n"
				for vv in v do
					b.append "\t{vv}\n"
				end
				b.append "\n"
			end
		end
		return b.write_to_string
	end
end
lib/popcorn/pop_validation.nit:93,1--168,3