Valiant/JSON/JSONBuilder.pm

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