blib/lib/JSON/MergePatch.pm

filter: Statementstmt 100% 17 / 17 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 100% 23 / 23 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Build ↑ Summary
1 package JSON::MergePatch;
2 3 ▶use 5.008001;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 our $VERSION = "0.01";
7  
8 3 ▶use parent 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use JSON qw/encode_json decode_json/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use List::MoreUtils qw/uniq/;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 our @EXPORT = qw/json_merge_patch json_merge_diff/;
13  
14  
15 sub patch {
16 my ($class, $target, $patch, $opt) = @_;
17 if (defined $target && !$opt->{repeat}) {
18 $target = decode_json($target);
19 }
20  
21 if (ref $patch eq 'HASH') {
22 unless (ref $target eq 'HASH') {
23 $target = +{};
24 }
25  
26 for my $key (keys $patch) {
27 if (defined $patch->{$key}) {
28 $target->{$key} = __PACKAGE__->patch($target->{$key}, $patch->{$key}, {repeat => 1});
29 }
30 else {
31 if (exists $target->{$key}) {
32 delete $target->{$key};
33 }
34 }
35 }
36 return ref $target ? encode_json($target) : $target;
37 }
38  
39 return ref $patch ? encode_json($patch) : $patch;
40 }
41  
42 sub diff {
43 my ($class, $source, $target, $opt) = @_;
44  
45 my ($decoded_source, $decoded_target);
46 if ($opt->{repeat}) {
47 $decoded_source = $source;
48 $decoded_target = $target;
49 } else {
50 $decoded_source = eval {
51 decode_json($source);
52 };
53 if ($@) {
54 return $source;
55 }
56  
57 $decoded_target = eval {
58 decode_json($target);
59 };
60 if ($@) {
61 return $decoded_source;
62 }
63 }
64  
65 if (ref $decoded_source eq 'ARRAY') {
66 return $decoded_source;
67 }
68  
69 if (ref $decoded_source eq 'HASH') {
70 if (ref $decoded_target eq 'HASH') {
71 for my $key (uniq (keys $decoded_target, keys $decoded_source)) {
72 $decoded_source->{$key} = __PACKAGE__->diff($decoded_source->{$key}, $decoded_target->{$key}, {repeat => 1});
73  
74 if (exists $decoded_target->{$key} && exists $decoded_source->{$key}) {
75 if (
76 (!defined $decoded_target->{$key} && !defined $decoded_source->{$key}) ||
77 (defined $decoded_target->{$key} && defined $decoded_source->{$key} && $decoded_target->{$key} eq $decoded_source->{$key})
78 ) {
79 delete $decoded_source->{$key};
80 }
81 }
82 }
83  
84 return $decoded_source;
85 }
86 else {
87 return $decoded_source;
88 }
89 }
90  
91 return $decoded_source;
92 }
93  
94 sub json_merge_patch {
95 __PACKAGE__->patch(@_);
96 }
97  
98 sub json_merge_diff {
99 __PACKAGE__->diff(@_);
100 }
101  
102  
103 1;
104 __END__
« Build ↑ Summary