1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
|
# frozen_string_literal: true
require 'dry/types/fn_container'
module Dry
module Types
# The built-in Hash type can be defined in terms of keys and associated types
# its values can contain. Such definitions are named {Schema}s and defined
# as lists of {Key} types.
#
# @see Dry::Types::Schema::Key
#
# {Schema} evaluates default values for keys missing in input hash
#
# @see Dry::Types::Default#evaluate
# @see Dry::Types::Default::Callable#evaluate
#
# {Schema} implements Enumerable using its keys as collection.
#
# @api public
class Schema < Hash
NO_TRANSFORM = Dry::Types::FnContainer.register { |x| x }
SYMBOLIZE_KEY = Dry::Types::FnContainer.register(:to_sym.to_proc)
include ::Enumerable
# @return [Array[Dry::Types::Schema::Key]]
attr_reader :keys
# @return [Hash[Symbol, Dry::Types::Schema::Key]]
attr_reader :name_key_map
# @return [#call]
attr_reader :transform_key
# @param [Class] _primitive
# @param [Hash] options
#
# @option options [Array[Dry::Types::Schema::Key]] :keys
# @option options [String] :key_transform_fn
#
# @api private
def initialize(_primitive, **options)
@keys = options.fetch(:keys)
@name_key_map = keys.each_with_object({}) do |key, idx|
idx[key.name] = key
end
key_fn = options.fetch(:key_transform_fn, NO_TRANSFORM)
@transform_key = Dry::Types::FnContainer[key_fn]
super
end
# @param [Hash] hash
#
# @return [Hash{Symbol => Object}]
#
# @api private
def call_unsafe(hash, options = EMPTY_HASH)
resolve_unsafe(coerce(hash), options)
end
# @param [Hash] hash
#
# @return [Hash{Symbol => Object}]
#
# @api private
def call_safe(hash, options = EMPTY_HASH)
resolve_safe(coerce(hash) { return yield }, options) { return yield }
end
# @param [Hash] hash
#
# @option options [Boolean] :skip_missing If true don't raise error if on missing keys
# @option options [Boolean] :resolve_defaults If false default value
# won't be evaluated for missing key
# @return [Hash{Symbol => Object}]
#
# @api public
def apply(hash, options = EMPTY_HASH)
call_unsafe(hash, options)
end
# @param [Hash] hash
#
# @yieldparam [Failure] failure
# @yieldreturn [Result]
#
# @return [Logic::Result]
# @return [Object] if coercion fails and a block is given
#
# @api public
def try(input)
if primitive?(input)
success = true
output = {}
result = {}
input.each do |key, value|
k = @transform_key.(key)
type = @name_key_map[k]
if type
key_result = type.try(value)
result[k] = key_result
output[k] = key_result.input
success &&= key_result.success?
elsif strict?
success = false
end
end
if output.size < keys.size
resolve_missing_keys(output, options) do
success = false
end
end
success &&= primitive?(output)
if success
failure = nil
else
error = CoercionError.new("#{input} doesn't conform schema", meta: result)
failure = failure(output, error)
end
else
failure = failure(input, CoercionError.new("#{input} must be a hash"))
end
if failure.nil?
success(output)
elsif block_given?
yield(failure)
else
failure
end
end
# @param meta [Boolean] Whether to dump the meta to the AST
#
# @return [Array] An AST representation
#
# @api public
def to_ast(meta: true)
if RUBY_VERSION >= "2.5"
opts = options.slice(:key_transform_fn, :type_transform_fn, :strict)
else
opts = options.select { |k, _|
k == :key_transform_fn || k == :type_transform_fn || k == :strict
}
end
[
:schema,
[keys.map { |key| key.to_ast(meta: meta) },
opts,
meta ? self.meta : EMPTY_HASH]
]
end
# Whether the schema rejects unknown keys
#
# @return [Boolean]
#
# @api public
def strict?
options.fetch(:strict, false)
end
# Make the schema intolerant to unknown keys
#
# @return [Schema]
#
# @api public
def strict(strict = true)
with(strict: strict)
end
# Injects a key transformation function
#
# @param [#call,nil] proc
# @param [#call,nil] block
#
# @return [Schema]
#
# @api public
def with_key_transform(proc = nil, &block)
fn = proc || block
raise ArgumentError, 'a block or callable argument is required' if fn.nil?
handle = Dry::Types::FnContainer.register(fn)
with(key_transform_fn: handle)
end
# Whether the schema transforms input keys
#
# @return [Boolean]
#
# @api public
def transform_keys?
!options[:key_transform_fn].nil?
end
# @overload schema(type_map, meta = EMPTY_HASH)
# @param [{Symbol => Dry::Types::Nominal}] type_map
# @param [Hash] meta
# @return [Dry::Types::Schema]
#
# @overload schema(keys)
# @param [Array<Dry::Types::Schema::Key>] key List of schema keys
# @param [Hash] meta
# @return [Dry::Types::Schema]
#
# @api public
def schema(keys_or_map)
if keys_or_map.is_a?(::Array)
new_keys = keys_or_map
else
new_keys = build_keys(keys_or_map)
end
keys = merge_keys(self.keys, new_keys)
Schema.new(primitive, **options, keys: keys, meta: meta)
end
# Iterate over each key type
#
# @return [Array<Dry::Types::Schema::Key>,Enumerator]
#
# @api public
def each(&block)
keys.each(&block)
end
# Whether the schema has the given key
#
# @param [Symbol] name Key name
#
# @return [Boolean]
#
# @api public
def key?(name)
name_key_map.key?(name)
end
# Fetch key type by a key name
#
# Behaves as ::Hash#fetch
#
# @overload key(name, fallback = Undefined)
# @param [Symbol] name Key name
# @param [Object] fallback Optional fallback, returned if key is missing
# @return [Dry::Types::Schema::Key,Object] key type or fallback if key is not in schema
#
# @overload key(name, &block)
# @param [Symbol] name Key name
# @param [Proc] block Fallback block, runs if key is missing
# @return [Dry::Types::Schema::Key,Object] key type or block value if key is not in schema
#
# @api public
def key(name, fallback = Undefined, &block)
if Undefined.equal?(fallback)
name_key_map.fetch(name, &block)
else
name_key_map.fetch(name, fallback)
end
end
# @return [Boolean]
#
# @api public
def constrained?
true
end
# @return [Lax]
#
# @api public
def lax
Lax.new(schema(keys.map(&:lax)))
end
private
# @param [Array<Dry::Types::Schema::Keys>] keys
#
# @return [Dry::Types::Schema]
#
# @api private
def merge_keys(*keys)
keys
.flatten(1)
.each_with_object({}) { |key, merged| merged[key.name] = key }
.values
end
# Validate and coerce a hash. Raise an exception on any error
#
# @api private
#
# @return [Hash]
def resolve_unsafe(hash, options = EMPTY_HASH)
result = {}
hash.each do |key, value|
k = @transform_key.(key)
type = @name_key_map[k]
if type
begin
result[k] = type.call_unsafe(value)
rescue ConstraintError => e
raise SchemaError.new(type.name, value, e.result)
rescue CoercionError => e
raise SchemaError.new(type.name, value, e.message)
end
elsif strict?
raise unexpected_keys(hash.keys)
end
end
resolve_missing_keys(result, options) if result.size < keys.size
result
end
# Validate and coerce a hash. Call a block and halt on any error
#
# @api private
#
# @return [Hash]
def resolve_safe(hash, options = EMPTY_HASH, &block)
result = {}
hash.each do |key, value|
k = @transform_key.(key)
type = @name_key_map[k]
if type
result[k] = type.call_safe(value, &block)
elsif strict?
yield
end
end
resolve_missing_keys(result, options, &block) if result.size < keys.size
result
end
# Try to add missing keys to the hash
#
# @api private
def resolve_missing_keys(hash, options)
skip_missing = options.fetch(:skip_missing, false)
resolve_defaults = options.fetch(:resolve_defaults, true)
keys.each do |key|
next if hash.key?(key.name)
if key.default? && resolve_defaults
hash[key.name] = key.call_unsafe(Undefined)
elsif key.required? && !skip_missing
if block_given?
return yield
else
raise missing_key(key.name)
end
end
end
end
# @param hash_keys [Array<Symbol>]
#
# @return [UnknownKeysError]
#
# @api private
def unexpected_keys(hash_keys)
extra_keys = hash_keys.map(&transform_key) - name_key_map.keys
UnknownKeysError.new(extra_keys)
end
# @return [MissingKeyError]
#
# @api private
def missing_key(key)
MissingKeyError.new(key)
end
end
end
end
|