blib/lib/JSON/Ordered/Conditional.pm untested

filter: Statementstmt 0.0% 0 / 70 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 11 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 121 CC 10 SCAR 24.8
CC
10
Cov
0%
ordered
30.0
compile
20.0
encode
6.0
CRAP 11.9
1 package JSON::Ordered::Conditional;
2  
3 use 5.006; use strict; use warnings; our $VERSION = '0.03';
4 use JSON::MultiValueOrdered; use base 'Struct::Conditional';
5  
6 use Tie::IxHash;
7  
8 our $JSON;
9  
10 BEGIN {
11 $JSON = JSON::MultiValueOrdered->new;
12 }
13  
14 sub encode {
15 if ($_[2]) {
16 $_[0]->encode_file($_[1], $_[2]);
17 }
18 $JSON->encode($_[1]);
19 }
20  
21 sub encode_file {
22 open my $file, '>', $_[2] or die "cannot open file $!";
23 print $file $_[0]->encode($_[1]);
24 close $file;
25 return $file;
26 }
27  
28 sub decode {
29 if ( $_[1] !~ m/\n/ && -f $_[1]) {
30 return $_[0]->decode_file($_[1]);
31 }
32 $JSON->decode($_[1]);
33 }
34  
35 sub decode_file {
36 open my $file, '<', $_[1] or die "cannot open file $!";
37 my $content = do { local $/; <$file> };
38 close $file;
39 return $_[0]->decode($content);
40 }
41  
42 sub compile {
43 my ($self, $json, $params, $return_struct, $out_file) = @_;
44 $json = $self->ordered($self->decode($json));
45 return unless ref $json;
46 $params = $self->decode($params) unless ref $params;
47 $json = $self->SUPER::compile($json, $params);
48 return $return_struct
49 ? $json
50 : $self->encode($json, $out_file);
51 }
52  
53 sub ordered {
54 my ($self, $json) = @_;
55  
56 my $oref = ref $json || "";
57  
58 if ($oref eq 'ARRAY') {
59 return [
60 map {
61 $self->ordered($_);
62 } @{$json}
63 ];
64 } elsif ($oref eq 'HASH') {
65 for my $key ( keys %{$json} ) {
66 my $ref = ref $json->{$key} || "";
67 if ( $ref eq 'HASH' ) {
68 $json->{$key} = $self->ordered($json->{$key});
69 } elsif ($ref eq 'ARRAY') {
70 for (my $i = 0; $i < scalar @{$json->{$key}}; $i++) {
71 $json->{$key}->[$i] = $self->ordered($json->{$key}->[$i]);
72 }
73 }
74 }
75 my %order;
76 tie %order, 'Tie::IxHash', %{$json};
77 return \%order;
78 }
79  
80 return $json;
81 }
82  
83 sub instantiate_hash {
84 my %hash;
85 tie %hash, 'Tie::IxHash';
86 return %hash;
87 }
88  
89 1;
90  
91 __END__