1
|
|
|
# frozen_string_literal: true |
2
|
|
|
|
3
|
|
|
require_relative '../../mixin/reflection' |
4
|
|
|
require_relative '../../mixin/errors' |
5
|
|
|
|
6
|
|
|
module AMA |
7
|
|
|
module Entity |
8
|
|
|
class Mapper |
9
|
|
|
module Handler |
10
|
|
|
module Entity |
11
|
|
|
# Default entity validator |
12
|
|
|
class Validator |
13
|
|
|
INSTANCE = new |
14
|
|
|
|
15
|
|
|
# @param [Object] entity |
16
|
|
|
# @param [Mapper::Type] type |
17
|
|
|
# @param [Mapper::Context] _context |
18
|
|
|
# @return [Array<Array<Attribute, String, Segment>] List of |
19
|
|
|
# violations, combined with attribute and segment |
20
|
|
|
def validate(entity, type, _context) |
21
|
|
|
return [] if type.instance?(entity) |
22
|
|
|
["Provided object is not an instance of #{type.type}"] |
23
|
|
|
end |
24
|
|
|
|
25
|
|
|
class << self |
26
|
|
|
include Mixin::Reflection |
27
|
|
|
|
28
|
|
|
# @param [Validator] validator |
29
|
|
|
# @return [Validator] |
30
|
|
View Code Duplication |
def wrap(validator) |
|
|
|
|
31
|
|
|
handler = handler_factory(validator, INSTANCE) |
32
|
|
|
description = "Safety wrapper for #{validator}" |
33
|
|
|
wrapper = method_object(:validate, to_s: description, &handler) |
34
|
|
|
wrapper.singleton_class.instance_eval do |
35
|
|
|
include Mixin::Errors |
36
|
|
|
end |
37
|
|
|
wrapper |
38
|
|
|
end |
39
|
|
|
|
40
|
|
|
private |
41
|
|
|
|
42
|
|
|
# @param [Validator] validator |
43
|
|
|
# @param [Validator] fallback |
44
|
|
|
# @return [Proc] |
45
|
|
|
def handler_factory(validator, fallback) |
46
|
|
|
lambda do |entity, type, ctx| |
47
|
|
|
begin |
48
|
|
|
validator.validate(entity, type, ctx) do |e, t, c| |
49
|
|
|
fallback.validate(e, t, c) |
50
|
|
|
end |
51
|
|
|
rescue StandardError => e |
52
|
|
|
raise_if_internal(e) |
53
|
|
|
message = "Unexpected error from validator #{validator}" |
54
|
|
|
signature = '(entity, type, context)' |
55
|
|
|
options = { parent: e, context: ctx, signature: signature } |
56
|
|
|
compliance_error(message, **options) |
57
|
|
|
end |
58
|
|
|
end |
59
|
|
|
end |
60
|
|
|
end |
61
|
|
|
end |
62
|
|
|
end |
63
|
|
|
end |
64
|
|
|
end |
65
|
|
|
end |
66
|
|
|
end |
67
|
|
|
|