|
1
|
|
|
# frozen_string_literal: true |
|
2
|
|
|
|
|
3
|
|
|
require_relative '../denormalizer' |
|
4
|
|
|
require_relative '../../mixin/reflection' |
|
5
|
|
|
require_relative '../../mixin/errors' |
|
6
|
|
|
|
|
7
|
|
|
module AMA |
|
8
|
|
|
module Entity |
|
9
|
|
|
class Mapper |
|
10
|
|
|
module API |
|
11
|
|
|
module Default |
|
12
|
|
|
# Default denormalization processor |
|
13
|
|
|
class Denormalizer < API::Denormalizer |
|
14
|
|
|
include Mixin::Reflection |
|
15
|
|
|
include Mixin::Errors |
|
16
|
|
|
|
|
17
|
|
|
INSTANCE = new |
|
18
|
|
|
|
|
19
|
|
|
# @param [Hash] source |
|
20
|
|
|
# @param [AMA::Entity::Mapper::Type] type |
|
21
|
|
|
# @param [AMA::Entity::Mapper::Context] context |
|
22
|
|
|
def denormalize(source, type, context = nil) |
|
23
|
|
|
validate_source!(source, type, context) |
|
24
|
|
|
entity = type.factory.create(type, source, context) |
|
25
|
|
|
type.attributes.values.each do |attribute| |
|
26
|
|
|
next if attribute.virtual |
|
27
|
|
|
[attribute.name.to_s, attribute.name].each do |name| |
|
28
|
|
|
next unless source.key?(name) |
|
29
|
|
|
set_object_attribute(entity, name, source[name]) |
|
30
|
|
|
end |
|
31
|
|
|
end |
|
32
|
|
|
entity |
|
33
|
|
|
end |
|
34
|
|
|
|
|
35
|
|
|
private |
|
36
|
|
|
|
|
37
|
|
|
def validate_source!(source, type, context) |
|
38
|
|
|
return if source.is_a?(Hash) |
|
39
|
|
|
message = "Expected Hash, #{source.class} provided " \ |
|
40
|
|
|
"(while denormalizing #{type})" |
|
41
|
|
|
mapping_error(message, context: context) |
|
42
|
|
|
end |
|
43
|
|
|
end |
|
44
|
|
|
end |
|
45
|
|
|
end |
|
46
|
|
|
end |
|
47
|
|
|
end |
|
48
|
|
|
end |
|
49
|
|
|
|