|
1
|
|
|
# frozen_string_literal: true |
|
2
|
|
|
|
|
3
|
|
|
require_relative '../entity_validator' |
|
4
|
|
|
require_relative '../../type/attribute' |
|
5
|
|
|
|
|
6
|
|
|
module AMA |
|
7
|
|
|
module Entity |
|
8
|
|
|
class Mapper |
|
9
|
|
|
module API |
|
10
|
|
|
module Wrapper |
|
11
|
|
|
# Default entity validation |
|
12
|
|
|
class EntityValidator < API::EntityValidator |
|
13
|
|
|
# @param [AMA::Entity::Mapper::API::EntityValidator] validator |
|
14
|
|
|
def initialize(validator) |
|
15
|
|
|
@validator = validator |
|
16
|
|
|
end |
|
17
|
|
|
|
|
18
|
|
|
# @param [Object] entity |
|
19
|
|
|
# @param [Mapper::Type::Concrete] type |
|
20
|
|
|
# @param [Mapper::Context] context |
|
21
|
|
|
# @return [Array<Array<Attribute, String, Segment>] List of |
|
22
|
|
|
# violations, combined with attribute and segment |
|
23
|
|
|
def validate(entity, type, context) |
|
24
|
|
|
result = @validator.validate(entity, type, context) do |e, t, c| |
|
25
|
|
|
API::Default::EntityValidator::INSTANCE.validate(e, t, c) |
|
26
|
|
|
end |
|
27
|
|
|
verify_result!(result, type, context) |
|
28
|
|
|
result |
|
29
|
|
|
rescue StandardError => e |
|
30
|
|
|
raise_if_internal(e) |
|
31
|
|
|
message = "Error during #{type} validation (entity: #{entity})" |
|
32
|
|
|
if e.is_a?(ArgumentError) |
|
33
|
|
|
message += '. Does provided validator have ' \ |
|
34
|
|
|
'(entity, type, context) signature?' |
|
35
|
|
|
end |
|
36
|
|
|
compliance_error(message, context: context, parent: e) |
|
37
|
|
|
end |
|
38
|
|
|
|
|
39
|
|
|
private |
|
40
|
|
|
|
|
41
|
|
|
def verify_result!(result, type, context) |
|
42
|
|
|
unless result.is_a?(Array) |
|
43
|
|
|
message = "Validator #{@validator} for type #{type} " \ |
|
44
|
|
|
'had to return list of violations, ' \ |
|
45
|
|
|
"#{result} was received instead" |
|
46
|
|
|
compliance_error(message, context: context) |
|
47
|
|
|
end |
|
48
|
|
|
result.each do |violation| |
|
49
|
|
|
verify_violation!(violation, type, context) |
|
50
|
|
|
end |
|
51
|
|
|
end |
|
52
|
|
|
|
|
53
|
|
|
def verify_violation!(violation, type, context) |
|
54
|
|
|
message = "Validator #{@validator} for type #{type} " \ |
|
55
|
|
|
"has returned #{violation} as violation " \ |
|
56
|
|
|
'([attribute, violation, path segment] expected)' |
|
57
|
|
|
unless violation.is_a?(Array) || violation.size == 3 |
|
58
|
|
|
compliance_error(message, context: context) |
|
59
|
|
|
end |
|
60
|
|
|
conditions = [ |
|
61
|
|
|
violation[0].is_a?(Type::Attribute), |
|
62
|
|
|
violation[1].is_a?(String), |
|
63
|
|
|
violation[2].is_a?(Path::Segment) || violation[2].nil? |
|
64
|
|
|
] |
|
65
|
|
|
return if conditions.all?(&:itself) |
|
66
|
|
|
compliance_error(message, context: context) |
|
67
|
|
|
end |
|
68
|
|
|
end |
|
69
|
|
|
end |
|
70
|
|
|
end |
|
71
|
|
|
end |
|
72
|
|
|
end |
|
73
|
|
|
end |
|
74
|
|
|
|