ThaiSchema/JSON.pm

filter: Statementstmt 82.0% 160 / 195 Branchbran 68.4% 78 / 114 Conditioncond 45.4% 10 / 22 MC/DCmcdc 36.3% 4 / 11 Subroutinesub 80.0% 16 / 20 Podpod 0.0% 0 / 6 totaltotal 72.8% 268 / 368 CC 65 SCAR 27.3
CC
65
Cov
75%
_decode_string
44.1
validate
22.5
_decode_value
17.0
CRAP 15.3
↑ Summary ThaiSchema.pm »
1 package ThaiSchema::JSON;
2 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 3 ▶use ThaiSchema;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 # Licensed under the Artistic 2.0 license.
10 # See http://www.perlfoundation.org/artistic_license_2_0.
11  
12 # This module is based on JSON::Tiny 0.22
13  
14 3 my $FALSE = \0;
15 3 my $TRUE = \1;
16  
17 0 ▶sub ddf {
Subroutine ddf: not called CC=1 SCAR=6.9
Pod undocumented
18 0 require Data::Dumper;
19 0 local $Data::Dumper::Terse = 1;
20 0 Data::Dumper::Dumper(@_);
21 }
22  
23 # Escaped special character map (with u2028 and u2029)
24 3 my %ESCAPE = (
25 '"' => '"',
26 '\\' => '\\',
27 '/' => '/',
28 'b' => "\x07",
29 'f' => "\x0C",
30 'n' => "\x0A",
31 'r' => "\x0D",
32 't' => "\x09",
33 'u2028' => "\x{2028}",
34 'u2029' => "\x{2029}"
35 );
36 3 my %REVERSE = map { $ESCAPE{$_} => "\\$_" } keys %ESCAPE;
37 3 ▶for ( 0x00 .. 0x1F, 0x7F ) { $REVERSE{ pack 'C', $_ } //= sprintf '\u%.4X', $_ }
Condition100%2/2
$REVERSE{pack "C", $_} //= sprintf("\\u%.4X", $_)
l!l
1584
MC/DC100%1/1
$REVERSE{pack "C", $_} //= sprintf("\\u%.4X", $_)
$REVERSE{pack "C", $_}
Truth table100%2/2
A
A= $REVERSE{pack "C", $_}
Aresult
11
00
38  
39 # Unicode encoding detection
40 3 my $UTF_PATTERNS = {
41 'UTF-32BE' => qr/^\0\0\0[^\0]/,
42 'UTF-16BE' => qr/^\0[^\0]\0[^\0]/,
43 'UTF-32LE' => qr/^[^\0]\0\0\0/,
44 'UTF-16LE' => qr/^[^\0]\0[^\0]\0/
45 };
46 3 my $WHITESPACE_RE = qr/[\x20\x09\x0a\x0d]*/;
47  
48 3 our $FAIL;
49  
50 3 our @_ERRORS;
51 3 our $_NAME = '';
52  
53 41 ▶sub new {
Subroutine new: called CC=3 SCAR=15.4
Pod undocumented
54 41 my $class = shift;
55 0 ▶ bless @_ ? @_ > 1 ? {@_} : { %{ $_[0] } } : {}, $class;
Branch: 2 branches
BranchTrueFalseTotal
@_ ? : 0 41 41
@_ > 1 ? : 0 0 0
56 }
57  
58 98 ▶sub error {
Subroutine error: called CC=2 SCAR=6.9
Pod undocumented
59 98 ▶ $_[0]->{error} = $_[1] if @_ > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ > 1 49 49 98
60 98 return $_[0]->{error};
61 }
62  
63 41 ▶sub validate {
Subroutine validate: called CC=17 SCAR=31.1
Pod undocumented
64 41 my ( $self, $bytes, $schema ) = @_;
65 41 $schema = _schema($schema);
66  
67 41 local $FAIL;
68 41 local @_ERRORS;
69 41 local $_NAME = '';
70  
71 # Cleanup
72 41 $self->error(undef);
73  
74 # Missing input
75 41 ▶ $self->error('Missing or empty input') and return undef
Branch: 1 branch
BranchTrueFalseTotal
unless $bytes 0 41 41
Condition20%1/5
$bytes || $self->error('Missing or empty input') && (return undef)
l!l&&r!l&&!r
4100
$self->error("Missing or empty input") and return undef
!ll
00
MC/DC0%0/2
$bytes || $self->error('Missing or empty input') && (return undef)
$bytes $self->error("Missing or empty input")
Truth table33%1/3
A || B
A= $bytesB= $self->error("Missing or empty input")
ABresult
1X1
011
000
76 unless $bytes; ## no critic (undef)
77  
78 # Remove BOM
79 41 $bytes =~
80 s/^(?:\357\273\277|\377\376\0\0|\0\0\376\377|\376\377|\377\376)//g;
81  
82 # Wide characters
83 41 ▶ $self->error('Wide character in input')
Branch: 1 branch
BranchTrueFalseTotal
unless utf8::downgrade($bytes, 1) 0 41 41
Condition20%1/5
utf8::downgrade($bytes, 1) || $self->error('Wide character in input') && (return undef)
l!l&&r!l&&!r
4100
$self->error("Wide character in input") and return undef
!ll
00
MC/DC0%0/2
utf8::downgrade($bytes, 1) || $self->error('Wide character in input') && (return undef)
utf8::downgrade($bytes, 1) $self->error("Wide character in input")
Truth table33%1/3
A || B
A= utf8::downgrade($bytes, 1)B= $self->error("Wide character in input")
ABresult
1X1
011
000
84 and return undef ## no critic (undef)
85 unless utf8::downgrade( $bytes, 1 );
86  
87 # Detect and decode Unicode
88 41 my $encoding = 'UTF-8';
89 41 ▶ $bytes =~ $UTF_PATTERNS->{$_} and $encoding = $_ for keys %$UTF_PATTERNS;
Branch: 1 branch
BranchTrueFalseTotal
$bytes =~ /$UTF_PATTERNS->{$_}/ and $encoding = $_ 0 164 164
90  
91 41 my $d_res = eval { $bytes = Encode::decode( $encoding, $bytes, 1 ); 1 };
92 41 ▶ $bytes = undef unless $d_res;
Branch: 1 branch
BranchTrueFalseTotal
unless $d_res 0 41 41
93  
94 # Object or array
95 41 my $res = eval {
96 41 local $_ = $bytes;
97  
98 # Leading whitespace
99 41 m/\G$WHITESPACE_RE/gc;
100  
101 # Array
102 41 my $ref;
103 41 ▶ if (m/\G\[/gc) {
Branch: 2 branches
BranchTrueFalseTotal
if (/\G\[/cg) { } 20 21 41
elsif (/\G\{/cg) { } 21 0 21
104 20 ▶ unless ($schema->is_array()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_array) 1 19 20
105 1 _exception2("Unexpected array found.");
106 }
107 19 $ref = _decode_array($schema->schema)
108 }
109  
110 # Object
111 elsif (m/\G\{/gc) {
112 21 ▶ unless ($schema->is_hash()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_hash) 1 20 21
113 1 _exception2("Unexpected object found.");
114 }
115 20 $ref = _decode_object($schema)
116 }
117  
118 # Unexpected
119 0 else { _exception('Expected array or object') }
120  
121 # Leftover data
122 33 ▶ unless (m/\G$WHITESPACE_RE\z/gc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/\G$WHITESPACE_RE\z/cg) 0 33 33
123 0 ▶ my $got = ref $ref eq 'ARRAY' ? 'array' : 'object';
Branch: 1 branch
BranchTrueFalseTotal
ref $ref eq 'ARRAY' ? : 0 0 0
124 0 _exception("Unexpected data after $got");
125 }
126  
127 33 $ref;
128 };
129  
130 # Exception
131 41 ▶ if ( !$res && ( my $e = $@ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $res and my $e = $@) 8 33 41
Condition66%2/3
not $res and my $e = $@
!ll&&!rl&&r
3308
MC/DC50%1/2
not $res and my $e = $@
not $res my $e = $@
Truth table66%2/3
not(A) and B
A= not $resB= my $e = $@
ABresult
0X0
100
111
132 8 chomp $e;
133 8 $self->error($e);
134 }
135  
136 41 ▶ if ($self->error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->error) 8 33 41
137 8 push @_ERRORS, $self->error;
138 8 $FAIL++;
139 }
140  
141 # return ($ok, \@errors);
142 41 return (!$FAIL, \@_ERRORS);
143 }
144  
145 16 ▶sub _fail {
Subroutine _fail: called CC=2 SCAR=7.2
146 16 my ($got, $schema) = @_;
147 16 ▶ _fail2(($_NAME ? "$_NAME: " : '') . $schema->name . " is expected, but $got is found");
Branch: 1 branch
BranchTrueFalseTotal
$ThaiSchema::JSON::_NAME ? : 16 0 16
148 }
149  
150 17 ▶sub _fail2 {
Subroutine _fail2: called CC=1 SCAR=0.0
151 17 my ($msg) = @_;
152 17 $FAIL++;
153 17 push @_ERRORS, $msg;
154 }
155  
156 0 ▶sub false { $FALSE }
Subroutine false: not called CC=1 SCAR=6.9
Pod undocumented
157 0 ▶sub true { $TRUE }
Subroutine true: not called CC=1 SCAR=6.9
Pod undocumented
158  
159 26 ▶sub _decode_array {
Subroutine _decode_array: called CC=4 SCAR=14.1
160 26 my $schema = _schema(shift);
161  
162 26 my @array;
163 26 my $i = 0;
164 26 ▶ until (m/\G$WHITESPACE_RE\]/gc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/\G$WHITESPACE_RE\]/cg) 24 2 26
165 24 local $_NAME = $_NAME . "[$i]";
166  
167 # Value
168 24 push @array, _decode_value($schema);
169  
170 20 $i++;
171  
172 # Separator
173 20 ▶ redo if m/\G$WHITESPACE_RE,/gc;
Branch: 1 branch
BranchTrueFalseTotal
if /\G$WHITESPACE_RE,/cg 0 20 20
174  
175 # End
176 20 ▶ last if m/\G$WHITESPACE_RE\]/gc;
Branch: 1 branch
BranchTrueFalseTotal
if /\G$WHITESPACE_RE\]/cg 20 0 20
177  
178 # Invalid character
179 0 _exception(
180 'Expected comma or right square bracket while parsing array');
181 }
182  
183 22 return \@array;
184 }
185  
186 25 ▶sub _decode_object {
Subroutine _decode_object: called CC=10 SCAR=23.1
187 25 my $schema = _schema(shift);
188  
189 25 my %hash;
190 25 ▶ my %schema = $schema->isa("ThaiSchema::Maybe") ? %{$schema->schema->schema} : %{$schema->schema};
Branch: 1 branch
BranchTrueFalseTotal
$schema->isa('ThaiSchema::Maybe') ? : 1 24 25
191 25 ▶ until (m/\G$WHITESPACE_RE\}/gc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/\G$WHITESPACE_RE\}/cg) 23 2 25
192  
193 # Quote
194 28 ▶ m/\G$WHITESPACE_RE"/gc
Branch: 1 branch
BranchTrueFalseTotal
/\G$WHITESPACE_RE"/cg or _exception("Expected string while parsing object") 28 0 28
195 or _exception('Expected string while parsing object');
196  
197 # Key
198 28 my $key = _decode_string();
199  
200 # Colon
201 28 ▶ m/\G$WHITESPACE_RE:/gc
Branch: 1 branch
BranchTrueFalseTotal
/\G$WHITESPACE_RE:/cg or _exception("Expected colon while parsing object") 28 0 28
202 or _exception('Expected colon while parsing object');
203  
204 # Value
205 28 local $_NAME = $_NAME . ".$key";
206 28 my $cschema = delete $schema{$key};
207 28 ▶ if ($cschema) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cschema) { } 22 6 28
208 22 $hash{$key} = _decode_value($cschema);
209 } else {
210 6 ▶ if ($ThaiSchema::ALLOW_EXTRA) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ThaiSchema::ALLOW_EXTRA) { } 5 1 6
211 5 $hash{$key} = _decode_value(ThaiSchema::Extra->new());
212 } else {
213 1 _exception2("There is extra key: $key");
214 }
215 }
216  
217 # Separator
218 26 ▶ redo if m/\G$WHITESPACE_RE,/gc;
Branch: 1 branch
BranchTrueFalseTotal
if /\G$WHITESPACE_RE,/cg 5 21 26
219  
220 # End
221 21 ▶ last if m/\G$WHITESPACE_RE\}/gc;
Branch: 1 branch
BranchTrueFalseTotal
if /\G$WHITESPACE_RE\}/cg 21 0 21
222  
223 # Invalid character
224 0 _exception(
225 'Expected comma or right curly bracket while parsing object');
226 }
227  
228 23 ▶ if (%schema) {
Branch: 1 branch
BranchTrueFalseTotal
if (%schema) 1 22 23
229 1 _fail2('There is missing keys: ' . join(', ', keys %schema));
230 }
231  
232 23 return \%hash;
233 }
234  
235 34 ▶sub _decode_string {
Subroutine _decode_string: called CC=9 SCAR=37.9
236 34 my $pos = pos;
237  
238 # Extract string with escaped characters
239 34 m#\G(((?:[^\x00-\x1F\\"]|\\(?:["\\/bfnrt]|u[[:xdigit:]]{4})){0,32766})*)#gc;
240 34 my $str = $1;
241  
242 # Missing quote
243 34 ▶ unless (m/\G"/gc) {
Branch: 1 branch
BranchTrueFalseTotal
unless (/\G"/cg) 0 34 34
244 0 ▶ _exception(
Branch: 1 branch
BranchTrueFalseTotal
if /\G[\x00-\x1F\\]/ 0 0 0
245 'Unexpected character or invalid escape while parsing string')
246 if m/\G[\x00-\x1F\\]/;
247 0 _exception('Unterminated string');
248 }
249  
250 # Unescape popular characters
251 34 ▶ if ( index( $str, '\\u' ) < 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($str, "\\u") == -1) 34 0 34
252 34 $str =~ s!\\(["\\/bfnrt])!$ESCAPE{$1}!gs;
253 34 return $str;
254 }
255  
256 # Unescape everything else
257 0 my $buffer = '';
258 0 ▶ while ( $str =~ m/\G([^\\]*)\\(?:([^u])|u(.{4}))/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ /\G([^\\]*)\\(?:([^u])|u(.{4}))/cg) 0 0 0
259 0 $buffer .= $1;
260  
261 # Popular character
262 0 ▶ if ($2) { $buffer .= $ESCAPE{$2} }
Branch: 1 branch
BranchTrueFalseTotal
if ($2) { } 0 0 0
263  
264 # Escaped
265 else {
266 0 my $ord = hex $3;
267  
268 # Surrogate pair
269 0 ▶ if ( ( $ord & 0xF800 ) == 0xD800 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ord & 63488) == 55296) 0 0 0
270  
271 # High surrogate
272 0 ▶ ( $ord & 0xFC00 ) == 0xD800
Branch: 1 branch
BranchTrueFalseTotal
($ord & 64512) == 55296 or pos $_ = $pos + pos($str), _exception("Missing high-surrogate") 0 0 0
273 or pos($_) = $pos + pos($str),
274 _exception('Missing high-surrogate');
275  
276 # Low surrogate
277 0 ▶ $str =~ m/\G\\u([Dd][C-Fc-f]..)/gc
Branch: 1 branch
BranchTrueFalseTotal
$str =~ /\G\\u([Dd][C-Fc-f]..)/cg or pos $_ = $pos + pos($str), _exception("Missing low-surrogate") 0 0 0
278 or pos($_) = $pos + pos($str),
279 _exception('Missing low-surrogate');
280  
281 # Pair
282 0 $ord =
283 0x10000 + ( $ord - 0xD800 ) * 0x400 + ( hex($1) - 0xDC00 );
284 }
285  
286 # Character
287 0 $buffer .= pack 'U', $ord;
288 }
289 }
290  
291 # The rest
292 0 return $buffer . substr $str, pos($str), length($str);
293 }
294  
295 145 ▶sub _schema {
Subroutine _schema: called CC=4 SCAR=14.0
296 145 my $schema = shift;
297 145 ▶ if (ref $schema eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $schema eq 'HASH') { } 9 136 145
elsif (ref $schema eq 'ARRAY') { } 2 134 136
298 9 return ThaiSchema::Hash->new(schema => $schema);
299 } elsif (ref $schema eq 'ARRAY') {
300 2 ▶ if (@$schema > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$schema > 1) 0 2 2
301 0 Carp::confess("Invalid schema: too many elements in arrayref: " . ddf($schema));
302 }
303 2 return ThaiSchema::Array->new(schema => _schema($schema->[0]));
304 } else {
305 134 return $schema;
306 }
307 }
308  
309 51 ▶sub _decode_value {
Subroutine _decode_value: called CC=17 SCAR=28.3
310 51 my $schema = _schema(shift);
311  
312 # Leading whitespace
313 51 m/\G$WHITESPACE_RE/gc;
314  
315 # String
316 51 ▶ if (m/\G"/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G"/cg) 6 45 51
317 6 ▶ unless ($schema->is_string) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_string) 4 2 6
318 4 _fail('string', $schema);
319 }
320 6 return _decode_string();
321 }
322  
323 # Array
324 45 ▶ if (m/\G\[/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G\[/cg) 9 36 45
325 9 ▶ unless ($schema->is_array) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_array) 2 7 9
326 2 _fail('array', $schema);
327 2 _exception2("Unexpected array.");
328 }
329 7 return _decode_array($schema->schema);
330 }
331  
332 # Object
333 36 ▶ if (m/\G\{/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G\{/cg) 8 28 36
334 8 ▶ unless ($schema->is_hash) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_hash) 3 5 8
335 3 _fail('object', $schema);
336 3 _exception2("Unexpected hash.");
337 }
338 5 return _decode_object($schema);
339 }
340  
341 # Number
342 28 ▶ if (m/\G([-]?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\G([-]?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)/cg) 16 12 28
343 16 my $number = 0+$1;
344 16 ▶ unless ($schema->is_number) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_number) 2 14 16
345 2 _fail('number', $schema);
346 }
347 16 ▶ if ($schema->is_integer && int($number) != $number) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema->is_integer and int $number != $number) 1 15 16
Condition100%3/3
$schema->is_integer and int $number != $number
!ll&&!rl&&r
2131
MC/DC100%2/2
$schema->is_integer and int $number != $number
$schema->is_integer int $number != $number
Truth table100%3/3
A and B
A= $schema->is_integerB= int $number != $number
ABresult
0X0
100
111
348 1 push @_ERRORS, "integer is expected, but you got $number";
349 1 $FAIL++;
350 }
351 16 return $number;
352 }
353  
354 # True
355 12 ▶ if (m/\Gtrue/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\Gtrue/cg) 6 6 12
356 6 ▶ unless ($schema->is_bool) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_bool) 2 4 6
357 2 _fail('true', $schema);
358 }
359 6 return $TRUE;
360 }
361  
362 # False
363 6 ▶ if (m/\Gfalse/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\Gfalse/cg) 2 4 6
364 2 ▶ unless ($schema->is_bool) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_bool) 1 1 2
365 1 _fail('false', $schema);
366 }
367 2 return $FALSE;
368 }
369  
370 # Null
371 4 ▶ if (m/\Gnull/gc) {
Branch: 1 branch
BranchTrueFalseTotal
if (/\Gnull/cg) 4 0 4
372 4 ▶ unless ($schema->is_null) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema->is_null) 2 2 4
373 2 _fail('null', $schema);
374 }
375 ## no critic (return)
376 4 return undef;
377 }
378  
379 # Invalid data
380 0 _exception('Expected string, array, object, number, boolean or null');
381 }
382  
383 8 ▶sub _exception2 {
Subroutine _exception2: called CC=4 SCAR=14.2
384 # Leading whitespace
385 8 m/\G$WHITESPACE_RE/gc;
386  
387 # Context
388 8 my $context;
389 8 ▶ $context .= "$_NAME: " if $_NAME;
Branch: 1 branch
BranchTrueFalseTotal
if $ThaiSchema::JSON::_NAME 6 2 8
390 8 $context .= shift;
391 0 ▶ if (m/\G\z/gc) { $context .= ' before end of data' }
Branch: 1 branch
BranchTrueFalseTotal
if (/\G\z/cg) { } 0 8 8
392 else {
393 8 my @lines = split /\n/, substr( $_, 0, pos );
394 8 ▶ $context .=
Condition50%1/2
pop @lines || ''
l!l
80
MC/DC0%0/1
pop @lines || ''
pop @lines
Truth table50%1/2
A
A= pop @lines
Aresult
11
00
395 ' at line ' . @lines . ', offset ' . length( pop @lines || '' );
396 }
397  
398 # Throw
399 8 die "$context\n";
400 }
401  
402 0 ▶sub _exception {
Subroutine _exception: not called CC=3 SCAR=24.8
403  
404 # Leading whitespace
405 0 m/\G$WHITESPACE_RE/gc;
406  
407 # Context
408 0 my $context = 'Malformed JSON: ' . shift;
409 0 ▶ if (m/\G\z/gc) { $context .= ' before end of data' }
Branch: 1 branch
BranchTrueFalseTotal
if (/\G\z/cg) { } 0 0 0
410 else {
411 0 my @lines = split /\n/, substr( $_, 0, pos );
412 0 ▶ $context .=
Condition0%0/2
pop @lines || ''
l!l
00
MC/DC0%0/1
pop @lines || ''
pop @lines
Truth table0%0/2
A
A= pop @lines
Aresult
11
00
413 ' at line ' . @lines . ', offset ' . length( pop @lines || '' );
414 }
415  
416 # Throw
417 0 die "$context\n";
418 }
419  
420 3 1;
421 __END__
↑ Summary ThaiSchema.pm »