| 1 |
use strict; |
| 2 |
use warnings; |
| 3 |
package SchemaParser; |
| 4 |
|
| 5 |
use 5.020; |
| 6 |
use stable 0.031 'postderef'; |
| 7 |
use experimental 'signatures'; |
| 8 |
use feature 'state'; |
| 9 |
use builtin::compat 'blessed'; |
| 10 |
|
| 11 |
sub new { |
| 12 |
return bless {}, __PACKAGE__; |
| 13 |
} |
| 14 |
|
| 15 |
# this is a very simple schema validator. |
| 16 |
# It only understands boolean schemas, or schemas that say {"type":"boolean"}. |
| 17 |
# Unrecognized keywords will be treated as the empty schema (i.e. a pass). |
| 18 |
sub validate_data ($self, $data, $schema) { |
| 19 |
return $schema if is_bool($schema); |
| 20 |
die 'unrecognized schema type '.ref $schema if ref $schema ne 'HASH'; |
| 21 |
|
| 22 |
return 1 if not exists $schema->{type} or ref $schema->{type} eq 'HASH'; |
| 23 |
|
| 24 |
return is_bool($data) ? 1 : 0 if $schema->{type} eq 'boolean'; |
| 25 |
return 1; |
| 26 |
} |
| 27 |
|
| 28 |
sub validate_json_string ($self, $data_string, $schema) { |
| 29 |
state $decoder = (Mojo::JSON::JSON_XS ? 'Cpanel::JSON::XS' : 'JSON::PP')->new->utf8(1)->allow_nonref(1); |
| 30 |
return $self->validate_data($decoder->decode($data_string), $schema); |
| 31 |
} |
| 32 |
|
| 33 |
# lifted from JSON::Schema::Modern::Utilities, which lifted it from JSON::MaybeXS |
| 34 |
# note: unlike builtin::compat::is_bool on older perls, we do not accept |
| 35 |
# dualvar(0,"") or dualvar(1,"1") because JSON::PP and Cpanel::JSON::XS |
| 36 |
# do not encode these as booleans. |
| 37 |
use constant HAVE_BUILTIN => "$]" >= 5.035010; |
| 38 |
use if HAVE_BUILTIN, experimental => 'builtin'; |
| 39 |
sub is_bool ($value) { |
| 40 |
HAVE_BUILTIN and builtin::is_bool($value) |
| 41 |
or |
| 42 |
!!blessed($value) |
| 43 |
and ($value->isa('JSON::PP::Boolean') |
| 44 |
or $value->isa('Cpanel::JSON::XS::Boolean') |
| 45 |
or $value->isa('JSON::XS::Boolean')); |
| 46 |
} |
| 47 |
|
| 48 |
1; |