1
|
|
|
# frozen_string_literal: true |
2
|
|
|
|
3
|
|
|
require_relative '../attribute_validator' |
4
|
|
|
|
5
|
|
|
module AMA |
6
|
|
|
module Entity |
7
|
|
|
class Mapper |
8
|
|
|
module API |
9
|
|
|
module Default |
10
|
|
|
# Default validator for single attribute |
11
|
|
|
class AttributeValidator < API::AttributeValidator |
12
|
|
|
INSTANCE = new |
13
|
|
|
|
14
|
|
|
# @param [Object] value Attribute value |
15
|
|
|
# @param [AMA::Entity::Mapper::Type::Attribute] attribute |
16
|
|
|
# @return [Array<String>] Single violation, list of violations |
17
|
|
|
def validate(value, attribute, *) |
18
|
|
|
violations = validate_internal(value, attribute) |
19
|
|
|
violations.nil? ? [] : [violations] |
20
|
|
|
end |
21
|
|
|
|
22
|
|
|
private |
23
|
|
|
|
24
|
|
|
def validate_internal(value, attribute) |
25
|
|
|
if illegal_nil?(value, attribute) |
26
|
|
|
return "Attribute #{attribute} could not be nil" |
27
|
|
|
end |
28
|
|
|
if invalid_type?(value, attribute) |
29
|
|
|
return "Provided value #{value} doesn't conform to " \ |
30
|
|
|
"any of attribute #{attribute} types (#{attribute.types})" |
31
|
|
|
end |
32
|
|
|
return unless illegal_value?(value, attribute) |
33
|
|
|
"Provided value #{value} doesn't match default value (#{value})" \ |
34
|
|
|
" or any of allowed values (#{attribute.values})" |
35
|
|
|
end |
36
|
|
|
|
37
|
|
|
# @param [Object] value Attribute value |
38
|
|
|
# @param [AMA::Entity::Mapper::Type::Attribute] attribute |
39
|
|
|
# @return [TrueClass, FalseClass] |
40
|
|
|
def illegal_nil?(value, attribute) |
41
|
|
|
value.nil? && !attribute.nullable |
42
|
|
|
end |
43
|
|
|
|
44
|
|
|
# @param [Object] value Attribute value |
45
|
|
|
# @param [AMA::Entity::Mapper::Type::Attribute] attribute |
46
|
|
|
# @return [TrueClass, FalseClass] |
47
|
|
|
def invalid_type?(value, attribute) |
48
|
|
|
attribute.types.all? do |type| |
49
|
|
|
!type.respond_to?(:instance?) || !type.instance?(value) |
50
|
|
|
end |
51
|
|
|
end |
52
|
|
|
|
53
|
|
|
# @param [Object] value Attribute value |
54
|
|
|
# @param [AMA::Entity::Mapper::Type::Attribute] attribute |
55
|
|
|
# @return [TrueClass, FalseClass] |
56
|
|
|
def illegal_value?(value, attribute) |
57
|
|
|
return false if value == attribute.default |
58
|
|
|
return false if attribute.values.empty? || attribute.values.nil? |
59
|
|
|
!attribute.values.include?(value) |
60
|
|
|
end |
61
|
|
|
end |
62
|
|
|
end |
63
|
|
|
end |
64
|
|
|
end |
65
|
|
|
end |
66
|
|
|
end |
67
|
|
|
|