File: SchemaParser.pm

package info (click to toggle)
libtest-json-schema-acceptance-perl 1.003%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 652 kB
  • sloc: perl: 521; makefile: 2
file content (34 lines) | stat: -rw-r--r-- 890 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use strict;
use warnings;
package SchemaParser;

use feature 'state';
use JSON::MaybeXS 1.002004 'is_bool';

sub new {
  return bless {}, __PACKAGE__;
}

# this is a very simple schema validator.
# It only understands boolean schemas, or schemas that say {"type":"boolean"}.
# Unrecognized keywords will be treated as the empty schema (i.e. a pass).
sub validate_data {
  my ($self, $data, $schema) = @_;

  return $schema if is_bool($schema);
  die 'unrecognized schema type '.ref $schema if ref $schema ne 'HASH';

  return 1 if not exists $schema->{type} or ref $schema->{type} eq 'HASH';

  return is_bool($data) ? 1 : 0 if $schema->{type} eq 'boolean';
  return 1;
}

sub validate_json_string {
  my ($self, $data_string, $schema) = @_;

  state $decoder = JSON::MaybeXS->new(utf8 => 1, allow_nonref => 1);
  return $self->validate_data($decoder->decode($data_string), $schema);
}

1;