blib/lib/Cpanel/JSON/XS/Type.pm

filter: Statementstmt 91.9% 149 / 162 Branchbran 79.3% 92 / 116 Conditioncond 55.0% 11 / 20 MC/DCmcdc 50.0% 6 / 12 Subroutinesub 90.0% 18 / 20 Podpod 100% 7 / 7 totaltotal 83.9% 283 / 337 CC 74 SCAR 33.4
CC
74
Cov
85%
_check_type
54.9
json_type_anyof
14.0
_detect_scalar_type
6.5
CRAP 28.2
↑ Summary blib/lib/Cpanel/JSON/XS.pm »
1 package Cpanel::JSON::XS::Type;
2  
3 5 our $VERSION = '4.82';
4  
5 =pod
6  
7 =head1 NAME
8  
9 Cpanel::JSON::XS::Type - Type support for JSON encode
10  
11 =head1 SYNOPSIS
12  
13 use Cpanel::JSON::XS;
14 use Cpanel::JSON::XS::Type;
15  
16  
17 encode_json([10, "10", 10.25], [JSON_TYPE_INT, JSON_TYPE_INT, JSON_TYPE_STRING]);
18 # '[10,10,"10.25"]'
19  
20 encode_json([10, "10", 10.25], json_type_arrayof(JSON_TYPE_INT));
21 # '[10,10,10]'
22  
23 encode_json(1, JSON_TYPE_BOOL);
24 # 'true'
25  
26 my $perl_struct = { key1 => 1, key2 => "2", key3 => 1 };
27 my $type_spec = { key1 => JSON_TYPE_STRING, key2 => JSON_TYPE_INT, key3 => JSON_TYPE_BOOL };
28 my $json_string = encode_json($perl_struct, $type_spec);
29 # '{"key1":"1","key2":2,"key3":true}'
30  
31 my $perl_struct = { key1 => "value1", key2 => "value2", key3 => 0, key4 => 1, key5 => "string", key6 => "string2" };
32 my $type_spec = json_type_hashof(JSON_TYPE_STRING);
33 my $json_string = encode_json($perl_struct, $type_spec);
34 # '{"key1":"value1","key2":"value2","key3":"0","key4":"1","key5":"string","key6":"string2"}'
35  
36 my $perl_struct = { key1 => { key2 => [ 10, "10", 10.6 ] }, key3 => "10.5" };
37 my $type_spec = { key1 => json_type_anyof(JSON_TYPE_FLOAT, json_type_hashof(json_type_arrayof(JSON_TYPE_INT))), key3 => JSON_TYPE_FLOAT };
38 my $json_string = encode_json($perl_struct, $type_spec);
39 # '{"key1":{"key2":[10,10,10]},"key3":10.5}'
40  
41  
42 my $value = decode_json('false', 1, my $type);
43 # $value is 0 and $type is JSON_TYPE_BOOL
44  
45 my $value = decode_json('0', 1, my $type);
46 # $value is 0 and $type is JSON_TYPE_INT
47  
48 my $value = decode_json('"0"', 1, my $type);
49 # $value is 0 and $type is JSON_TYPE_STRING
50  
51 my $json_string = '{"key1":{"key2":[10,"10",10.6]},"key3":"10.5"}';
52 my $perl_struct = decode_json($json_string, 0, my $type_spec);
53 # $perl_struct is { key1 => { key2 => [ 10, 10, 10.6 ] }, key3 => 10.5 }
54 # $type_spec is { key1 => { key2 => [ JSON_TYPE_INT, JSON_TYPE_STRING, JSON_TYPE_FLOAT ] }, key3 => JSON_TYPE_STRING }
55  
56 =head1 DESCRIPTION
57  
58 This module provides stable JSON type support for the
59 L<Cpanel::JSON::XS|Cpanel::JSON::XS> encoder which doesn't depend on
60 any internal perl scalar flags or characteristics. Also it provides
61 real JSON types for L<Cpanel::JSON::XS|Cpanel::JSON::XS> decoder.
62  
63 In most cases perl structures passed to
64 L<encode_json|Cpanel::JSON::XS/encode_json> come from other functions
65 or from other modules and caller of Cpanel::JSON::XS module does not
66 have control of internals or they are subject of change. So it is not
67 easy to support enforcing types as described in the
68 L<simple scalars|Cpanel::JSON::XS/simple scalars> section.
69  
70 For services based on JSON contents it is sometimes needed to correctly
71 process and enforce JSON types.
72  
73 The function L<decode_json|Cpanel::JSON::XS/decode_json> takes optional
74 third scalar parameter and fills it with specification of json types.
75  
76 The function L<encode_json|Cpanel::JSON::XS/encode_json> takes a perl
77 structure as its input and optionally also a json type specification in
78 the second parameter.
79  
80 If the specification is not provided (or is undef) internal perl
81 scalar flags are used for the resulting JSON type. The internal flags
82 can be changed by perl itself, but also by external modules. Which
83 means that types in resulting JSON string aren't stable. Specially it
84 does not work reliable for dual vars and scalars which were used in
85 both numeric and string operations. See L<simple
86 scalars|Cpanel::JSON::XS/simple scalars>.
87  
88 To enforce that specification is always provided use C<require_types>.
89 In this case when C<encode> is called without second argument (or is
90 undef) then it croaks. It applies recursively for all sub-structures.
91  
92 =head2 JSON type specification for scalars:
93  
94 =over 4
95  
96 =item JSON_TYPE_BOOL
97  
98 It enforces JSON boolean in resulting JSON, i.e. either C<true> or
99 C<false>. For determining whether the scalar passed to the encoder
100 is true, standard perl boolean logic is used.
101  
102 =item JSON_TYPE_INT
103  
104 It enforces JSON number without fraction part in the resulting JSON.
105 Equivalent of perl function L<int|perlfunc/int> is used for conversion.
106  
107 =item JSON_TYPE_FLOAT
108  
109 It enforces JSON number with fraction part in the resulting JSON.
110 Equivalent of perl operation C<+0> is used for conversion.
111  
112 =item JSON_TYPE_STRING
113  
114 It enforces JSON string type in the resulting JSON.
115  
116 =item JSON_TYPE_NULL
117  
118 It represents JSON C<null> value. Makes sense only when passing
119 perl's C<undef> value.
120  
121 =back
122  
123 For each type, there also exists a type with the suffix C<_OR_NULL>
124 which encodes perl's C<undef> into JSON C<null>. Without type with
125 suffix C<_OR_NULL> perl's C<undef> is converted to specific type
126 according to above rules.
127  
128 =head2 JSON type specification for arrays:
129  
130 =over 4
131  
132 =item [...]
133  
134 The array must contain the same number of elements as in the perl
135 array passed for encoding. Each element of the array describes the
136 JSON type which is enforced for the corresponding element of the
137 perl array.
138  
139 =item json_type_arrayof
140  
141 This function takes a JSON type specification as its argument which
142 is enforced for every element of the passed perl array.
143  
144 =back
145  
146 =head2 JSON type specification for hashes:
147  
148 =over 4
149  
150 =item {...}
151  
152 Each hash value for corresponding key describes the JSON type
153 specification for values of passed perl hash structure. Keys in hash
154 which are not present in passed perl hash structure are simple
155 ignored and not used.
156  
157 =item json_type_hashof
158  
159 This function takes a JSON type specification as its argument which
160 is enforced for every value of passed perl hash structure.
161  
162 =back
163  
164 =head2 JSON type specification for alternatives:
165  
166 =over 4
167  
168 =item json_type_anyof
169  
170 This function takes a list of JSON type alternative specifications
171 (maximally one scalar, one array, and one hash) as its input and the
172 JSON encoder chooses one that matches.
173  
174 =item json_type_null_or_anyof
175  
176 Like L<C<json_type_anyof>|/json_type_anyof>, but scalar can be only
177 perl's C<undef>.
178  
179 =back
180  
181 =head2 Recursive specifications
182  
183 =over 4
184  
185 =item json_type_weaken
186  
187 This function can be used as an argument for L</json_type_arrayof>,
188 L</json_type_hashof> or L</json_type_anyof> functions to create weak
189 references suitable for complicated recursive structures. It depends
190 on L<the weaken function from Scalar::Util|Scalar::Util/weaken> module.
191 See following example:
192  
193 my $struct = {
194 type => JSON_TYPE_STRING,
195 array => json_type_arrayof(JSON_TYPE_INT),
196 };
197 $struct->{recursive} = json_type_anyof(
198 json_type_weaken($struct),
199 json_type_arrayof(JSON_TYPE_STRING),
200 );
201  
202 If you want to encode all perl scalars to JSON string types despite
203 how complicated is input perl structure you can define JSON type
204 specification for alternatives recursively. It could be defined as:
205  
206 my $type = json_type_anyof();
207 $type->[0] = JSON_TYPE_STRING_OR_NULL;
208 $type->[1] = json_type_arrayof(json_type_weaken($type));
209 $type->[2] = json_type_hashof(json_type_weaken($type));
210  
211 print encode_json([ 10, "10", { key => 10 } ], $type);
212 # ["10","10",{"key":"10"}]
213  
214 An alternative solution for encoding all scalars to JSON strings is to
215 use C<type_all_string> method of L<Cpanel::JSON::XS> itself:
216  
217 my $json = Cpanel::JSON::XS->new->type_all_string;
218 print $json->encode([ 10, "10", { key => 10 } ]);
219 # ["10","10",{"key":"10"}]
220  
221 =back
222  
223 =head2 Short scalar type names
224  
225 As sugar for the constants above, anywhere a scalar JSON type is
226 accepted (currently: L</check_type> and the encoder's type spec) a
227 plain string may be used instead:
228  
229 Str Int Float Bool Null Any
230  
231 C<Any> matches any scalar, including C<undef> (it is exactly
232 C<JSON_TYPE_SCALAR>, the "no constraint, use perl's own flags" type).
233 Suffix a name with C<?> for the C<_OR_NULL> variant: C<Str?>, C<Int?>,
234 C<Float?>, C<Bool?>. So a schema can be written the way the L<issue
235 that requested it|https://github.com/rurban/Cpanel-JSON-XS/issues/238>
236 suggested, as a plain hash of keys and types:
237  
238 my $schema = { name => 'Str', age => 'Int?', active => 'Bool' };
239  
240 =head2 Optional hash keys
241  
242 =over 4
243  
244 =item json_type_optional
245  
246 Wraps a type so that, when used as a hash schema value for
247 L</check_type>, the corresponding key is allowed to be entirely
248 absent from the data (as opposed to C<_OR_NULL>, which requires the
249 key to be present but allows its value to be C<null>).
250  
251 my $schema = { name => 'Str', nickname => json_type_optional('Str') };
252 check_type({ name => 'Joe' }, $schema); # ok, nickname is optional
253  
254 The encoder also understands C<json_type_optional>: when it
255 encounters one in a type spec it simply unwraps it and encodes the
256 wrapped type, since C<encode> only ever sees keys that are actually
257 present and has no use for "may be absent" (GH #242). This lets one
258 type spec, built once with C<json_type_optional> for the keys that
259 are sometimes missing, be handed to both C<encode> and
260 L</check_type>/L<C<decode_and_validate>|Cpanel::JSON::XS/decode_and_validate>.
261 Note that this only unwraps the C<json_type_optional> wrapper itself;
262 the encoder does not understand the short scalar type name sugar
263 (C<'Str'>, C<'Int'>, ...), so a spec shared with C<encode> must wrap an
264 actual C<JSON_TYPE_*> constant, e.g. C<json_type_optional(JSON_TYPE_STRING)>.
265  
266 my $type_spec = { name => JSON_TYPE_STRING, nickname => json_type_optional(JSON_TYPE_STRING) };
267 encode_json({ name => "Joe" }, $type_spec); # '{"name":"Joe"}', no croak
268  
269 =back
270  
271 =head2 Schema validation
272  
273 =over 4
274  
275 =item check_type
276  
277 my @errors = check_type($data, $schema);
278 my @errors = check_type($data, $schema, $found_type);
279  
280 Validates an already-decoded perl structure C<$data> against
281 C<$schema>, a type specification using the same building blocks as
282 the encoder's type spec above (C<JSON_TYPE_*> constants or the short
283 names, C<[...]>/C<json_type_arrayof>, C<{...}>/C<json_type_hashof>,
284 C<json_type_anyof>, plus C<json_type_optional> for hash keys).
285 Returns a list of human readable error strings (one per mismatch,
286 prefixed with a C<$>-rooted path such as C<$-E<gt>{users}-E<gt>[0]-E<gt>{id}>);
287 an empty list means C<$data> matches C<$schema>.
288  
289 Unlike the encoder's plain C<{...}> hash type spec (which silently
290 ignores hash keys not mentioned in the spec), a plain hashref schema
291 here is I<closed>: every key present in C<$data> must be declared in
292 C<$schema>, and every key declared in C<$schema> must be present in
293 C<$data> unless wrapped in C<json_type_optional>. Use
294 C<json_type_hashof> for an open, homogeneous-value hash, exactly like
295 the encoder.
296  
297 The optional third argument C<$found_type> is the type structure
298 L<decode|Cpanel::JSON::XS/decode> fills in via its own third
299 argument. When given, it is used as the ground truth for scalar
300 leaves instead of guessing from perl's internal scalar flags, which
301 removes the usual dual-var / stringified-number ambiguities. This is
302 exactly what
303 L<C<$json-E<gt>decode_and_validate>|Cpanel::JSON::XS/decode_and_validate>
304 does:
305  
306 my $json = Cpanel::JSON::XS->new;
307 my $schema = { id => JSON_TYPE_INT, name => 'Str', tags => json_type_arrayof('Str') };
308 my $data = $json->decode_and_validate($json_text, $schema); # croaks on mismatch
309  
310 =back
311  
312 =head1 AUTHOR
313  
314 Pali E<lt>pali@cpan.orgE<gt>
315  
316 =head1 COPYRIGHT & LICENSE
317  
318 Copyright (c) 2017, GoodData Corporation. All rights reserved.
319  
320 This module is available under the same licences as perl, the Artistic
321 license and the GPL.
322  
323 =cut
324  
325 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
326 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
327  
328 5 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=11.1
329 5 ▶ if (eval { require Scalar::Util }) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { require Scalar::Util } }) { } 5 0 5
330 5 Scalar::Util->import('weaken', 'looks_like_number');
331 } else {
332 0 ▶ *weaken = sub($) { die 'Scalar::Util is required for weaken' };
Subroutine __ANON__: not called CC=1 SCAR=6.9
333 0 ▶ *looks_like_number = sub($) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
334 0 ▶ defined($_[0]) && $_[0] =~ /^\s*-?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\s*\z/;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] and $_[0] =~ /^\s*-?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\s*\z/ 0 0 0
335 0 };
336 }
337 }
338  
339 # This exports needed XS constants to perl
340 5 ▶use Cpanel::JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
341  
342 5 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
343 5 our @ISA = qw(Exporter);
344 5 our @EXPORT = our @EXPORT_OK = qw(
345 json_type_arrayof
346 json_type_hashof
347 json_type_anyof
348 json_type_null_or_anyof
349 json_type_weaken
350 json_type_optional
351 check_type
352 JSON_TYPE_NULL
353 JSON_TYPE_BOOL
354 JSON_TYPE_INT
355 JSON_TYPE_FLOAT
356 JSON_TYPE_STRING
357 JSON_TYPE_BOOL_OR_NULL
358 JSON_TYPE_INT_OR_NULL
359 JSON_TYPE_FLOAT_OR_NULL
360 JSON_TYPE_STRING_OR_NULL
361 JSON_TYPE_ARRAYOF_CLASS
362 JSON_TYPE_HASHOF_CLASS
363 JSON_TYPE_ANYOF_CLASS
364 JSON_TYPE_OPTIONAL_CLASS
365 );
366  
367 5 ▶use constant JSON_TYPE_WEAKEN_CLASS => 'Cpanel::JSON::XS::Type::Weaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
368 5 ▶use constant JSON_TYPE_SCALAR => 0; # matches C JSON_TYPE_SCALAR: "no constraint" / Any
Subroutine BEGIN: called CC=1 SCAR=0.0
369  
370  
371 88 ▶sub json_type_anyof {
Subroutine json_type_anyof: called CC=14 SCAR=26.4
Pod documented
372 88 my ($scalar, $array, $hash);
373 88 my ($scalar_weaken, $array_weaken, $hash_weaken);
374 88 foreach (@_) {
375 160 my $type = $_;
376 160 my $ref = ref($_);
377 160 my $weaken;
378 160 ▶ if ($ref eq JSON_TYPE_WEAKEN_CLASS) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "Cpanel::JSON::XS::Type::Weaken") 1 159 160
379 1 $type = ${$type};
380 1 $ref = ref($type);
381 1 $weaken = 1;
382 }
383 160 ▶ if ($ref eq '') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq '') { } 79 81 160
elsif ($ref eq 'ARRAY' or $ref eq 'Cpanel::JSON::XS::Type::ArrayOf') { } 43 38 81
elsif ($ref eq 'HASH' or $ref eq 'Cpanel::JSON::XS::Type::HashOf') { } 37 1 38
384 79 ▶ die 'Only one scalar type can be specified in anyof' if defined $scalar;
Branch: 1 branch
BranchTrueFalseTotal
if defined $scalar 1 78 79
385 78 $scalar = $type;
386 78 $scalar_weaken = $weaken;
387 ▶ } elsif ($ref eq 'ARRAY' or $ref eq JSON_TYPE_ARRAYOF_CLASS) {
Condition100%3/3
$ref eq "ARRAY" or $ref eq "Cpanel::JSON::XS::Type::ArrayOf"
l!l&&r!l&&!r
321138
MC/DC100%2/2
$ref eq "ARRAY" or $ref eq "Cpanel::JSON::XS::Type::ArrayOf"
$ref eq "ARRAY" $ref eq "Cpanel::JSON::XS::Type::ArrayOf"
Truth table100%3/3
A or B
A= $ref eq "ARRAY"B= $ref eq "Cpanel::JSON::XS::Type::ArrayOf"
ABresult
1X1
011
000
388 43 ▶ die 'Only one array type can be specified in anyof' if defined $array;
Branch: 1 branch
BranchTrueFalseTotal
if defined $array 3 40 43
389 40 $array = $type;
390 40 $array_weaken = $weaken;
391 ▶ } elsif ($ref eq 'HASH' or $ref eq JSON_TYPE_HASHOF_CLASS) {
Condition100%3/3
$ref eq "HASH" or $ref eq "Cpanel::JSON::XS::Type::HashOf"
l!l&&r!l&&!r
3251
MC/DC100%2/2
$ref eq "HASH" or $ref eq "Cpanel::JSON::XS::Type::HashOf"
$ref eq "HASH" $ref eq "Cpanel::JSON::XS::Type::HashOf"
Truth table100%3/3
A or B
A= $ref eq "HASH"B= $ref eq "Cpanel::JSON::XS::Type::HashOf"
ABresult
1X1
011
000
392 37 ▶ die 'Only one hash type can be specified in anyof' if defined $hash;
Branch: 1 branch
BranchTrueFalseTotal
if defined $hash 3 34 37
393 34 $hash = $type;
394 34 $hash_weaken = $weaken;
395 } else {
396 1 die 'Only scalar, array or hash can be specified in anyof';
397 }
398 }
399 80 my $type = [$scalar, $array, $hash];
400 80 ▶ weaken $type->[0] if $scalar_weaken;
Branch: 1 branch
BranchTrueFalseTotal
if $scalar_weaken 0 80 80
401 80 ▶ weaken $type->[1] if $array_weaken;
Branch: 1 branch
BranchTrueFalseTotal
if $array_weaken 0 80 80
402 80 ▶ weaken $type->[2] if $hash_weaken;
Branch: 1 branch
BranchTrueFalseTotal
if $hash_weaken 1 79 80
403 80 return bless $type, JSON_TYPE_ANYOF_CLASS;
404 }
405  
406 4 ▶sub json_type_null_or_anyof {
Subroutine json_type_null_or_anyof: called CC=3 SCAR=11.0
Pod documented
407 4 foreach (@_) {
408 4 ▶ die 'Scalar cannot be specified in null_or_anyof' if ref($_) eq '';
Branch: 1 branch
BranchTrueFalseTotal
if ref $_ eq "" 1 3 4
409 }
410 3 return json_type_anyof(JSON_TYPE_CAN_BE_NULL, @_);
411 }
412  
413 23 ▶sub json_type_arrayof {
Subroutine json_type_arrayof: called CC=3 SCAR=11.0
Pod documented
414 23 ▶ die 'Exactly one type must be specified in arrayof' if scalar @_ != 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ != 1 1 22 23
415 22 my $type = $_[0];
416 22 ▶ if (ref($type) eq JSON_TYPE_WEAKEN_CLASS) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $type eq "Cpanel::JSON::XS::Type::Weaken") 1 21 22
417 1 $type = ${$type};
418 1 weaken $type;
419 }
420 22 return bless \$type, JSON_TYPE_ARRAYOF_CLASS;
421 }
422  
423 13 ▶sub json_type_hashof {
Subroutine json_type_hashof: called CC=3 SCAR=11.0
Pod documented
424 13 ▶ die 'Exactly one type must be specified in hashof' if scalar @_ != 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ != 1 1 12 13
425 12 my $type = $_[0];
426 12 ▶ if (ref($type) eq JSON_TYPE_WEAKEN_CLASS) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $type eq "Cpanel::JSON::XS::Type::Weaken") 1 11 12
427 1 $type = ${$type};
428 1 weaken $type;
429 }
430 12 return bless \$type, JSON_TYPE_HASHOF_CLASS;
431 }
432  
433 3 ▶sub json_type_weaken {
Subroutine json_type_weaken: called CC=3 SCAR=11.7
Pod documented
434 3 ▶ die 'Exactly one type must be specified in weaken' if scalar @_ != 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ != 1 0 3 3
435 3 ▶ die 'Scalar cannot be specfied in weaken' if ref($_[0]) eq '';
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] eq "" 0 3 3
436 3 return bless \(my $type = $_[0]), JSON_TYPE_WEAKEN_CLASS;
437 }
438  
439 8 ▶sub json_type_optional {
Subroutine json_type_optional: called CC=2 SCAR=7.2
Pod documented
440 8 ▶ die 'Exactly one type must be specified in optional' if scalar @_ != 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ != 1 0 8 8
441 8 return bless \(my $type = $_[0]), JSON_TYPE_OPTIONAL_CLASS;
442 }
443  
444 # ---------------------------------------------------------------------
445 # Schema validation (GH #238): validate an already-decoded perl
446 # structure against a type specification built from the same pieces
447 # as the encoder's type spec above, plus json_type_optional() and the
448 # short scalar type names documented in the POD.
449 # ---------------------------------------------------------------------
450  
451 5 my %SCALAR_TYPE_ALIAS = (
452 Any => JSON_TYPE_SCALAR,
453 Str => JSON_TYPE_STRING,
454 Int => JSON_TYPE_INT,
455 Float => JSON_TYPE_FLOAT,
456 Bool => JSON_TYPE_BOOL,
457 Null => JSON_TYPE_NULL,
458 'Str?' => JSON_TYPE_STRING_OR_NULL,
459 'Int?' => JSON_TYPE_INT_OR_NULL,
460 'Float?' => JSON_TYPE_FLOAT_OR_NULL,
461 'Bool?' => JSON_TYPE_BOOL_OR_NULL,
462 );
463  
464 5 my %SCALAR_TYPE_NAME = (
465 JSON_TYPE_SCALAR() => 'Any',
466 JSON_TYPE_STRING() => 'Str',
467 JSON_TYPE_INT() => 'Int',
468 JSON_TYPE_FLOAT() => 'Float',
469 JSON_TYPE_BOOL() => 'Bool',
470 JSON_TYPE_NULL() => 'Null',
471 );
472  
473 42 ▶sub _schema_scalar_type {
Subroutine _schema_scalar_type: called CC=3 SCAR=11.4
474 42 my ($type) = @_;
475 42 ▶ return $type if $type =~ /^-?[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $type =~ /^-?[0-9]+\z/ 4 38 42
476 38 ▶ return $SCALAR_TYPE_ALIAS{$type} if exists $SCALAR_TYPE_ALIAS{$type};
Branch: 1 branch
BranchTrueFalseTotal
if exists $SCALAR_TYPE_ALIAS{$type} 38 0 38
477 0 die "invalid scalar type '$type' in schema (expected a JSON_TYPE_* constant".
478 " or one of: " . join(', ', sort keys %SCALAR_TYPE_ALIAS) . ")";
479 }
480  
481 12 ▶sub _scalar_type_name {
Subroutine _scalar_type_name: called CC=2 SCAR=7.2
482 12 my ($type) = @_;
483 12 ▶ return exists $SCALAR_TYPE_NAME{$type} ? $SCALAR_TYPE_NAME{$type} : "type($type)";
Branch: 1 branch
BranchTrueFalseTotal
exists $SCALAR_TYPE_NAME{$type} ? : 12 0 12
484 }
485  
486 25 ▶sub _detect_scalar_type {
Subroutine _detect_scalar_type: called CC=6 SCAR=18.7
487 25 my ($value) = @_;
488 25 ▶ return JSON_TYPE_NULL unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 25 25
489 25 ▶ return JSON_TYPE_BOOL if Cpanel::JSON::XS::is_bool($value);
Branch: 1 branch
BranchTrueFalseTotal
if &Cpanel::JSON::XS::is_bool($value) 0 25 25
490 25 ▶ if (!ref($value) && looks_like_number($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $value and &looks_like_number($value)) 18 7 25
Condition66%2/3
not ref $value and &looks_like_number($value)
!ll&&!rl&&r
0718
MC/DC50%1/2
not ref $value and &looks_like_number($value)
not ref $value &looks_like_number($value)
Truth table66%2/3
not(A) and B
A= not ref $valueB= &looks_like_number($value)
ABresult
0X0
100
111
491 18 ▶ return $value =~ /^-?[0-9]+\z/ ? JSON_TYPE_INT : JSON_TYPE_FLOAT;
Branch: 1 branch
BranchTrueFalseTotal
$value =~ /^-?[0-9]+\z/ ? : 18 0 18
492 }
493 7 return JSON_TYPE_STRING;
494 }
495  
496 26 ▶sub check_type {
Subroutine check_type: called CC=1 SCAR=0.0
Pod documented
497 26 my ($data, $schema, $found) = @_;
498 26 my @errors;
499 26 _check_type($data, $schema, $found, '$', \@errors);
500 26 return @errors;
501 }
502  
503 64 ▶sub _check_type {
Subroutine _check_type: called CC=42 SCAR=40.1
504 64 my ($data, $schema, $found, $path, $errors) = @_;
505  
506 64 ▶ if (ref($schema) eq JSON_TYPE_OPTIONAL_CLASS) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $schema eq "Cpanel::JSON::XS::Type::Optional") 1 63 64
507 1 $schema = ${$schema};
508 1 ▶ return unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 1 0 1
509 }
510  
511 63 my $ref = ref($schema);
512  
513 63 ▶ if ($ref eq JSON_TYPE_ANYOF_CLASS) {
Branch: 5 branches
BranchTrueFalseTotal
if ($ref eq 'Cpanel::JSON::XS::Type::AnyOf') { } 2 61 63
elsif ($ref eq 'Cpanel::JSON::XS::Type::ArrayOf') { } 7 54 61
elsif ($ref eq 'ARRAY') { } 2 52 54
elsif ($ref eq 'Cpanel::JSON::XS::Type::HashOf') { } 2 50 52
elsif ($ref eq 'HASH') { } 8 42 50
514 2 my ($scalar_alt, $array_alt, $hash_alt) = @$schema;
515 2 my $dref = ref($data);
516 2 ▶ if ($dref eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if ($dref eq 'ARRAY') { } 1 1 2
elsif ($dref eq 'HASH') { } 0 1 1
517 1 ▶ return push @$errors, "$path: array not allowed by schema" unless defined $array_alt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $array_alt 0 1 1
518 1 return _check_type($data, $array_alt, $found, $path, $errors);
519 } elsif ($dref eq 'HASH') {
520 0 ▶ return push @$errors, "$path: hash not allowed by schema" unless defined $hash_alt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hash_alt 0 0 0
521 0 return _check_type($data, $hash_alt, $found, $path, $errors);
522 } else {
523 1 ▶ return push @$errors, "$path: scalar not allowed by schema" unless defined $scalar_alt;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $scalar_alt 0 1 1
524 1 return _check_type($data, $scalar_alt, $found, $path, $errors);
525 }
526 }
527 elsif ($ref eq JSON_TYPE_ARRAYOF_CLASS) {
528 7 ▶ if (ref($data) ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "ARRAY") 1 6 7
529 1 ▶ push @$errors, "$path: expected array, got " . (ref($data) || 'scalar');
Condition50%1/2
ref $data || 'scalar'
l!l
01
MC/DC0%0/1
ref $data || 'scalar'
ref $data
Truth table50%1/2
A
A= ref $data
Aresult
11
00
530 1 return;
531 }
532 6 my $sub = $$schema;
533 6 my $i = 0;
534 6 for my $elem (@$data) {
535 14 ▶ my $f = ref($found) eq 'ARRAY' ? $found->[$i] : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $found eq 'ARRAY' ? : 6 8 14
536 14 _check_type($elem, $sub, $f, $path . "->[$i]", $errors);
537 14 $i++;
538 }
539 }
540 elsif ($ref eq 'ARRAY') {
541 2 ▶ if (ref($data) ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "ARRAY") 0 2 2
542 0 ▶ push @$errors, "$path: expected array, got " . (ref($data) || 'scalar');
Condition0%0/2
ref $data || 'scalar'
l!l
00
MC/DC0%0/1
ref $data || 'scalar'
ref $data
Truth table0%0/2
A
A= ref $data
Aresult
11
00
543 0 return;
544 }
545 2 ▶ if (@$data != @$schema) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$data != @$schema) 1 1 2
546 1 push @$errors, "$path: expected array of length " . scalar(@$schema) . ", got " . scalar(@$data);
547 1 return;
548 }
549 1 for my $i (0 .. $#$schema) {
550 2 ▶ my $f = ref($found) eq 'ARRAY' ? $found->[$i] : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $found eq 'ARRAY' ? : 0 2 2
551 2 _check_type($data->[$i], $schema->[$i], $f, $path . "->[$i]", $errors);
552 }
553 }
554 elsif ($ref eq JSON_TYPE_HASHOF_CLASS) {
555 2 ▶ if (ref($data) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 0 2 2
556 0 ▶ push @$errors, "$path: expected hash, got " . (ref($data) || 'scalar');
Condition0%0/2
ref $data || 'scalar'
l!l
00
MC/DC0%0/1
ref $data || 'scalar'
ref $data
Truth table0%0/2
A
A= ref $data
Aresult
11
00
557 0 return;
558 }
559 2 my $sub = $$schema;
560 2 for my $key (sort keys %$data) {
561 4 ▶ my $f = ref($found) eq 'HASH' ? $found->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $found eq 'HASH' ? : 0 4 4
562 4 _check_type($data->{$key}, $sub, $f, $path . "->{$key}", $errors);
563 }
564 }
565 elsif ($ref eq 'HASH') {
566 8 ▶ if (ref($data) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 0 8 8
567 0 ▶ push @$errors, "$path: expected hash, got " . (ref($data) || 'scalar');
Condition0%0/2
ref $data || 'scalar'
l!l
00
MC/DC0%0/1
ref $data || 'scalar'
ref $data
Truth table0%0/2
A
A= ref $data
Aresult
11
00
568 0 return;
569 }
570 8 for my $key (sort keys %$schema) {
571 18 my $subschema = $schema->{$key};
572 18 ▶ unless (exists $data->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $data->{$key}) 2 16 18
573 2 ▶ push @$errors, "$path: missing required key '$key'"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $subschema eq "Cpanel::JSON::XS::Type::Optional" 1 1 2
574 unless ref($subschema) eq JSON_TYPE_OPTIONAL_CLASS;
575 2 next;
576 }
577 16 ▶ my $f = ref($found) eq 'HASH' ? $found->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $found eq 'HASH' ? : 9 7 16
578 16 _check_type($data->{$key}, $subschema, $f, $path . "->{$key}", $errors);
579 }
580 8 for my $key (sort keys %$data) {
581 17 ▶ push @$errors, "$path: unexpected key '$key'" unless exists $schema->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $schema->{$key} 1 16 17
582 }
583 }
584 else {
585 42 my $want = _schema_scalar_type($schema);
586 42 ▶ if ($want == JSON_TYPE_SCALAR) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want == 0) 2 40 42
587 # 'Any': matches every value, including undef/null
588 2 return;
589 }
590 40 ▶ if ($want == JSON_TYPE_NULL) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want == 256) 2 38 40
591 2 ▶ push @$errors, "$path: expected null, got " . _scalar_type_name(_detect_scalar_type($data))
Branch: 1 branch
BranchTrueFalseTotal
if defined $data 1 1 2
592 if defined $data;
593 2 return;
594 }
595 38 my $can_null = $want & JSON_TYPE_CAN_BE_NULL;
596 38 my $base = $want & ~JSON_TYPE_CAN_BE_NULL;
597 38 ▶ if (!defined $data) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 2 36 38
598 2 ▶ push @$errors, "$path: expected " . _scalar_type_name($base) . ", got null"
Branch: 1 branch
BranchTrueFalseTotal
unless $can_null 1 1 2
599 unless $can_null;
600 2 return;
601 }
602 36 ▶ my $actual = defined($found) && !ref($found) ? ($found & ~JSON_TYPE_CAN_BE_NULL) : _detect_scalar_type($data);
Branch: 1 branch
BranchTrueFalseTotal
defined $found && !ref($found) ? : 12 24 36
Condition66%2/3
defined $found and not ref $found
!ll&&!rl&&r
24012
MC/DC50%1/2
defined $found and not ref $found
defined $found not ref $found
Truth table66%2/3
A and not(B)
A= defined $foundB= not ref $found
ABresult
0X0
100
111
603 36 ▶ push @$errors, "$path: expected " . _scalar_type_name($base) . ", got " . _scalar_type_name($actual)
Branch: 1 branch
BranchTrueFalseTotal
if $actual != $base 5 31 36
604 if $actual != $base;
605 }
606 }
607  
608 5 1;
↑ Summary blib/lib/Cpanel/JSON/XS.pm »