Debian Codegraph @

lib/Kwalify.pm

raw
1 # -*- mode: cperl -*-
2
3 #
4 # Author: Slaven Rezic
5 #
6 # Copyright (C) 2006,2007,2008,2009,2010,2015,2020,2024 Slaven Rezic. All rights reserved.
7 # This package is free software; you can redistribute it and/or
8 # modify it under the same terms as Perl itself.
9 #
10 # Mail: [email protected]
11 # WWW: https://github.com/eserte/p5-kwalify/
12 #
13
14 package Kwalify;
15
16 use strict;
17 use warnings;
18
19 use base qw(Exporter);
20 use vars qw(@EXPORT_OK $VERSION);
21 @EXPORT_OK = qw(validate);
22
23 $VERSION = '1.24';
24
25 sub validate ($$) {
26 my($schema, $data) = @_;
27 my $self = Kwalify::Validator->new;
28 $self->validate($schema, $data, "/");
29 if (@{$self->{errors}}) {
30 die join("\n", map { " - $_" } @{$self->{errors}}) . "\n";
31 } else {
32 1;
33 }
34 }
35
36 package Kwalify::Validator;
37
38 use overload ();
39
40 sub new {
41 my($class) = @_;
42 bless { errors => [] }, $class;
43 }
44
45 sub validate {
46 my($self, $schema, $data, $path, $args) = @_;
47 $self->{done} = {};
48 $self->_validate($schema, $data, $path, $args);
49 }
50
51 sub _validate {
52 my($self, $schema, $data, $path, $args) = @_;
53 $self->{path} = $path;
54
55 if (!UNIVERSAL::isa($schema, "HASH")) {
56 $self->_die("Schema structure must be a hash reference");
57 }
58
59 my $type = $schema->{type};
60 if (!defined $type) {
61 $type = 'str'; # default type;
62 }
63 my $type_check_method = "validate_" . $type;
64 if (!$self->can($type_check_method)) {
65 $self->_die("Invalid or unimplemented type '$type'");
66 }
67
68 $self->$type_check_method($schema, $data, $path, $args);
69 }
70
71 sub _additional_rules {
72 my($self, $schema, $data, $path) = @_;
73 no warnings 'uninitialized'; # legal undef values may happen everywhere
74 for my $schema_key (keys %$schema) {
75 if (defined $schema->{$schema_key}) {
76 if ($schema_key eq 'pattern') {
77 (my $pattern = $schema->{pattern}) =~ s{^/(.*)/$}{$1};
78 if ($data !~ qr{$pattern}) {
79 $self->_error("Non-valid data '$data' does not match /$pattern/");
80 }
81 } elsif ($schema_key eq 'length') {
82 if (!UNIVERSAL::isa($schema->{'length'}, "HASH")) {
83 $self->_die("'length' must be a hash with keys max and/or min");
84 }
85 my $length = length($data);
86 for my $sub_schema_key (keys %{ $schema->{'length'} }) {
87 if ($sub_schema_key eq 'min') {
88 my $min = $schema->{'length'}->{min};
89 if ($length < $min) {
90 $self->_error("'$data' is too short (length $length < min $min)");
91 }
92 } elsif ($sub_schema_key eq 'min-ex') {
93 my $min = $schema->{'length'}->{'min-ex'};
94 if ($length <= $min) {
95 $self->_error("'$data' is too short (length $length <= min $min)");
96 }
97 } elsif ($sub_schema_key eq 'max') {
98 my $max = $schema->{'length'}->{max};
99 if ($length > $max) {
100 $self->_error("'$data' is too long (length $length > max $max)");
101 }
102 } elsif ($sub_schema_key eq 'max-ex') {
103 my $max = $schema->{'length'}->{'max-ex'};
104 if ($length >= $max) {
105 $self->_error("'$data' is too long (length $length >= max $max)");
106 }
107 } else {
108 $self->_die("Unexpected key '$sub_schema_key' in length specification, expected min, max, min-ex and/or max-ex");
109 }
110 }
111 } elsif ($schema_key eq 'enum') {
112 if (!UNIVERSAL::isa($schema->{enum}, 'ARRAY')) {
113 $self->_die("'enum' must be an array");
114 }
115 my %valid = map { ($_,1) } @{ $schema->{enum} };
116 if (!exists $valid{$data}) {
117 $self->_error("'$data': invalid " . _base_path($path) . " value");
118 }
119 } elsif ($schema_key eq 'range') {
120 if (!UNIVERSAL::isa($schema->{range}, "HASH")) {
121 $self->_die("'range' must be a hash with keys max and/or min");
122 }
123 my($lt, $le, $gt, $ge);
124 ## yes? no?
125 # if (eval { require Scalar::Util; defined &Scalar::Util::looks_like_number }) {
126 # if (Scalar::Util::looks_like_number($data)) {
127 # $lt = sub { $_[0] < $_[1] };
128 # $gt = sub { $_[0] > $_[1] };
129 # } else {
130 # $lt = sub { $_[0] lt $_[1] };
131 # $gt = sub { $_[0] gt $_[1] };
132 # }
133 # } else {
134 # warn "Cannot determine whether $data is a number, assume so..."; # XXX show only once
135 no warnings 'numeric';
136 $lt = sub { $_[0] < $_[1] };
137 $gt = sub { $_[0] > $_[1] };
138 $le = sub { $_[0] <= $_[1] };
139 $ge = sub { $_[0] >= $_[1] };
140 # }
141
142 for my $sub_schema_key (keys %{ $schema->{range} }) {
143 if ($sub_schema_key eq 'min') {
144 my $min = $schema->{range}->{min};
145 if ($lt->($data, $min)) {
146 $self->_error("'$data' is too small (< min $min)");
147 }
148 } elsif ($sub_schema_key eq 'min-ex') {
149 my $min = $schema->{range}->{'min-ex'};
150 if ($le->($data, $min)) {
151 $self->_error("'$data' is too small (<= min $min)");
152 }
153 } elsif ($sub_schema_key eq 'max') {
154 my $max = $schema->{range}->{max};
155 if ($gt->($data, $max)) {
156 $self->_error("'$data' is too large (> max $max)");
157 }
158 } elsif ($sub_schema_key eq 'max-ex') {
159 my $max = $schema->{range}->{'max-ex'};
160 if ($ge->($data, $max)) {
161 $self->_error("'$data' is too large (>= max $max)");
162 }
163 } else {
164 $self->_die("Unexpected key '$sub_schema_key' in range specification, expected min, max, min-ex and/or max-ex");
165 }
166 }
167 } elsif ($schema_key eq 'assert') {
168 $self->_die("'assert' is not yet implemented");
169 } elsif ($schema_key !~ m{^(type|required|unique|name|classname|class|desc)$}) {
170 $self->_die("Unexpected key '$schema_key' in type specification");
171 }
172 }
173 }
174 }
175
176 sub validate_text {
177 my($self, $schema, $data, $path) = @_;
178 if (!defined $data || ref $data) {
179 return $self->_error("Non-valid data '" . (defined $data ? $data : 'undef') . "', expected text");
180 }
181 $self->_additional_rules($schema, $data, $path);
182 }
183
184 sub validate_str {
185 my($self, $schema, $data, $path) = @_;
186 if (!defined $data || ref $data || $data =~ m{^\d+(\.\d+)?$}) {
187 return $self->_error("Non-valid data '" . (defined $data ? $data : 'undef') . "', expected a str");
188 }
189 $self->_additional_rules($schema, $data, $path);
190 }
191
192 sub validate_int {
193 my($self, $schema, $data, $path) = @_;
194 if ($data !~ m{^[+-]?\d+$}) { # XXX what about scientific notation?
195 $self->_error("Non-valid data '" . $data . "', expected an int");
196 }
197 $self->_additional_rules($schema, $data, $path);
198 }
199
200 sub validate_float {
201 my($self, $schema, $data, $path) = @_;
202 if ($data !~ m{^[+-]?\d+\.\d+$}) { # XXX other values?
203 $self->_error("Non-valid data '" . $data . "', expected a float");
204 }
205 $self->_additional_rules($schema, $data, $path);
206 }
207
208 sub validate_number {
209 my($self, $schema, $data, $path) = @_;
210 if ($data !~ m{^[+-]?\d+(\.\d+)?$}) { # XXX combine int+float regexp!
211 $self->_error("Non-valid data '" . $data . "', expected a number");
212 }
213 $self->_additional_rules($schema, $data, $path);
214 }
215
216 sub validate_bool {
217 my($self, $schema, $data, $path) = @_;
218 if ($data !~ m{^(yes|true|1|no|false|0)$}) { # XXX correct?
219 $self->_error("Non-valid data '" . $data . "', expected a boolean");
220 }
221 $self->_additional_rules($schema, $data, $path);
222 }
223
224 # XXX is this correct?
225 sub validate_scalar {
226 shift->validate_text(@_);
227 }
228
229 sub validate_date {
230 my($self, $schema, $data, $path) = @_;
231 if ($data !~ m{^\d{4}-\d{2}-\d{2}$}) {
232 $self->_error("Non-valid data '" . $data . "', expected a date (YYYY-MM-DD)");
233 }
234 $self->_additional_rules($schema, $data, $path);
235 }
236
237 sub validate_time {
238 my($self, $schema, $data, $path) = @_;
239 if ($data !~ m{^\d{2}:\d{2}:\d{2}$}) {
240 $self->_error("Non-valid data '" . $data . "', expected a time (HH:MM:SS)");
241 }
242 $self->_additional_rules($schema, $data, $path);
243 }
244
245 sub validate_timestamp {
246 my($self) = @_;
247 $self->_error("timestamp validation NYI"); # XXX
248 }
249
250 sub validate_any {
251 my($self, $schema, $data, $path) = @_;
252 $self->_additional_rules($schema, $data, $path);
253 }
254
255 sub validate_seq {
256 my($self, $schema, $data, $path) = @_;
257 if (!exists $schema->{sequence}) {
258 $self->_die("'sequence' missing with 'seq' type");
259 }
260 my $sequence = $schema->{sequence};
261 if (!UNIVERSAL::isa($sequence, 'ARRAY')) {
262 $self->_die("Expected array in 'sequence'");
263 }
264 if (@$sequence != 1) {
265 $self->_die("Expect exactly one element in sequence");
266 }
267 if (!UNIVERSAL::isa($data, 'ARRAY')) {
268 $self->_error("Non-valid data " . $data . ", expected sequence");
269 return;
270 }
271
272 return if ($self->{done}{overload::StrVal($data)}{overload::StrVal($schema)});
273 $self->{done}{overload::StrVal($data)}{overload::StrVal($schema)} = 1;
274
275 my $subschema = $sequence->[0];
276 my $unique = _get_boolean($subschema->{unique});
277 my %unique_val;
278 my %unique_mapping_val;
279 my $index = 0;
280 for my $elem (@$data) {
281 my $subpath = _append_path($path, $index);
282 $self->_validate($subschema, $elem, $subpath, { unique_mapping_val => \%unique_mapping_val});
283 if ($unique) {
284 if (exists $unique_val{$elem}) {
285 $self->_error("'$elem' is already used at '$unique_val{$elem}'");
286 } else {
287 $unique_val{$elem} = $subpath;
288 }
289 }
290 $index++;
291 }
292 }
293
294 sub validate_map {
295 my($self, $schema, $data, $path, $args) = @_;
296 my $unique_mapping_val;
297 if ($args && $args->{unique_mapping_val}) {
298 $unique_mapping_val = $args->{unique_mapping_val};
299 }
300 if (!exists $schema->{mapping}) {
301 $self->_die("'mapping' missing with 'map' type");
302 }
303 my $mapping = $schema->{mapping};
304 if (!UNIVERSAL::isa($mapping, 'HASH')) {
305 $self->_die("Expected hash in 'mapping'");
306 }
307 if (!defined $data) {
308 $self->_error("Undefined data, expected mapping");
309 return;
310 }
311 if (!UNIVERSAL::isa($data, 'HASH')) {
312 $self->_error("Non-valid data " . $data . ", expected mapping");
313 return;
314 }
315
316 return if ($self->{done}{overload::StrVal($data)}{overload::StrVal($schema)});
317 $self->{done}{overload::StrVal($data)}{overload::StrVal($schema)} = 1;
318
319 my %seen_key;
320 my $default_key_schema;
321
322 ## Originally this was an each-loop, but this could lead into
323 ## endless recursions, because mapping may be reused in Kwalify,
324 ## thus the each iterator was shared between recursion levels.
325 # while(my($key,$subschema) = each %$mapping) {
326 for my $key (keys %$mapping) {
327 my $subschema = $mapping->{$key};
328 if ($key eq '=') { # the "default" key
329 $default_key_schema = $subschema;
330 next;
331 }
332 my $subpath = _append_path($path, $key);
333 $self->{path} = $subpath;
334 if (!UNIVERSAL::isa($subschema, 'HASH')) {
335 $self->_die("Expected subschema (a hash)");
336 }
337 my $required = _get_boolean($subschema->{required});
338 if (!defined $data->{$key}) {
339 if ($required) {
340 $self->{path} = $path;
341 $self->_error("Expected required key '$key'");
342 next;
343 } else {
344 $seen_key{$key}++;
345 next;
346 }
347 }
348 my $unique = _get_boolean($subschema->{unique});
349 if ($unique) {
350 if (defined $unique_mapping_val->{$data->{$key}}->{val}
351 && $unique_mapping_val->{$data->{$key}}->{val} eq $data->{$key}) {
352 $self->_error("'$data->{$key}' is already used at '$unique_mapping_val->{$data->{$key}}->{path}'");
353 } else {
354 $unique_mapping_val->{$data->{$key}} = { val => $data->{$key},
355 path => $subpath,
356 };
357 }
358 }
359
360 $self->_validate($subschema, $data->{$key}, $subpath);
361 $seen_key{$key}++;
362 }
363
364 # while(my($key,$val) = each %$data) {
365 for my $key (keys %$data) {
366 my $val = $data->{$key};
367 my $subpath = _append_path($path, $key);
368 $self->{path} = $subpath;
369 if (!$seen_key{$key}) {
370 if ($default_key_schema) {
371 $self->_validate($default_key_schema, $val, $subpath);
372 } else {
373 $self->_error("Unexpected key '$key'");
374 }
375 }
376 }
377 }
378
379 sub _die {
380 my($self, $msg) = @_;
381 $msg = "[$self->{path}] $msg";
382 die $msg."\n";
383 }
384
385 sub _error {
386 my($self, $msg) = @_;
387 $msg = "[$self->{path}] $msg";
388 push @{$self->{errors}}, $msg;
389 0;
390 }
391
392 # Functions:
393 sub _append_path {
394 my($root, $leaf) = @_;
395 $root . ($root !~ m{/$} ? "/" : "") . $leaf;
396 }
397
398 sub _base_path {
399 my($path) = @_;
400 my($base) = $path =~ m{([^/]+)$};
401 $base;
402 }
403
404 sub _get_boolean {
405 my($val) = @_;
406 defined $val && $val =~ m{^(yes|true|1)$}; # XXX check for all boolean trues
407 }
408
409 1;
410 __END__
411
412 =head1 NAME
413
414 Kwalify - Kwalify schema for data structures
415
416 =head1 SYNOPSIS
417
418 use Kwalify qw(validate);
419 validate($schema, $data);
420
421 Typically used together with YAML or JSON:
422
423 use YAML;
424 validate(YAML::LoadFile($schema_file), YAML::LoadFile($data_file));
425
426 use JSON;
427 validate(decode_json($schema_data), decode_json($data));
428
429 =head1 DESCRIPTION
430
431 Kwalify is a Perl implementation for validating data structures
432 against the Kwalify schema. For a schema definition, see
433 L<https://web.archive.org/web/20190718083758/http://www.kuwata-lab.com/kwalify/ruby/users-guide.01.html>, but see
434 also below L</SCHEMA DEFINITION>.
435
436 =head2 validate($schema_data, $data)
437
438 Validate I<$data> according to Kwalify schema specified in
439 I<$schema_data>. Dies if the validation fails.
440
441 B<validate> may be exported.
442
443 =head1 SCHEMA DEFINITION
444
445 The original schema definition document is not very specific about
446 types and behaviour. Here's how B<Kwalify.pm> implements things:
447
448 =over
449
450 =item name
451
452 The name of the schema.
453
454 =item desc
455
456 The description for the rule.
457 It is not used for validation.
458
459 =item pattern
460
461 A pattern matching the valid values.
462
463 Perl regular expressions are used for patterns. This may or may not be
464 compatible with other Kwalify validators, so restrict to "simple"
465 regular expression constructs to be compatible with other validators.
466
467 =item enum
468
469 A list of the valid values.
470
471 =item range
472
473 A hash with the valid value ranges for types other than B<seq>, B<map>,
474 B<bool> and B<any>.
475
476 =over
477
478 =item max
479
480 The maximum inclusive.
481
482 =item min
483
484 The minimum inclusive.
485
486 =item max-ex
487
488 The maximum exclusive.
489
490 =item min-ex
491
492 The minimum exclusive.
493
494 =back
495
496 =item length
497
498 Like B<range> but for B<str> and B<text>.
499
500 =item required
501
502 A constraint to denote the value is required when B<true>.
503 The default is B<false>.
504
505 =item type
506
507 The default B<type> if omitted is B<str>.
508
509 =over
510
511 =item str
512
513 Any defined value which is B<not> a number. Most probably you will
514 want to use B<text> instead of B<str>.
515
516 =item int
517
518 A possibly signed integer. Note that scientific notation is not
519 supported, and it is also not clear whether it should be supported.
520
521 =item float
522
523 A possibly signed floating value with a mandatory decimal point. Note
524 that scientific notation is also not supported here.
525
526 =item number
527
528 A possibly signed floating value with an optional decimal point (so
529 either B<int> or B<float>).
530 Note that scientific notation is also not supported here.
531
532 =item text
533
534 Any defined value which is either a B<str> or a B<number>.
535
536 =item bool
537
538 The values B<yes>, B<true>, and B<1> for true values and the values
539 B<no>, B<false>, and B<0> for false values are allowed. The ruby
540 implementation possibly allows more values, but this is not
541 documented.
542
543 Note that this definition is problematic, because for example the
544 string B<no> is a true boolean value in Perl. So one should stick to
545 B<0> and B<1> as data values, and probably define an additional
546 B<pattern> or B<enum> to ensure this:
547
548 type: bool
549 enum: [0, 1]
550
551 =item date
552
553 A string matching C<< /^\d{4}-\d{2}-\d{2}$/ >> (i.e. YYYY-MM-DD). Note
554 that no date range checks are done (yet).
555
556 =item time
557
558 A string matching C<< /^\d{2}:\d{2}:\d{2}$/ >> (i.e. HH:MM:SS). Note
559 that no time range checks are done (yet).
560
561 =item timestamp
562
563 Not supported --- it is not clear what this is supposed to be.
564
565 =item seq
566
567 A sequence (list) of rules.
568
569 =item map
570
571 A mapping (hash) of rules.
572
573 The name "B<=>" can be used to apply rules to any key.
574
575 =item scalar
576
577 Currently the same as B<text>, but it's not clear if this is correct.
578 Originally defined as all but B<seq> and B<map>.
579
580 =item any
581
582 Any data type.
583
584 =back
585
586 =item unique
587
588 The value is unique for a B<seq> or a B<map>.
589
590 =item assert
591
592 Currently not supported by the Perl implementation.
593
594 =item classname
595
596 Previously defined what is now B<class>, see L<https://web.archive.org/web/20190718083758/http://www.kuwata-lab.com/kwalify/ruby/users-guide.01.html>.
597
598 =item class
599
600 Currently not used, as there's no genclass action.
601
602 =item default
603
604 Currently not used, as there's no genclass action.
605
606 =back
607
608 =head1 TECHNICAL NOTES
609
610 As B<Kwalify.pm> is a pure validator and de-coupled from a parser (in
611 fact, it does not need to deal with YAML at all, but just with pure
612 perl data structures), there's no connection to the original validated
613 document. This means that no line numbers are available to the
614 validator. In case of validation errors the validator is only able to
615 show a path-like expression to the data causing the error.
616
617 =head1 AUTHOR
618
619 Slaven ReziE<x0107>, E<lt>[email protected]<gt>
620
621 =head1 COPYRIGHT AND LICENSE
622
623 Copyright (C) 2006,2007,2008,2009,2010,2015 by Slaven ReziE<x0107>
624
625 This library is free software; you can redistribute it and/or modify
626 it under the same terms as Perl itself.
627
628 =head1 SEE ALSO
629
630 L<pkwalify>, L<kwalify(1)>.
631
632 Other non-XML schema languages: L<http://rx.codesimply.com/>
633
634 =cut