Debian Codegraph @

lib/JSON/Schema/Modern/Vocabulary/Validation.pm

raw
1 use strict;
2 use warnings;
3 package JSON::Schema::Modern::Vocabulary::Validation;
4 # vim: set ts=8 sts=2 sw=2 tw=100 et :
5 # ABSTRACT: Implementation of the JSON Schema Validation vocabulary
6
7 our $VERSION = '0.650';
8
9 use 5.020;
10 use Moo;
11 use strictures 2;
12 use stable 0.031 'postderef';
13 use experimental 'signatures';
14 no autovivification warn => qw(fetch store exists delete);
15 use if "$]" >= 5.022, experimental => 're_strict';
16 no if "$]" >= 5.031009, feature => 'indirect';
17 no if "$]" >= 5.033001, feature => 'multidimensional';
18 no if "$]" >= 5.033006, feature => 'bareword_filehandles';
19 no if "$]" >= 5.041009, feature => 'smartmatch';
20 no feature 'switch';
21 use if "$]" < 5.041010, 'List::Util' => 'any';
22 use if "$]" >= 5.041010, experimental => 'keyword_any';
23 use Scalar::Util 'looks_like_number';
24 use JSON::Schema::Modern::Utilities qw(is_type get_type is_bignum is_equal is_elements_unique E assert_keyword_type assert_pattern jsonp sprintf_num);
25 use Math::BigFloat;
26 use namespace::clean;
27
28 with 'JSON::Schema::Modern::Vocabulary';
29
30 sub vocabulary ($class) {
31 'https://json-schema.org/draft/2019-09/vocab/validation' => 'draft2019-09',
32 'https://json-schema.org/draft/2020-12/vocab/validation' => 'draft2020-12';
33 }
34
35 sub evaluation_order ($class) { 1 }
36
37 sub keywords ($class, $spec_version) {
38 return (
39 qw(type enum),
40 $spec_version ne 'draft4' ? 'const' : (),
41 qw(multipleOf maximum exclusiveMaximum minimum exclusiveMinimum
42 maxLength minLength pattern maxItems minItems uniqueItems),
43 $spec_version !~ /^draft[467]\z/ ? qw(maxContains minContains) : (),
44 qw(maxProperties minProperties required),
45 $spec_version !~ /^draft[467]\z/ ? 'dependentRequired' : (),
46 );
47 }
48
49 sub _traverse_keyword_type ($class, $schema, $state) {
50 if (ref $schema->{type} eq 'ARRAY') {
51 # Note: this is not actually in the spec, but the restriction exists in the metaschema
52 return E($state, 'type array is empty') if not $schema->{type}->@*;
53
54 foreach my $type ($schema->{type}->@*) {
55 return E($state, 'unrecognized type "%s"', $type//'<null>')
56 if not any { ($type//'') eq $_ } qw(null boolean object array string number integer);
57 }
58 return E($state, '"type" values are not unique') if not is_elements_unique($schema->{type});
59 }
60 else {
61 return if not assert_keyword_type($state, $schema, 'string');
62 return E($state, 'unrecognized type "%s"', $schema->{type}//'<null>')
63 if not any { ($schema->{type}//'') eq $_ } qw(null boolean object array string number integer);
64 }
65 return 1;
66 }
67
68 sub _eval_keyword_type ($class, $data, $schema, $state) {
69 my $type = get_type($data, $state->{specification_version} eq 'draft4' ? { legacy_ints => 1 } : ());
70 my @want = ref $schema->{type} eq 'ARRAY' ? $schema->{type}->@* : $schema->{type};
71
72 return 1 if any {
73 $type eq $_ or ($_ eq 'number' and $type eq 'integer')
74 or ($type eq 'string' and $state->{stringy_numbers} and looks_like_number($data)
75 and ($_ eq 'number' or ($_ eq 'integer' and $data == int($data))))
76 or ($_ eq 'boolean' and $state->{scalarref_booleans} and $type eq 'reference to SCALAR')
77 } @want;
78
79 return E($state, 'got %s, not %s%s', $type, (@want > 1 ? 'one of ' : ''), join(', ', @want));
80 }
81
82 sub _traverse_keyword_enum ($class, $schema, $state) {
83 return assert_keyword_type($state, $schema, 'array');
84 }
85
86 sub _eval_keyword_enum ($class, $data, $schema, $state) {
87 my @s; my $idx = 0;
88 my %s = $state->%{qw(scalarref_booleans stringy_numbers)};
89 return 1 if any { is_equal($data, $_, $s[$idx++] = {%s}) } $schema->{enum}->@*;
90 return E($state, 'value does not match ('
91 .(join('; ', map "from enum $_".(length $s[$_]->{path} ? " at '$s[$_]->{path}'" : '').": $s[$_]->{error}", 0..$#s).')'));
92 }
93
94 sub _traverse_keyword_const ($class, $schema, $state) { 1 }
95
96 sub _eval_keyword_const ($class, $data, $schema, $state) {
97 my %s = $state->%{qw(scalarref_booleans stringy_numbers)};
98 return 1 if is_equal($data, $schema->{const}, \%s);
99 return E($state, 'value does not match ('.($s{path} ? "at '$s{path}': " : '').$s{error}.')');
100 }
101
102 sub _traverse_keyword_multipleOf ($class, $schema, $state) {
103 return if not assert_keyword_type($state, $schema, 'number');
104 return E($state, 'multipleOf value is not a positive number') if $schema->{multipleOf} <= 0;
105 return 1;
106 }
107
108 sub _eval_keyword_multipleOf ($class, $data, $schema, $state) {
109 return 1 if not is_type('number', $data)
110 and not ($state->{stringy_numbers} and is_type('string', $data) and looks_like_number($data)
111 and do { $data = 0+$data; 1 });
112
113 my $remainder;
114
115 if (get_type($data) eq 'integer' and get_type($schema->{multipleOf}) eq 'integer') {
116 $remainder = $data % $schema->{multipleOf};
117 }
118 else {
119 # if either value is a float, use the bignum library for the calculation for an accurate remainder
120 my $dividend = is_bignum($data) ? $data->copy : Math::BigFloat->new($data);
121 my $divisor = is_bignum($schema->{multipleOf}) ? $schema->{multipleOf} : Math::BigFloat->new($schema->{multipleOf});
122 $remainder = $dividend->bmod($divisor);
123 }
124
125 return 1 if $remainder == 0;
126 return E($state, 'value is not a multiple of %s', sprintf_num($schema->{multipleOf}));
127 }
128
129 *_traverse_keyword_maximum = \&_assert_number;
130
131 sub _eval_keyword_maximum ($class, $data, $schema, $state) {
132 return 1 if not is_type('number', $data)
133 and not ($state->{stringy_numbers} and is_type('string', $data) and looks_like_number($data));
134
135 return 1 if 0+$data < $schema->{maximum};
136 if ($state->{specification_version} eq 'draft4' and $schema->{exclusiveMaximum}) {
137 return E($state, 'value is greater than or equal to %s', sprintf_num($schema->{maximum}));
138 }
139 else {
140 return 1 if 0+$data == $schema->{maximum};
141 return E($state, 'value is greater than %s', sprintf_num($schema->{maximum}));
142 }
143 }
144
145 sub _traverse_keyword_exclusiveMaximum ($class, $schema, $state) {
146 return assert_keyword_type($state, $schema, 'number') if $state->{specification_version} ne 'draft4';
147
148 return if not assert_keyword_type($state, $schema, 'boolean');
149 return E($state, 'use of exclusiveMaximum requires the presence of maximum')
150 if not exists $schema->{maximum};
151 return 1;
152 }
153
154 sub _eval_keyword_exclusiveMaximum ($class, $data, $schema, $state) {
155 # we do the work in "maximum" for draft4 so we don't generate multiple errors
156 return 1 if $state->{specification_version} eq 'draft4';
157
158 return 1 if not is_type('number', $data)
159 and not ($state->{stringy_numbers} and is_type('string', $data) and looks_like_number($data));
160
161 return 1 if 0+$data < $schema->{exclusiveMaximum};
162 return E($state, 'value is greater than or equal to %s', sprintf_num($schema->{exclusiveMaximum}));
163 }
164
165 *_traverse_keyword_minimum = \&_assert_number;
166
167 sub _eval_keyword_minimum ($class, $data, $schema, $state) {
168 return 1 if not is_type('number', $data)
169 and not ($state->{stringy_numbers} and is_type('string', $data) and looks_like_number($data));
170
171 return 1 if 0+$data > $schema->{minimum};
172 if ($state->{specification_version} eq 'draft4' and $schema->{exclusiveMinimum}) {
173 return E($state, 'value is less than or equal to %s', sprintf_num($schema->{minimum}));
174 }
175 else {
176 return 1 if 0+$data == $schema->{minimum};
177 return E($state, 'value is less than %s', sprintf_num($schema->{minimum}));
178 }
179 }
180
181 sub _traverse_keyword_exclusiveMinimum ($class, $schema, $state) {
182 return assert_keyword_type($state, $schema, 'number') if $state->{specification_version} ne 'draft4';
183
184 return if not assert_keyword_type($state, $schema, 'boolean');
185 return E($state, 'use of exclusiveMinimum requires the presence of minimum')
186 if not exists $schema->{minimum};
187 return 1;
188 }
189
190 sub _eval_keyword_exclusiveMinimum ($class, $data, $schema, $state) {
191 # we do the work in "minimum" for draft4 so we don't generate multiple errors
192 return 1 if $state->{specification_version} eq 'draft4';
193
194 return 1 if not is_type('number', $data)
195 and not ($state->{stringy_numbers} and is_type('string', $data) and looks_like_number($data));
196
197 return 1 if 0+$data > $schema->{exclusiveMinimum};
198 return E($state, 'value is less than or equal to %s', sprintf_num($schema->{exclusiveMinimum}));
199 }
200
201 *_traverse_keyword_maxLength = \&_assert_non_negative_integer;
202
203 sub _eval_keyword_maxLength ($class, $data, $schema, $state) {
204 return 1 if not is_type('string', $data);
205 return 1 if length($data) <= $schema->{maxLength};
206 return E($state, 'length is greater than %d', $schema->{maxLength});
207 }
208
209 *_traverse_keyword_minLength = \&_assert_non_negative_integer;
210
211 sub _eval_keyword_minLength ($class, $data, $schema, $state) {
212 return 1 if not is_type('string', $data);
213 return 1 if length($data) >= $schema->{minLength};
214 return E($state, 'length is less than %d', $schema->{minLength});
215 }
216
217 sub _traverse_keyword_pattern ($class, $schema, $state) {
218 return if not assert_keyword_type($state, $schema, 'string')
219 or not assert_pattern($state, $schema->{pattern});
220 return 1;
221 }
222
223 sub _eval_keyword_pattern ($class, $data, $schema, $state) {
224 return 1 if not is_type('string', $data);
225
226 return 1 if $data =~ m/(?:$schema->{pattern})/;
227 return E($state, 'pattern does not match');
228 }
229
230 *_traverse_keyword_maxItems = \&_assert_non_negative_integer;
231
232 sub _eval_keyword_maxItems ($class, $data, $schema, $state) {
233 return 1 if not is_type('array', $data);
234 return 1 if @$data <= $schema->{maxItems};
235 return E($state, 'array has more than %d item%s', $schema->{maxItems}, $schema->{maxItems} > 1 ? 's' : '');
236 }
237
238 *_traverse_keyword_minItems = \&_assert_non_negative_integer;
239
240 sub _eval_keyword_minItems ($class, $data, $schema, $state) {
241 return 1 if not is_type('array', $data);
242 return 1 if @$data >= $schema->{minItems};
243 return E($state, 'array has fewer than %d item%s', $schema->{minItems}, $schema->{minItems} > 1 ? 's' : '');
244 }
245
246 sub _traverse_keyword_uniqueItems ($class, $schema, $state) {
247 return assert_keyword_type($state, $schema, 'boolean');
248 }
249
250 sub _eval_keyword_uniqueItems ($class, $data, $schema, $state) {
251 return 1 if not is_type('array', $data);
252 return 1 if not $schema->{uniqueItems};
253 return 1 if is_elements_unique($data, my $s = +{ $state->%{qw(scalarref_booleans stringy_numbers)}, equal_indices => [] });
254 return E($state, 'items at indices %d and %d are not unique', $s->{equal_indices}->@*);
255 }
256
257 # The evaluation implementations of maxContains and minContains are in the Applicator vocabulary,
258 # as 'contains' needs to run first
259 *_traverse_keyword_maxContains = \&_assert_non_negative_integer;
260
261 *_traverse_keyword_minContains = \&_assert_non_negative_integer;
262
263 *_traverse_keyword_maxProperties = \&_assert_non_negative_integer;
264
265 sub _eval_keyword_maxProperties ($class, $data, $schema, $state) {
266 return 1 if not is_type('object', $data);
267 return 1 if keys %$data <= $schema->{maxProperties};
268 return E($state, 'object has more than %d propert%s', $schema->{maxProperties},
269 $schema->{maxProperties} > 1 ? 'ies' : 'y');
270 }
271
272 *_traverse_keyword_minProperties = \&_assert_non_negative_integer;
273
274 sub _eval_keyword_minProperties ($class, $data, $schema, $state) {
275 return 1 if not is_type('object', $data);
276 return 1 if keys %$data >= $schema->{minProperties};
277 return E($state, 'object has fewer than %d propert%s', $schema->{minProperties},
278 $schema->{minProperties} > 1 ? 'ies' : 'y');
279 }
280
281 sub _traverse_keyword_required ($class, $schema, $state) {
282 return if not assert_keyword_type($state, $schema, 'array');
283 return E($state, '"required" array is empty') if $state->{specification_version} eq 'draft4' and not $schema->{required}->@*;
284
285 if (my @non_string = grep !is_type('string', $schema->{required}->[$_]), 0 .. $schema->{required}->$#*) {
286 ()= E({ %$state, _keyword_path_suffix => $_ }, '"required" element is not a string')
287 foreach @non_string;
288 return;
289 }
290
291 return E($state, '"required" values are not unique') if not is_elements_unique($schema->{required});
292 return 1;
293 }
294
295 sub _eval_keyword_required ($class, $data, $schema, $state) {
296 return 1 if not is_type('object', $data);
297
298 my @missing = grep !exists $data->{$_}, $schema->{required}->@*;
299 return 1 if not @missing;
300 return E($state, 'object is missing propert%s: %s', @missing > 1 ? 'ies' : 'y', join(', ', @missing));
301 }
302
303 sub _traverse_keyword_dependentRequired ($class, $schema, $state) {
304 return if not assert_keyword_type($state, $schema, 'object');
305
306 my $valid = 1;
307 foreach my $property (sort keys $schema->{dependentRequired}->%*) {
308 $valid = E({ %$state, _keyword_path_suffix => $property }, 'value is not an array'), next
309 if not is_type('array', $schema->{dependentRequired}{$property});
310
311 foreach my $index (0..$schema->{dependentRequired}{$property}->$#*) {
312 $valid = E({ %$state, _keyword_path_suffix => [ $property, $index ] }, 'element is not a string')
313 if not is_type('string', $schema->{dependentRequired}{$property}[$index]);
314 }
315
316 $valid = E({ %$state, _keyword_path_suffix => $property }, 'elements are not unique')
317 if not is_elements_unique($schema->{dependentRequired}{$property});
318 }
319 return $valid;
320 }
321
322 sub _eval_keyword_dependentRequired ($class, $data, $schema, $state) {
323 return 1 if not is_type('object', $data);
324
325 my $valid = 1;
326 foreach my $property (sort keys $schema->{dependentRequired}->%*) {
327 next if not exists $data->{$property};
328
329 if (my @missing = grep !exists($data->{$_}), $schema->{dependentRequired}{$property}->@*) {
330 $valid = E({ %$state, _keyword_path_suffix => $property },
331 'object is missing propert%s: %s', @missing > 1 ? 'ies' : 'y', join(', ', @missing));
332 }
333 }
334
335 return 1 if $valid;
336 return E($state, 'not all dependencies are satisfied');
337 }
338
339 sub _assert_number ($class, $schema, $state) {
340 return assert_keyword_type($state, $schema, 'number');
341 }
342
343 sub _assert_non_negative_integer ($class, $schema, $state) {
344 return if not assert_keyword_type($state, $schema, 'integer');
345 return E($state, '%s value is not a non-negative integer', $state->{keyword})
346 if $schema->{$state->{keyword}} < 0;
347 return 1;
348 }
349
350 1;
351
352 __END__
353
354 =pod
355
356 =encoding UTF-8
357
358 =head1 NAME
359
360 JSON::Schema::Modern::Vocabulary::Validation - Implementation of the JSON Schema Validation vocabulary
361
362 =head1 VERSION
363
364 version 0.650
365
366 I use a linearly-increasing version numbering scheme. No meaning should be
367 presumed or inferred from the version being less than 1.0.
368
369 =head1 DESCRIPTION
370
371 =for Pod::Coverage vocabulary evaluation_order keywords
372
373 =for stopwords metaschema
374
375 Implementation of the JSON Schema Draft 2020-12 "Validation" vocabulary, indicated in metaschemas
376 with the URI C<https://json-schema.org/draft/2020-12/vocab/validation> and formally specified in
377 L<https://json-schema.org/draft/2020-12/json-schema-validation.html#section-6>.
378
379 Support is also provided for
380
381 =over 4
382
383 =item *
384
385 the equivalent Draft 2019-09 keywords, indicated in metaschemas with the URI C<https://json-schema.org/draft/2019-09/vocab/validation> and formally specified in L<https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-02#section-6>.
386
387 =item *
388
389 the equivalent Draft 7 keywords that correspond to this vocabulary and are formally specified in L<https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6>.
390
391 =item *
392
393 the equivalent Draft 6 keywords that correspond to this vocabulary and are formally specified in L<https://json-schema.org/draft-06/draft-wright-json-schema-validation-01#rfc.section.6>.
394
395 =item *
396
397 the equivalent Draft 4 keywords that correspond to this vocabulary and are formally specified in L<https://json-schema.org/draft-04/draft-fge-json-schema-validation-00#rfc.section.5>.
398
399 =back
400
401 =head1 GIVING THANKS
402
403 =for stopwords MetaCPAN GitHub
404
405 If you found this module to be useful, please show your appreciation by
406 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
407 and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.
408
409 =head1 SUPPORT
410
411 Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.
412
413 I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.
414
415 =for stopwords OpenAPI
416
417 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
418 server|https://open-api.slack.com>, which are also great resources for finding help.
419
420 =head1 AUTHOR
421
422 Karen Etheridge <[email protected]>
423
424 =head1 COPYRIGHT AND LICENCE
425
426 This software is copyright (c) 2020 by Karen Etheridge.
427
428 This is free software; you can redistribute it and/or modify it under
429 the same terms as the Perl 5 programming language system itself.
430
431 Some schema files have their own licence, in share/LICENSE.
432
433 =cut