blib/lib/MOP4Import/Base/JSON.pm untested

filter: Statementstmt 0.0% 0 / 55 Branchbran 0.0% 0 / 12 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 94 CC 7 SCAR 27.6
CC
7
Cov
0%
cli_encode_json_as_bytes
42.0
cli_json_encoder
6.0
TO_JSON
2.0
CRAP 15.8
1 package MOP4Import::Base::JSON;
2 use strict;
3 use warnings;
4 use constant DEBUG => $ENV{DEBUG_MOP4IMPORT};
5  
6 use MOP4Import::Base::Configure -as_base;
7  
8 use JSON::MaybeXS;
9 use constant USING_CPANEL_JSON_XS => JSON()->isa("Cpanel::JSON::XS");
10  
11 # Only works with Cpanel::JSON::XS. JSON::XS prohibits use of restricted hash.
12 sub TO_JSON {
13 my ($self) = @_;
14 +{map(($_ => $self->{$_}), grep {!/^_/} keys %$self)}
15 }
16  
17 sub cli_json_type {
18 (my MY $self) = @_;
19 $self->cli_json_type_of($self);
20 }
21  
22 sub cli_json_type_of {
23 (my MY $self, my $objOrTypeName) = @_;
24 $self->JSON_TYPE_HANDLER->lookup_json_type(ref $objOrTypeName || $objOrTypeName);
25 }
26  
27 sub cli_json_encoder {
28 (my MY $self) = @_;
29 my $js = JSON()->new->canonical->allow_nonref;
30 if (USING_CPANEL_JSON_XS) {
31 $js->convert_blessed;
32 }
33 $js;
34 }
35  
36 sub cli_encode_json {
37 (my MY $self, my ($obj, $json_type)) = @_;
38 my $json = $self->cli_encode_json_as_bytes($obj, $json_type);
39 $json;
40 }
41  
42 sub cli_encode_json_as_bytes {
43 (my MY $self, my ($obj, $json_type)) = @_;
44 my $codec = $self->cli_json_encoder;
45 my @opts;
46 my $json = do {
47 if (not USING_CPANEL_JSON_XS) {
48 $codec->encode($obj);
49 }
50 elsif (defined $json_type) {
51 $codec->encode($obj, $self->cli_json_type_of($json_type) // $json_type);
52 }
53 elsif (my $sub = UNIVERSAL::can($obj, 'TO_JSON')) {
54 my $conv = $sub->($obj);
55 if (ref $conv eq 'HASH') {
56 $codec->encode($conv, $self->cli_json_type_of(ref $obj));
57 } else {
58 $codec->encode($conv);
59 }
60 }
61 elsif (ref $obj and my @opts = $self->cli_json_type_of(ref $obj)) {
62 $codec->encode($obj, @opts);
63 }
64 else {
65 $codec->encode($obj);
66 }
67 };
68 $json;
69 }
70  
71 1;