Valiant/JSON/JSONBuilder.pm

filter: Statementstmt 95.0% 266 / 280 Branchbran 76.0% 108 / 142 Conditioncond 64.1% 34 / 53 MC/DCmcdc 35.7% 10 / 28 Subroutinesub 93.4% 43 / 46 Podpod 65.3% 17 / 26 totaltotal 83.1% 478 / 575 CC 94 SCAR 20.2
CC
94
Cov
86%
set_current_data
18.5
array
14.2
__ANON__
11.1
CRAP 7.6
« Valiant/Util.pm ↑ Summary Valiant/Filterable.pm »
1 package Valiant::JSON::JSONBuilder;
2  
3 4 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use Module::Runtime 'use_module';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Cpanel::JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use Valiant::HTML::Util::Collection;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use Valiant::Naming;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use Valiant::HTML::FormBuilder::DefaultModel;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 4 has model => (is=>'rw', required=>1);
13 4 has has_custom_view => ( is=>'ro', required=>1);
14 4 has view => ( is=>'ro', required=>1);
15  
16 4 has namespace => (is=>'ro', required=>1, default=>'');
17  
18 4 has content_type => (is=>'ro', required=>1, default=>'application/json');
19  
20 10 ▶has data => (is=>'rw', required=>1, default=>sub { +{ data => +{}} });
Subroutine __ANON__: called CC=1 SCAR=0.0
21 4 has index => (is=>'rw', clearer=>1, predicate=>1);
22  
23 4 has data_pointer => (
24 is => 'rw',
25 required => 1,
26 lazy => 1,
27 builder => 1,
28 clearer => 1,
29 predicate => 1,
30 );
31 50 ▶ sub _build_data_pointer {
Subroutine _build_data_pointer: called CC=2 SCAR=6.9
32 50 my ($self) = @_;
33 50 my $ns = $self->namespace;
34 50 ▶ if($ns eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ns eq '') { } 1 49 50
35 1 return [ $self->data->{data} ];
36 } else {
37 49 $self->data(+{ data => { $ns => +{} }});
38 49 return [ $self->data->{data}{$ns} ];
39 }
40 }
41  
42 has 'json_args' => (
43 is => 'ro',
44 required => 1,
45 10 ▶ default => sub { +{} },
Subroutine __ANON__: called CC=1 SCAR=0.0
46 4 );
47  
48 has 'json' => (
49 is => 'ro',
50 required => 1,
51 lazy => 1,
52 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
53 0 my %args = %{ shift->json_args };
54 0 return Cpanel::JSON::XS->new(%args, utf8=>1, pretty=>1);
55 },
56 4 handles => {
57 encode_json => 'encode',
58 },
59 );
60  
61 40 ▶sub reset {
Subroutine reset: called CC=1 SCAR=0.0
Pod documented
62 40 my ($self) = @_;
63 40 $self->data(+{ data => +{} });
64 40 $self->clear_data_pointer;
65 40 $self->clear_index;
66 40 return $self;
67 }
68  
69 5 ▶sub json_true { Cpanel::JSON::XS::true() }
Subroutine json_true: called CC=1 SCAR=0.0
Pod documented
70 2 ▶sub json_false { Cpanel::JSON::XS::false() }
Subroutine json_false: called CC=1 SCAR=0.0
Pod documented
71  
72 0 ▶sub render_json {
Subroutine render_json: not called CC=1 SCAR=6.9
Pod documented
73 0 my ($self) = @_;
74 0 return my $json = $self->encode_json($self->render_perl);
75 }
76  
77 52 ▶sub render_perl {
Subroutine render_perl: called CC=2 SCAR=6.9
Pod documented
78 52 my ($self) = @_;
79 52 ▶ $self->data_pointer unless $self->has_data_pointer;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_data_pointer 9 43 52
80 52 return $self->data->{data};
81 }
82  
83 46 ▶sub push_model {
Subroutine push_model: called CC=1 SCAR=0.0
Pod undocumented
84 46 my ($self, $model) = @_;
85 46 $self->model([@{$self->model}, $model]);
86 46 return $self;
87 }
88  
89 46 ▶sub pop_model {
Subroutine pop_model: called CC=1 SCAR=0.0
Pod undocumented
90 46 my ($self) = @_;
91 46 my @models = @{ $self->model };
92 46 my $discard = pop @models;
93 46 $self->model(\@models);
94 46 return $self;
95 }
96  
97 26 ▶sub push_pointer {
Subroutine push_pointer: called CC=4 SCAR=13.9
Pod undocumented
98 26 my ($self, $key, $type, %opts) = @_;
99 26 ▶ my $ns = exists $opts{namespace} ? $opts{namespace} : $key;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'namespace'} ? : 14 12 26
100  
101 26 ▶ $type ||= +{};
Condition50%1/2
$type ||= {}
l!l
260
MC/DC0%0/1
$type ||= {}
$type
Truth table50%1/2
A
A= $type
Aresult
11
00
102 26 $self->current_data->{$ns} = $type;
103 $self->data_pointer([
104 26 @{$self->data_pointer},
105 26 $self->current_data->{$ns},
106 ]);
107 26 ▶ $self->index(0) if ref($type) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $type eq "ARRAY" 13 13 26
108 26 return $self;
109 }
110  
111 26 ▶sub pop_pointer {
Subroutine pop_pointer: called CC=1 SCAR=0.0
Pod undocumented
112 26 my ($self) = @_;
113 26 my @pointers = @{ $self->data_pointer };
114 26 my $discard = pop @pointers;
115 26 $self->data_pointer(\@pointers);
116 26 return $self;
117 }
118  
119 31 ▶sub inc_index {
Subroutine inc_index: called CC=1 SCAR=0.0
Pod undocumented
120 31 my ($self) = @_;
121 31 $self->index($self->index + 1);
122 31 return $self;
123 }
124  
125 11 ▶sub _to_model {
Subroutine _to_model: called CC=4 SCAR=14.6
126 11 my ($self, $model) = @_;
127 11 ▶ croak "No model provided" unless $model;
Branch: 1 branch
BranchTrueFalseTotal
unless $model 0 11 11
128 11 ▶ confess "Model is not an object: $model" unless Scalar::Util::blessed($model);
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($model) 0 11 11
129 11 ▶ return $model->to_model if $model->can('to_model');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("to_model") 0 11 11
130 11 return $model;
131 }
132  
133 11 ▶sub _model_name_from_object_or_class {
Subroutine _model_name_from_object_or_class: called CC=2 SCAR=6.9
134 11 my ($self, $proto) = @_;
135 11 my $model = $self->_to_model($proto);
136 11 ▶ return $model->model_name if $model->can('model_name');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("model_name") 7 4 11
137 4 return Valiant::Name->new(Valiant::Naming::prepare_model_name_args($model));
138 }
139  
140 10 ▶around BUILDARGS => sub {
Subroutine __ANON__: called CC=10 SCAR=24.1
141 10 my ($orig, $class, @args) = @_;
142 10 my $options = $class->$orig(@args);
143 10 my $model_name = '';
144  
145 10 ▶ $options->{has_custom_view} = exists($options->{view}) ? 1:0;
Branch: 1 branch
BranchTrueFalseTotal
exists $options->{'view'} ? : 1 9 10
146 10 ▶ $options->{view} ||= Module::Runtime::use_module('Valiant::HTML::Util::View')->new;
Condition66%2/3
$options->{"view"} ||= &Module::Runtime::use_module("Valiant::HTML::Util::View")->new
l!l&&r!l&&!r
190
MC/DC0%0/2
$options->{"view"} ||= &Module::Runtime::use_module("Valiant::HTML::Util::View")->new
$options->{"view"} &Module::Runtime::use_module("Valiant::HTML::Util::View")->new
Truth table66%2/3
A ||= B
A= $options->{"view"}B= &Module::Runtime::use_module("Valiant::HTML::Util::View")->new
ABresult
1X1
011
000
147 10 ▶ $options->{model} ||= bless +{}, 'Valiant::HTML::FormBuilder::DefaultModel';
Condition50%1/2
$options->{"model"} ||= bless({}, "Valiant::HTML::FormBuilder::DefaultModel")
l!l
100
MC/DC0%0/1
$options->{"model"} ||= bless({}, "Valiant::HTML::FormBuilder::DefaultModel")
$options->{"model"}
Truth table50%1/2
A
A= $options->{"model"}
Aresult
11
00
148  
149 10 ▶ if(blessed $options->{model}) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($options->{'model'})) { } 9 1 10
150 9 $model_name = $class->_model_name_from_object_or_class($options->{model})->param_key;
151 $options->{namespace} = $model_name unless exists($options->{namespace})
152 9 ▶ } else {
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options->{"namespace"} 7 2 9
153 1 $model_name = $options->{model};
154 1 ▶ if($options->{view}->can('get_model_for_json')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($options->{'view'}->can('get_model_for_json')) { } 0 1 1
elsif ($options->{'view'}->can($model_name)) { } 1 0 1
155 0 $options->{model} = $options->{view}->get_model_for_json($model_name);
156 } elsif($options->{view}->can($model_name)){
157 1 $options->{model} = $options->{view}->$model_name;
158 } else {
159 0 croak "Can't find model '$model_name' in view";
160 }
161 $options->{namespace} = $model_name unless exists($options->{namespace})
162 1 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options->{"namespace"} 1 0 1
163  
164 $options->{model} = [$options->{model}]
165 10 ▶ unless ref $options->{model} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $options->{"model"} eq "ARRAY" 10 0 10
166  
167 10 return $options;
168 4 };
169  
170 65 ▶sub get_attribute_for_json {
Subroutine get_attribute_for_json: called CC=3 SCAR=12.0
Pod documented
171 65 my ($self, $name) = @_;
172 65 my $model = $self->model->[-1];
173 65 ▶ return my $value = $model->get_attribute_for_json($name) if $model->can('get_attribute_for_json');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("get_attribute_for_json") 0 65 65
174 65 ▶ return $model->$name if $model->can($name);
Branch: 1 branch
BranchTrueFalseTotal
if $model->can($name) 65 0 65
175 0 croak "Can't find attribute '$name' for model '$model'";
176 }
177  
178 1 ▶sub has_attribute_for_json {
Subroutine has_attribute_for_json: called CC=5 SCAR=17.8
Pod documented
179 1 my ($self, $name) = @_;
180 1 my $model = $self->model->[-1];
181 1 ▶ return my $value = $model->has_attribute_for_json($name) if $model->can('has_attribute_for_json');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("has_attribute_for_json") 0 1 1
182 1 ▶ return $self->view->has_attribute_for_json($model, $name) if $self->view->can('has_attribute_for_json');
Branch: 1 branch
BranchTrueFalseTotal
if $self->view->can("has_attribute_for_json") 0 1 1
183 1 ▶ my $predicate = $self->view->can('build_predicate') ? $self->view->build_predicate($model, $name) : "has_${name}";
Branch: 1 branch
BranchTrueFalseTotal
$self->view->can('build_predicate') ? : 0 1 1
184 1 ▶ return $model->$predicate if $model->can($predicate);
Branch: 1 branch
BranchTrueFalseTotal
if $model->can($predicate) 1 0 1
185 0 croak "Can't find attribute '$name' for model '$model'";
186 }
187  
188 130 ▶sub current_data {
Subroutine current_data: called CC=1 SCAR=0.0
Pod undocumented
189 130 my ($self) = @_;
190 130 my $what = $self->data_pointer->[-1];
191 130 return $what;
192 }
193  
194 5 ▶sub current_model {
Subroutine current_model: called CC=1 SCAR=0.0
Pod undocumented
195 5 my ($self) = @_;
196 5 my $model = $self->model->[-1];
197 5 return $model;
198 }
199  
200 78 ▶sub set_current_data {
Subroutine set_current_data: called CC=15 SCAR=29.2
Pod undocumented
201 78 my ($self, $key, $value, %opts) = @_;
202 78 ▶ return $self if $opts{omit_undef} && !defined($value);
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"omit_undef"} and not defined $value 17 61 78
Condition100%3/3
$opts{"omit_undef"} and not defined $value
!ll&&!rl&&r
57417
MC/DC100%2/2
$opts{"omit_undef"} and not defined $value
$opts{"omit_undef"} not defined $value
Truth table100%3/3
A and not(B)
A= $opts{"omit_undef"}B= not defined $value
ABresult
0X0
100
111
203 61 ▶ return $self if $opts{omit_empty} && (ref($value)||'') eq 'ARRAY' && !@$value;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"omit_empty"} and (ref $value || "") eq "ARRAY" and not @$value 0 61 61
Condition50%4/8
$opts{"omit_empty"} and (ref $value || "") eq "ARRAY" and not @$value
!ll&&!rl&&r
6100
$opts{"omit_empty"} and (ref $value || "") eq "ARRAY"
!ll&&!rl&&r
6010
ref $value || ''
l!l
01
MC/DC0%0/3
$opts{"omit_empty"} and (ref $value || "") eq "ARRAY" and not @$value
$opts{"omit_empty"} ref $value not @$value
Truth table50%2/4
A and B and not(C)
A= $opts{"omit_empty"}B= ref $valueC= not @$value
ABCresult
0XX0
10X0
1100
1111
204 61 ▶ return $self if $opts{omit_empty} && (ref($value)||'') eq 'HASH' && !%$value;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"omit_empty"} and (ref $value || "") eq "HASH" and not %$value 0 61 61
Condition50%4/8
$opts{"omit_empty"} and (ref $value || "") eq "HASH" and not %$value
!ll&&!rl&&r
6100
$opts{"omit_empty"} and (ref $value || "") eq "HASH"
!ll&&!rl&&r
6010
ref $value || ''
l!l
01
MC/DC0%0/3
$opts{"omit_empty"} and (ref $value || "") eq "HASH" and not %$value
$opts{"omit_empty"} ref $value not %$value
Truth table50%2/4
A and B and not(C)
A= $opts{"omit_empty"}B= ref $valueC= not %$value
ABCresult
0XX0
10X0
1100
1111
205 61 ▶ return $self if $opts{omit_empty} && !$self->has_attribute_for_json($key);;
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"omit_empty"} and not $self->has_attribute_for_json($key) 1 60 61
Condition66%2/3
$opts{"omit_empty"} and not $self->has_attribute_for_json($key)
!ll&&!rl&&r
6001
MC/DC50%1/2
$opts{"omit_empty"} and not $self->has_attribute_for_json($key)
$opts{"omit_empty"} not $self->has_attribute_for_json($key)
Truth table66%2/3
A and not(B)
A= $opts{"omit_empty"}B= not $self->has_attribute_for_json($key)
ABresult
0X0
100
111
206  
207 60 ▶ $key = $opts{name} if exists $opts{name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"name"} 4 56 60
208 60 ▶ if($self->has_index) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_index) { } 11 49 60
209 11 $self->current_data->[$self->index]{$key} = $value;
210 } else {
211 49 $self->current_data->{$key} = $value;
212 }
213 60 return $self;
214 }
215  
216 0 ▶sub TO_JSON {
Subroutine TO_JSON: not called CC=1 SCAR=6.9
Pod undocumented
217 0 my ($self) = @_;
218 0 return $self->render_perl;
219 }
220  
221 104 ▶sub _normalize_opts {
Subroutine _normalize_opts: called CC=8 SCAR=21.1
222 104 my ($self, @args) = @_;
223 104 ▶ return () unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 51 53 104
224 53 ▶ if(@args == 1) {
Branch: 2 branches
BranchTrueFalseTotal
if (@args == 1) { } 47 6 53
elsif (@args == 2) { } 6 0 6
225 47 my $arg = $args[0];
226 47 ▶ return %$arg if ref($arg) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg eq "HASH" 39 8 47
227 8 ▶ return (cb => $arg ) if ref($arg) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $arg eq "CODE" 1 7 8
228 7 return (value => $arg); # assume scalar
229 } elsif(@args == 2) {
230 6 ▶ carp 'Arg 1 must be hashref if passing 2 args to FormBuilder methods' if ref($args[0]) ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $args[0] ne "HASH" 0 6 6
231 6 ▶ carp 'Arg 2 must be coderef if passing 2 args to FormBuilder methods' if ref($args[1]) ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $args[1] ne "CODE" 0 6 6
232 6 return (%{$args[0]}, cb => $args[1]);
233 } else {
234 0 croak "Invalid options: @args";
235 }
236 }
237  
238 78 ▶sub _normalize_value {
Subroutine _normalize_value: called CC=6 SCAR=17.9
239 78 my ($self, $key, %opts) = @_;
240 78 ▶ my $cb = exists $opts{cb} ? $opts{cb} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'cb'} ? : 7 71 78
241  
242 78 my $return_value;
243 78 ▶ if($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 7 71 78
244 7 ▶ my $value = exists $opts{value} ? $opts{value} : $self->get_attribute_for_json($key);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'value'} ? : 4 3 7
245 7 ▶ $return_value = $cb->($self->has_custom_view ? ($self->view, $self, $value) : ($self, $value));
Branch: 1 branch
BranchTrueFalseTotal
$self->has_custom_view ? : 0 7 7
246 } else {
247 71 ▶ $return_value = exists $opts{value} ? $opts{value} : $self->get_attribute_for_json($key);
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'value'} ? : 27 44 71
248 }
249 78 return $return_value;
250 }
251  
252 # type handlers
253  
254 8 ▶sub value {
Subroutine value: called CC=3 SCAR=11.8
Pod documented
255 8 my ($self, $value) = @_;
256 8 ▶ $value = "$value" if blessed($value);
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($value) 8 0 8
257 8 ▶ if($self->has_index) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_index) { } 8 0 8
258 8 $self->current_data->[$self->index] = $value;
259 } else {
260 0 $self->current_data = $value;
261 }
262 8 return $self;
263 }
264  
265 48 ▶sub string {
Subroutine string: called CC=1 SCAR=0.0
Pod documented
266 48 my $self = shift;
267 48 my $key = shift;
268 48 my %opts = $self->_normalize_opts(@_);
269 48 my $value = $self->_normalize_value($key, %opts);
270 48 $self->set_current_data($key, $value, %opts);
271 48 return $self;
272 }
273  
274 9 ▶sub boolean {
Subroutine boolean: called CC=5 SCAR=16.1
Pod documented
275 9 my $self = shift;
276 9 my $key = shift;
277 9 my %opts = $self->_normalize_opts(@_);
278 9 my $raw_value = $self->_normalize_value($key, %opts);
279 9 ▶ $raw_value = 0 if !defined($raw_value) && $opts{coerce_undef};
Branch: 1 branch
BranchTrueFalseTotal
if not defined $raw_value and $opts{"coerce_undef"} 1 8 9
Condition100%3/3
not defined $raw_value and $opts{"coerce_undef"}
!ll&&!rl&&r
621
MC/DC100%2/2
not defined $raw_value and $opts{"coerce_undef"}
not defined $raw_value $opts{"coerce_undef"}
Truth table100%3/3
not(A) and B
A= not defined $raw_valueB= $opts{"coerce_undef"}
ABresult
0X0
100
111
280  
281 9 my $boolean_value = $raw_value;
282 9 ▶ if(defined $raw_value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $raw_value) 7 2 9
283 7 ▶ $boolean_value = $raw_value ?
Branch: 1 branch
BranchTrueFalseTotal
$raw_value ? : 5 2 7
284 $self->json_true :
285 $self->json_false;
286 }
287  
288 9 $self->set_current_data($key, $boolean_value, %opts);
289 9 return $self;
290 }
291  
292 21 ▶sub number {
Subroutine number: called CC=2 SCAR=6.9
Pod documented
293 21 my $self = shift;
294 21 my $key = shift;
295 21 my %opts = $self->_normalize_opts(@_);
296 21 my $raw_value = $self->_normalize_value($key, %opts);
297 21 ▶ my $num_value = defined($raw_value) ? 0+$raw_value : $raw_value;
Branch: 1 branch
BranchTrueFalseTotal
defined $raw_value ? : 17 4 21
298 21 $self->set_current_data($key, $num_value, %opts);
299 21 return $self;
300 }
301  
302 13 ▶sub object {
Subroutine object: called CC=7 SCAR=19.5
Pod documented
303 13 my $self = shift;
304 13 my $key = shift;
305 13 my $cb = pop;
306 13 my %opts = $self->_normalize_opts(@_);
307  
308 13 ▶ croak "You must provide a callback for '$key' to object" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 13 13
309
310 13 my $model;
311 13 ▶ if(blessed $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($key)) { } 2 11 13
312 2 $model = $key;
313 2 $key = $self->_model_name_from_object_or_class($model)->param_key;
314 } else {
315 11 $model = $self->get_attribute_for_json($key);
316 }
317  
318 13 $self->push_model($model);
319 13 $self->push_pointer($key, +{}, %opts);
320 13 ▶ $cb->($self->has_custom_view ? ($self->view, $self, $model) : ($self, $model));
Branch: 1 branch
BranchTrueFalseTotal
$self->has_custom_view ? : 1 12 13
321 13 $self->pop_model;
322 13 $self->pop_pointer;
323  
324 13 ▶ my $ns = exists($opts{namespace}) ? $opts{namespace} : $key;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'namespace'} ? : 4 9 13
325 13 ▶ delete $self->current_data->{$ns} if $opts{omit_empty} && !%{$self->current_data->{$ns}};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"omit_empty"} and not %{$self->current_data->{$ns};} 2 11 13
Condition66%2/3
$opts{"omit_empty"} and not %{$self->current_data->{$ns};}
!ll&&!rl&&r
1102
MC/DC50%1/2
$opts{"omit_empty"} and not %{$self->current_data->{$ns};}
$opts{"omit_empty"} not %{$self->current_data->{$ns};}
Truth table66%2/3
A and not(B)
A= $opts{"omit_empty"}B= not %{$self->current_data->{$ns};}
ABresult
0X0
100
111
326  
327  
328 13 return $self;
329 }
330  
331 1 ▶sub skip { return bless {}, 'Valiant::JSON::Util::Skip'}
Subroutine skip: called CC=1 SCAR=0.0
Pod documented
332  
333 13 ▶sub array {
Subroutine array: called CC=14 SCAR=26.5
Pod documented
334 13 my $self = shift;
335 13 my $key = shift;
336 13 my $cb = pop;
337  
338 13 ▶ croak "You must provide a callback for '$key' to array" unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 13 13
339  
340 13 my %opts = $self->_normalize_opts(@_);
341
342 13 my $collection;
343 13 ▶ if( ((ref($key)||'') eq 'ARRAY') || blessed($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $key || '') eq 'ARRAY' or builtin::blessed($key)) { } 6 7 13
Condition80%4/5
(ref $key || "") eq "ARRAY" or builtin::blessed($key)
l!l&&r!l&&!r
607
ref $key || ''
l!l
67
MC/DC50%1/2
(ref $key || "") eq "ARRAY" or builtin::blessed($key)
ref $key builtin::blessed($key)
Truth table66%2/3
A or B
A= ref $keyB= builtin::blessed($key)
ABresult
1X1
011
000
344 6 $collection = $key;
345 6 $key = $opts{namespace};
346 } else {
347 7 $collection = $self->get_attribute_for_json($key);
348 }
349
350 13 ▶ $collection = Valiant::HTML::Util::Collection->new(@$collection)
Branch: 1 branch
BranchTrueFalseTotal
if ref $collection eq "ARRAY" 13 0 13
351 if ref($collection) eq 'ARRAY';
352  
353 13 $self->push_pointer($key, [], %opts);
354 13 ▶ while(my $model = $collection->next) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $model = $collection->next) 32 13 45
355 32 $self->push_model($model);
356 32 ▶ my $return = $cb->($self->has_custom_view ? ($self->view, $self, $model) : ($self, $model));
Branch: 1 branch
BranchTrueFalseTotal
$self->has_custom_view ? : 2 30 32
357 32 $self->pop_model;
358 32 ▶ $self->inc_index unless ((ref($return)||'') eq 'Valiant::JSON::Util::Skip');
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $return || "") eq "Valiant::JSON::Util::Skip" 31 1 32
Condition100%2/2
ref $return || ''
l!l
266
MC/DC100%1/1
ref $return || ''
ref $return
Truth table100%2/2
A
A= ref $return
Aresult
11
00
359 }
360 13 $self->pop_pointer;
361 13 $self->clear_index;
362 13 ▶ $collection->reset if $collection->can('reset');
Branch: 1 branch
BranchTrueFalseTotal
if $collection->can("reset") 13 0 13
363  
364 13 ▶ my $ns = exists($opts{namespace}) ? $opts{namespace} : $key;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts{'namespace'} ? : 10 3 13
365 13 ▶ delete $self->current_data->{$ns} if $opts{omit_empty} && !@{$self->current_data->{$ns}};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"omit_empty"} and not @{$self->current_data->{$ns};} 3 10 13
Condition66%2/3
$opts{"omit_empty"} and not @{$self->current_data->{$ns};}
!ll&&!rl&&r
1003
MC/DC50%1/2
$opts{"omit_empty"} and not @{$self->current_data->{$ns};}
$opts{"omit_empty"} not @{$self->current_data->{$ns};}
Truth table66%2/3
A and not(B)
A= $opts{"omit_empty"}B= not @{$self->current_data->{$ns};}
ABresult
0X0
100
111
366  
367 13 return $self;
368 }
369  
370 2 ▶sub if {
Subroutine if: called CC=6 SCAR=19.9
Pod documented
371 2 my ($self, $cond, $cb) = @_;
372 2 ▶ croak 'You must provide a callback to if' unless ref($cb) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 0 2 2
373  
374 2 ▶ $cond = $cond->($self->has_custom_view ? ($self->view, $self) : ($self)) if ref($cond) eq 'CODE';
Branch: 2 branches
BranchTrueFalseTotal
if ref $cond eq "CODE" 0 2 2
$self->has_custom_view ? : 0 0 0
375 2 ▶ $cb->($self->has_custom_view ? ($self->view, $self) : $self) if $cond;
Branch: 2 branches
BranchTrueFalseTotal
if $cond 2 0 2
$self->has_custom_view ? : 1 1 2
376  
377 2 return $self;
378 }
379  
380 1 ▶sub with_model {
Subroutine with_model: called CC=2 SCAR=7.0
Pod documented
381 1 my ($self, $model, $cb) = @_;
382 1 $self->push_model($model);
383 1 ▶ $cb->($self->has_custom_view ? ($self->view, $self, $model) : ($self, $model));
Branch: 1 branch
BranchTrueFalseTotal
$self->has_custom_view ? : 0 1 1
384 1 $self->pop_model;
385 1 return $self;
386 }
387  
388 5 ▶sub errors {
Subroutine errors: called CC=3 SCAR=11.0
Pod documented
389 5 my $self = shift;
390 5 my @errors = $self->_errors_for($self->current_model, $self->namespace);
391 5 ▶ return $self unless scalar(@errors);
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @errors 2 3 5
392 3 ▶ $self->data_pointer unless $self->has_data_pointer;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_data_pointer 0 3 3
393 3 $self->data->{data}{errors} = \@errors;
394 3 return $self;
395 }
396  
397 5 ▶sub _errors_for {
Subroutine _errors_for: called CC=10 SCAR=23.4
398 5 my ($self, $model, $ns) = @_;
399 5 ▶ unless($model->can('errors')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($model->can("errors")) 1 4 5
400 1 carp "model $model does not support the errors API";
401 1 return ();
402 }
403  
404 4 ▶ $ns ||= $model->model_name->param_key if $model->can('model_name');
Branch: 1 branch
BranchTrueFalseTotal
if $model->can("model_name") 4 0 4
Condition33%1/3
$ns ||= $model->model_name->param_key
l!l&&r!l&&!r
400
MC/DC0%0/2
$ns ||= $model->model_name->param_key
$ns $model->model_name->param_key
Truth table33%1/3
A ||= B
A= $nsB= $model->model_name->param_key
ABresult
1X1
011
000
405  
406 4 my $content_type = $self->content_type;
407 4 my $cb;
408 4 ▶ if(
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type eq 'application/x-www-form-urlencoded' or $content_type eq 'multipart/form-data') { } 1 3 4
Condition66%2/3
$content_type eq "application/x-www-form-urlencoded" or $content_type eq "multipart/form-data"
l!l&&r!l&&!r
103
MC/DC50%1/2
$content_type eq "application/x-www-form-urlencoded" or $content_type eq "multipart/form-data"
$content_type eq "application/x-www-form-urlencoded" $content_type eq "multipart/form-data"
Truth table66%2/3
A or B
A= $content_type eq "application/x-www-form-urlencoded"B= $content_type eq "multipart/form-data"
ABresult
1X1
011
000
409 ($content_type eq 'application/x-www-form-urlencoded')
410 ||
411 ($content_type eq 'multipart/form-data')
412 ) {
413 2 ▶ $cb = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
414 2 my $field = shift;
415 2 return +{ parameter => $field };
416 1 };
417 } else {
418 # Anything that isn't a classic form post gets JSON pointer style sources
419 4 ▶ $cb = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
420 4 my $field = shift;
421 4 $field =~ s/\./\//g;
422 4 $field =~ s/\[/\//g;
423 4 $field =~ s/\]//g;
424 4 return +{ pointer => $field };
425 3 };
426 }
427  
428 4 my %errors = $model->errors->to_hash(1);
429 4 my @errors = ();
430 4 foreach my $field (sort keys %errors) {
431 3 ▶ my @error_messages = @{ $errors{$field} || [] };
Condition50%1/2
$errors{$field} || []
l!l
30
MC/DC0%0/1
$errors{$field} || []
$errors{$field}
Truth table50%1/2
A
A= $errors{$field}
Aresult
11
00
432 3 foreach my $error_message (@error_messages) {
433 6 my $info = +{ detail => $error_message };
434 6 ▶ if($field eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($field eq '*') { } 0 6 6
435 0 $info->{source} = $cb->("${ns}");
436 } else {
437 6 $info->{source} = $cb->("${ns}.${field}");
438 }
439 6 push @errors, $info;
440 }
441 }
442 4 return @errors;
443 }
444  
445 4 1;
446  
447 =head1 NAME
448  
449 Valiant::JSON::JSONBuilder - Wraps a model with a JSON builder
450  
451 =head1 SYNOPSIS
452  
453 Given an object defined like this:
454  
455 package Local::Test::User;
456  
457 use Moo;
458  
459 has username => (is=>'ro');
460 has active => (is=>'ro');
461 has age => (is=>'ro');
462  
463 Create an instance of the object and then use the JSONBuilder to render it:
464  
465 my $user = Local::Test::User->new(
466 username => 'bob',
467 active => 1,
468 age => 42,
469 );
470  
471 my $jb = Valiant::JSON::JSONBuilder->new(model=>$user);
472 my $json = $jb->string('username')
473 ->boolean('active')
474 ->number('age')
475 ->render_json;
476  
477 say $json;
478  
479 Response is:
480  
481 "local_test_user" : {
482 "username" : "bob",
483 "age" : 42,
484 "active" : true
485 }
486  
487 You can control value the top level field of the rendered JSON or remove it:
488  
489 my $jb = Valiant::JSON::JSONBuilder->new(model=>$user, namespace=>'');
490 my $json = $jb->string('username')
491 ->boolean('active')
492 ->number('age')
493 ->render_json;
494  
495 say $json;
496  
497 Response is:
498  
499 {
500 "username" : "bob",
501 "age" : 42,
502 "active" : true
503 }
504  
505 It can also work with a view object, see below for details.
506  
507 =head1 DESCRIPTION
508  
509 Serializing an object into a JSON string is a common task. This module
510 provides a simple way to do that using a JSON builder pattern. It is
511 intended to be used with L<Valiant> but can be used with any object.
512  
513 There's tons of different patterns for serializing objects into JSON. One common
514 approach is to add a C<TO_JSON> method to your object. This is a fine approach
515 but it has a few drawbacks the biggest of which is that it forces you into a
516 single serialization pattern for the object. This might be ok for using serialization
517 for saving an object to a database but it is less than ideal for rendering an object
518 into a JSON response for an API. For example you might want to render the object
519 differently depending on the user's role or depending on the API version, or for any
520 other reason I'm sure you can think of.
521  
522 Another approach is to just write some bespoke code to turn your object into a perl
523 data structure suitable for passing to a JSON encoder such as L<JSON::MaybeXS>. This
524 is also a fine approach but it can be a bit tedious to write and maintain. It's also
525 easy to mess up handling of nested objects and arrays or in situations when you want to make
526 sure a scalar is coerced into a string or a number. The purpose behind this module is
527 to encapsulate some basic patterns for serializing objects into JSON and to make it easy
528 to extend and customize. Although this works well with simple cases I think it really
529 shines when you have a complex object with nested objects and arrays contained within it
530 as well as when you need to inject extra fields and values into the JSON response that are
531 not part of the object itself. You can even include other objects in the response and
532 the API includes some basic conditional logic to smooth over very complex cases.
533  
534 =head1 ATTRIBUTES
535  
536 This class defines the follwoing attributes.
537  
538 =head2 model
539  
540 This is the object to be serialized. It can be any object but it has some extensions to play
541 nice with objects that are using L<Valiant> for validation.
542  
543 This value should be either a blessed object or the scalar name of the object which refers to
544 an attribute on the view object (which must then be provided, see below)
545  
546 =head2 namespace
547  
548 This is the top level field name to use when rendering the object. If not specified it will
549 use the C<model_name> of the object if it has one. If the object does not have a C<model_name>
550 then it will use the class name of the object. If you want to render the object without a
551 top level field then set this to an empty string.
552  
553 =head2 content_type
554  
555 The content type of the request this JSON is a response to. This is used by L</errors> to
556 choose the style of its error source references: C<application/x-www-form-urlencoded> and
557 C<multipart/form-data> get C<parameter> style sources, anything else (including the default
558 of C<application/json>) gets JSON pointer style sources. If you are using this builder
559 inside a web framework you can pass the request content type here.
560  
561 =head2 view
562  
563 This is an optional view object. If provided we can use view attributes to provide models.
564  
565 =head2 json_args
566  
567 This is an optional hashref of options which is passed to the L<JSON::MaybeXS> encoder.
568  
569 =head1 METHODS
570  
571 This class defines the following methods.
572  
573 =head2 reset
574  
575 Clears any previously defined JSON field and value definitions but preserves the model and related
576 attributes. Useful if you want to reuse the same builder object to render representations of the
577 same model, but I mostly used it for testing and saw no reason to mark it private.
578  
579 =head2 json_true
580  
581 =head2 json_false
582  
583 Returns an object representing a JSON boolean value for serialization. Useful since Perl doesn't
584 have a native boolean type.
585  
586 =head2 render_perl
587  
588 Returns a perl data structure representing the current defined JSON structure. Useful for testing
589 but I see no reason to mark it private
590  
591 =head2 render_json
592  
593 A JSON encoded string representing the current defined JSON structure.
594  
595 =head2 string
596  
597 Renders an object attribute as a string.
598  
599 $jb->string('username', \%options);
600  
601 The options hashref is optional and can contain the following keys:
602  
603 =over 4
604  
605 =item name
606  
607 The name of the field to render. Generally this is an attribute on the model object (or the
608 model has the C<get_attribute_for_json> method defined). You can use a non attribute value
609 here if you need to inject a field that isn't in the model (for example a CSRF token) but
610 if you do so you must prove a C<value> option.
611  
612 =item value
613  
614 If provided use this value instead of the value of the attribute.
615  
616 =item omit_undef
617  
618 If true then the field will not be rendered if the value is undefined.
619  
620 =item omit_empty
621  
622 If true then the field will not be rendered if the value is an empty string. For this to work
623 the model should support C<has_attribute_for_json> or provide a method called C<has_$attribute>
624  
625 =back
626  
627 =head2 number
628  
629 Same as L</string> but coerces the value into a number instead. Same options supported
630  
631 =head2 boolean
632  
633 Same as L</string> but coerces the value into a boolean instead. Same options supported.
634 Coerces into s JSON boolean value (true/false) not a Perl boolean value (1/0). See L</json_true>
635 and L</json_false>.
636  
637 Supports one additional option: C<coerce_undef> which if true will coerce an undefined value
638 into a false value. By default an undefined value will be rendered as a JSON null value unless
639 C<omit_undef> is true. Same thing if the value is not present, that will render as null unless
640 C<omit_empty> is true.
641  
642 =head2 value
643  
644 This returns the value of the current field directly. Useful when you want to render a simple
645 array of values
646  
647 package Local::Test::List;
648  
649 use Moo;
650  
651 has numbers => (is=>'ro');
652  
653 my $list_of_numbers = Local::Test::List->new(numbers=>[1,2,3]);
654 my $jb = Valiant::JSON::JSONBuilder->new(model=>$list_of_numbers);
655 my $json = $jb->array([1,2,3], {namespace=>'numbers'}, sub {
656 my ($jb, $item) = @_;
657 $jb->value($item);
658 })->render_json;
659  
660 response is:
661  
662 {
663 "local_test_list" : {
664 "numbers" : [
665 "1",
666 "2",
667 "3"
668 ]
669 }
670 }
671  
672 =head2 object
673  
674 $jb->object('profile', sub {
675 my ($jb, $profile) = @_;
676 $jb->string('address')
677 ->string('city');
678 });
679  
680 Renders a nested JSON object. The first argument is either an attribute name (whose
681 value must be an object) or a blessed object directly (in which case the field name is
682 derived from its C<model_name>). The last argument is a callback which receives the
683 builder and the nested model (or C<< ($view, $jb, $model) >> when the builder has a
684 custom view) and defines the nested fields; inside the callback the nested model is the
685 current model.
686  
687 Options may be passed as a hashref before the callback: C<namespace> to override the
688 field name used, and C<omit_empty> to drop the field entirely if the callback added
689 nothing to it.
690  
691 =head2 array
692  
693 $jb->array('credit_cards', sub {
694 my ($jb, $card) = @_;
695 $jb->number('id')
696 ->string('card_number');
697 });
698  
699 Renders a JSON array with one entry per item. The first argument is an attribute name
700 (whose value must be an arrayref or a collection object responding to C<next>), a raw
701 arrayref (in which case you must pass a C<namespace> option to name the field), or a
702 collection object. The last argument is a callback run once per item, receiving the
703 builder and the item (or C<< ($view, $jb, $item) >> with a custom view); inside the
704 callback the item is the current model.
705  
706 Return L</skip> from the callback to exclude the current item from the output. Options
707 may be passed as a hashref before the callback: C<namespace> to override the field name
708 and C<omit_empty> to drop the field entirely when the resulting array is empty.
709  
710 =head2 skip
711  
712 $jb->array('users', sub {
713 my ($jb, $user) = @_;
714 return $jb->skip if $user->is_hidden;
715 $jb->string('username');
716 });
717  
718 Returns a sentinel value which, when returned from an L</array> callback, excludes the
719 current item from the rendered array.
720  
721 =head2 if
722  
723 $jb->if($boolean, sub { my ($jb) = @_; ... });
724 $jb->if(sub { ... }, sub { my ($jb) = @_; ... });
725  
726 Conditionally add to the JSON. The first argument is a boolean or a coderef evaluated
727 to one; when true the callback runs (receiving the builder, or C<< ($view, $jb) >> with
728 a custom view).
729  
730 =head2 with_model
731  
732 $jb->with_model($other_model, sub {
733 my ($jb, $model) = @_;
734 $jb->string('address');
735 });
736  
737 Runs the callback with the given model temporarily set as the current model, without
738 opening a nested JSON object the way L</object> does. Fields added inside the callback
739 land at the current level but read their values from C<$other_model>.
740  
741 =head2 errors
742  
743 $jb->string('username')->errors;
744  
745 If the current model has validation errors (it supports the errors API of
746 L<Valiant::Validates>) this adds an C<errors> field at the top level of the rendered
747 structure, containing one entry per validation message in the style of the JSON:API
748 error format:
749  
750 {
751 "local_test_user" : { "username" : "" },
752 "errors" : [
753 {
754 "detail" : "Username can't be blank",
755 "source" : { "pointer" : "local_test_user/username" }
756 }
757 ]
758 }
759  
760 Each entry has a C<detail> (the human readable message) and a C<source> which locates the
761 failing input: a JSON pointer style path by default, or a C<parameter> name when
762 L</content_type> is a classic HTML form type. Fields are emitted in sorted order.
763  
764 If the model has no errors this is a no op; if the model doesn't support the errors API
765 it warns and is a no op.
766  
767 =head1 METHODS FOR OBJECTS
768  
769 Although not required, if the model object provides these methods they can be used to customize
770 how we render the object.
771  
772 =head2 get_attribute_for_json
773  
774 When requesting that a model provide a value for an attribute, if this method is defined it will
775 be called with the attribute name and be expected to return the value to be used for the attribute.
776 this can be useful if you want to do some custom processing on the value before it is rendered or
777 if you want to create virtual attributs jsut for JSON.
778  
779 If the method doesn't exist we expect to find a method on the object that matches the attribute name.
780  
781 =head2 has_attribute_for_json
782  
783 When requesting that a model provide a value for an attribute, if this method is defined it will
784 be called with the attribute name and be expected to return a boolean value indicating if the attributes
785 exists or not. If this method is not provided we expect to find a method on the object that matches
786 "has_$attribute_name", which is the common convention on L<Moo> and L<Moose> objects. If neither method
787 exists you will get a runtime error.
788  
789 This method is called if you use the C<omit_empty> option on a builder method so you need to remember to
790 provide the correct model API to support checking an attribute exists.
791  
792 =head1 USING WITH A VIEW
793  
794 If you pass a C<view> object at construction time then every builder callback (for
795 L</object>, L</array>, L</if>, L</with_model> and friends) receives the view as its
796 first argument, followed by the builder and any model or item:
797  
798 my $jb = Valiant::JSON::JSONBuilder->new(model=>$user, view=>$view);
799 $jb->object('profile', sub {
800 my ($view, $jb, $profile) = @_;
801 ...
802 });
803  
804 Additionally, when you have a view you can pass a string model I<name> instead of a
805 model object at construction: the model is then looked up on the view, either via a
806 C<get_model_for_json($name)> method if the view provides one, or by calling the method
807 of that name on the view. This is aimed at web framework view classes (for example the
808 Catalyst views in the C<Catalyst-View-Valiant> distribution) where the view already
809 holds the models being rendered.
810  
811 =head1 SEE ALSO
812
813 L<Valiant>, L<JSON::MaybeXS>
814  
815 =head1 AUTHOR
816
817 See L<Valiant>
818  
819 =head1 COPYRIGHT & LICENSE
820
821 See L<Valiant>
822  
823 =cut
« Valiant/Util.pm ↑ Summary Valiant/Filterable.pm »