blib/lib/JSONP.pm

filter: Statementstmt 31.0% 146 / 470 Branchbran 18.1% 44 / 242 Conditioncond 17.9% 30 / 167 MC/DCmcdc 8.5% 7 / 82 Subroutinesub 53.4% 31 / 58 Podpod 96.0% 24 / 25 totaltotal 27.0% 282 / 1044 CC 199 SCAR 67.4
CC
199
Cov
25%
run
3532.5
_merge
110.0
sendblob
42.0
CRAP 845.0
↑ Summary
1 package JSONP;
2 # some older 5.8.x perl versions on exotic platforms don't get the v5.10 syntax
3 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Time::HiRes qw(gettimeofday);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use File::Temp qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use File::Path;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Cwd qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use Scalar::Util qw(reftype blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use CGI qw();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Digest::SHA;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Want;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 use overload
19 fallback => 0,
20 7 ▶ 'eq' => sub {_compare(@_)},
Subroutine __ANON__: called CC=1 SCAR=0.0
21 5 ▶ 'ne' => sub {! _compare(@_)},
Subroutine __ANON__: called CC=1 SCAR=0.0
22 'bool' => sub {
23 0 ▶ my $self = shift;
Subroutine __ANON__: not called CC=2 SCAR=17.9
24 0 ▶ ! ($self->errors && scalar @{$self->errors});
Condition0%0/2
$self->errors && scalar @{$self->errors;}
!ll
00
MC/DC0%0/1
$self->errors && scalar @{$self->errors;}
$self->errors
Truth table0%0/2
A
A= $self->errors
Aresult
00
11
25 1 ▶ };
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 sub _compare {
28 12 ▶ my ($self, $other, $swap) = @_;
Subroutine _compare: called CC=8 SCAR=20.9
29 12 ▶ return 0 unless defined $other;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $other 2 10 12
30 10 my $reftype_self = reftype $self;
31 10 my $reftype_other = reftype $other;
32 10 ▶ return 0 if defined $reftype_other and $reftype_self ne $reftype_other;
Branch: 1 branch
BranchTrueFalseTotal
if defined $reftype_other and $reftype_self ne $reftype_other 0 10 10
Condition66%2/3
defined $reftype_other and $reftype_self ne $reftype_other
!ll&&!rl&&r
460
MC/DC0%0/2
defined $reftype_other and $reftype_self ne $reftype_other
defined $reftype_other $reftype_self ne $reftype_other
Truth table66%2/3
A and B
A= defined $reftype_otherB= $reftype_self ne $reftype_other
ABresult
0X0
100
111
33 10 my $j = JSON->new->canonical;
34 10 ▶ unless ($reftype_other) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($reftype_other) 4 6 10
35 4 eval{
36 4 local $SIG{'__DIE__'};
37 4 $other = JSON->new->decode($other);
38 };
39 4 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 2 4
40 }
41  
42 8 my $canonother;
43 8 ▶ if (blessed $other and $other->isa('JSONP')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($other) and $other->isa('JSONP')) { } 2 6 8
Condition66%2/3
builtin::blessed($other) and $other->isa("JSONP")
!ll&&!rl&&r
602
MC/DC50%1/2
builtin::blessed($other) and $other->isa("JSONP")
builtin::blessed($other) $other->isa("JSONP")
Truth table66%2/3
A and B
A= builtin::blessed($other)B= $other->isa("JSONP")
ABresult
0X0
100
111
44 2 $canonother = $other->serialize(0, 1);
45 } else {
46 6 $canonother = $j->encode($other);
47 }
48  
49 8 my $canonself = $self->serialize(0, 1);
50 8 return $canonself eq $canonother;
51 }
52  
53 1 our $VERSION = '2.24';
54  
55 =encoding utf8
56  
57 =head1 NAME
58  
59 JSONP - a module to quickly build JSON/JSONP web services, providing also some syntactic sugar acting a bit like a sort of DSL (domain specific language) for JSON.
60  
61 =head1 SYNOPSIS
62  
63 =over 2
64  
65 =item * under CGI environment:
66  
67 You can pass the name of instance variable, skipping the I<-E<gt>new> call.
68 If you prefer, you can use I<-E<gt>new> just passing nothing in I<use>.
69  
70 use JSONP 'jsonp';
71 $jsonp->run;
72  
73 ...
74  
75 sub yoursubname
76 {
77 $j->table->fields = $sh->{NAME};
78 $j->table->data = $sh->fetchall_arrayref;
79 }
80  
81 OR
82  
83 use JSONP;
84  
85 my $j = JSONP->new;
86 $j->run;
87  
88 ...
89  
90 sub yoursubname
91 {
92 $j->table->fields = $sh->{NAME};
93 $j->table->data = $sh->fetchall_arrayref;
94 }
95  
96 =item * under mod_perl:
97  
98 You must declare the instance variable, remember to use I<local our>.
99  
100 use JSONP;
101 local our $j = JSONP->new;
102 $j->run;
103  
104 ...
105  
106 sub yoursubname
107 {
108 my $namedparam = $j->params->namedparam;
109 $j->table->fields = $sh->{NAME};
110 $j->table->data = $sh->fetchall_arrayref;
111 }
112  
113 option setting methods allow for chained calls:
114  
115 use JSONP;
116 local our $j = JSONP->new;
117 $j->aaa('your_session_sub')->login('your_login_sub')->debug->insecure->run;
118  
119 ...
120  
121 sub yoursubname
122 {
123 my $namedparam = $j->params->namedparam;
124 $j->table->fields = $sh->{NAME};
125 $j->table->data = $sh->fetchall_arrayref;
126 }
127  
128 just make sure I<run> it is the last element in chain.
129  
130 =back
131  
132 the module will call automatically the sub which name is specified in the req parameter of GET/POST request. JSONP will check if the sub exists in current script namespace by looking in typeglob and only in that case the sub will be called. The built-in policy about function names requires also a name starting by a lowercase letter, followed by up to 63 characters chosen between ASCII letters, numbers, and underscores. Since this module is intended to be used by AJAX calls, this will spare you to define routes and mappings between requests and back end code. In your subroutines you will therefore add all the data you want to the JSON/JSONP object instance in form of hashmap of any deep and complexity, JSONP will return that data automatically as JSON object with/without padding (by using the function name passed as 'callback' in GET/POST request, or using simply 'callback' as default) to the calling javascript. The supplied callback name wanted from calling javascript must follow same naming conventions as function names above. Please note that I<params> and I<session> keys on top of JSONP object hierarchy are reserved. See also "I<notation convenience features>" paragraph at the end of the POD.
133 The jQuery call:
134  
135 // note that jQuery will automatically chose a non-clashing callback name when you insert callback=? in request
136 $.getJSON(yourwebserverhost + '?req=yoursubname&firstparam=firstvalue&...&callback=?', function(data){
137 //your callback code
138 });
139  
140 processed by JSONP, will execute I<yoursubname> in your script if it exists, otherwise will return a JSONP codified error. The default error object returned by this module in its root level has a boolean "error" flag and an "errors" array where you can put a list of your customized errors. The structure of the elements of the array is of course free so you can adapt it to your needs and frameworks.
141  
142 you can autovivify the response hash omiting braces
143  
144 $jsonp->firstlevelhashvalue = 'I am a first level hash value';
145 $jsonp->first->second = 'I am a second level hash value';
146  
147 you can then access hash values either with or without braces notation
148  
149 $jsonp->firstlevelhashvalue = 5;
150 print $jsonp->firstlevelhashvalue; # will print 5
151  
152 it is equivalent to:
153  
154 $jsonp->{firstlevelhashvalue} = 5;
155 print $jsonp->{firstlevelhashvalue};
156  
157 you can even build a tree:
158  
159 $jsonp->first->second = 'hello!';
160 print $jsonp->first->second; # will print "hello!"
161  
162 it is the same as:
163  
164 $jsonp->{first}->{second} = 'hello!';
165 print $jsonp->{first}->{second};
166  
167 or (the perl "array rule"):
168  
169 $jsonp->{first}{second} = 'hello!';
170 print $jsonp->{first}{second};
171  
172 or even (deference ref):
173  
174 $$jsonp{first}{second} = 'hello!';
175 print $$jsonp{first}{second};
176  
177 you can insert hashes at any level of structure and they will become callable with the built-in convenience shortcut:
178  
179 my $obj = {a => 1, b => 2};
180 $jsonp->first->second = $obj;
181 print $jsonp->first->second->b; # will print 2
182 $jsonp->first->second->b = 3;
183 print $jsonp->first->second->b; # will print 3
184  
185 you can insert also array at any level of structure and the nodes (hashrefs) within resulting structure will become callable with the built-in convenience shortcut. You will need to call C<-E<gt>[index]> in order to access them, though:
186  
187 my $ary = [{a => 1}, 2];
188 $jsonp->first->second = $ary;
189 print $jsonp->first->second->[1]; # will print 2
190 print $jsonp->first->second->[0]->a; # will print 1
191 $jsonp->first->second->[0]->a = 9;
192 print $jsonp->first->second->[0]->a; # will print 9 now
193  
194 you can almost freely interleave above listed styles in order to access to elements of JSONP object. As usual, respect I<_private> variables if you don't know what you are doing. One value-leaf/object-node element set by the convenience notation shortcut will be read by normal hash access syntax. You can delete elements from the hash tree, though it is not supported via the convenience notation. You can use it, but the last node has to be referenced via braces notation:
195  
196 my $j = JSONP->new;
197 $j->firstnode->a = 5;
198 $j->firstnode->b = 9;
199 $j->secondnode->thirdnode->a = 7;
200 delete $j->secondnode->{thirdnode}; # will delete thirdnode as expected in hash structures.
201  
202 you can compare the JSONP object with another Perl data structure or JSON string via C<eq> and C<ne> overloaded operators, it will return true if the two operands will result in same JSON structure and values:
203  
204 my $j = JSONP->new(
205 {
206 firstkey => 5,
207 secondkey => [1, 2, 3],
208 thirdkey => {
209 nested => \1
210 }
211 }
212 );
213  
214 my $json = '
215 {
216 "thirdkey": {"nested": true},
217 "firstkey": 5,
218 "secondkey": [1, 2, 3]
219 }
220 ';
221  
222 say $j eq $json ? 'the same' : 'different'; # will print 'the same'
223 say $j ne $json ? 'different' : 'the same'; # will print 'the same'
224 say $j eq 'a random string, not a valid JSON' ? 'the same' : 'different'; # will print 'different'
225 say $j eq '{"akey": "something"}' ? 'the same' : 'different'; # will print 'different'
226  
227 TODO: will investigate if possible to implement deletion using exclusively the convenience notation feature.
228  
229 IMPORTANT NOTE: while using the convenience notation without braces, if you autovivify a hierarchy without assigning anything to the last item, or assigning it an B<I<undef>>ined value, JSONP will assign to the last element a zero string ( '' ). Since it evaluates to false in a boolean context and can be safely catenated to other strings without causing runtime errors you can avoid several I<exists> checks without the risk to incur in runtime errors. The only dangerous tree traversal can occur if you try to treat an object node as an array node, or vice versa.
230  
231 IMPORTANT NOTE 2: remember that all the method names of the module cannot be used as key names via convenience notation feature, at any level of the response tree. You can set such key names anyway by using the braces notation. To retrieve their value, you will need to use the brace notation for the node that has the key equal to a native method name of this very module. It is advisable to assign the branch that contains them to an higher level node:
232  
233 my $j = JSONP->new;
234 $j->firstnode = 5;
235 my $branch = {};
236 $branch->{debug} = 0; # debug is a native method name
237 $branch->{serialize} = 1; # serialize is a native method name
238 $j->secondnode = $branch; # $branch structure will be grafted and relative nodes blessed accordingly
239 say $j->secondnode->{serialize}; # will print 1
240  
241 IMPORTANT NOTE 3: deserialized booleans from JSON are turned into referenes to scalars by JSON module, to say JSON I<true> will turn into a Perl I<\1> and JSON I<false> will turn into a Perl I<\0>. JSONP module detects boolen context so when you try to evaluate one of these values in a boolean context it correctly returns the actual boolean value hold by the leaf instead of the reference (that would always evaluate to I<true> even for I<\0>), to say will dereference I<\0> and I<\1> in order to return I<0> and I<1> respectively.
242  
243 $j->graft('testbool', q|{"true": true, "false":false}|);
244 say $j->testbool->true;
245 say $j->testbool->false;
246 say !! $j->testbool->true;
247 say !! $j->testbool->false;
248  
249 NOTE: in order to get a "pretty print" via serialize method you will need to either call I<debug> or I<pretty> methods before serialize, use I<pretty> if you want to serialize a deeper branch than the root one. If your JSONP object/branch is an ARRAY object the internal I<_pretty> member that stores the related setting for I<serialize> in the object branch cannot exist and hence cannot be set/used, to circumvent this inconvenience you can pass a true value to I<serialize>:
250  
251 my $j = JSONP->new->debug;
252 $j->firstnode->a = 5;
253 $j->firstnode->b = 9;
254 $j->secondnode->thirdnode->a = 7;
255 my $pretty = $j->serialize; # will get a pretty print
256 my $deepser = $j->firstnode->serialize; # won't get a pretty print, because deeper than root
257 my $prettydeeper = $j->firstnode->pretty->serialize; # will get a pretty print, because we called I<pretty> first
258  
259 my $j = JSONP->new(['one', 'two', 'three']);
260 $j->serialize(1); # will get a pretty print
261 $j->serialize; # will get a normal print
262 $j->pretty->serialize; # ->pretty call will be ignored cause $j is an array, you will get a normal print
263  
264 =head1 DESCRIPTION
265  
266 The purpose of JSONP is to give an easy and fast way to build JSON-only web services that can be used even from a different domain from which one they are hosted on. It is supplied only the object interface: this module does not export any symbol, apart the optional pointer to its own instance in the CGI environment (not possible in mod_perl environment).
267 Once you have the instance of JSONP, you can build a response hash tree, containing whatever data structure, that will be automatically sent back as JSON object to the calling page. The built-in automatic cookie session keeping uses a secure SHA256 to build the session key. The related cookie is HttpOnly, Secure (only SSL) and with path set way down the one of current script (keep the authentication script in the root of your scripts path to share session among all scripts). For high trusted intranet environments a method to disable the Secure flag has been supplied. The automatically built cookie key will be long exactly 64 chars (hex format).
268 You can retrieve parameters supplied from browser either via GET, POST, PUT, or DELETE by accessing the reserved I<params> key of JSONP object. For example the value of a parameter named I<test> will be accessed via $j->params->test. In case of POSTs or PUTs of application/json requests (JSONP application/javascript requests are always loaded as GETs) the JSONP module will transparently detect them and populate the I<params> key with the deserialization of posted JSON, note that in this case the JSON being P(OS|U)Ted must be an object and not an array, having a I<req> param key on the first level of the structure in order to point out the corresponding function to be invoked.
269 You have to provide the string name or sub ref (the module accepts either way) of your own I<aaa> and I<login> functions. The AAA (aaa) function will get called upon every request with the session key (retrieved from session cookie or newly created for brand new sessions) as argument. That way you will be free to implement routines for authentication, authorization, access, and session tracking that most suit your needs, together with rules for user/groups to access the methods you expose. Your AAA function must return the session string (if you previously saved it, read on) if a valid session exists under the given key. A return value evaluated as false by perl will result in a 'forbidden' response (you can add as much errors as you want in the I<errors> array of response object). B<Be sure you return a false value if the user is not authenticated!> otherwise you will give access to all users. If you want you can check the invoked method under the req parameter (see query method) in order to implement your own access policies. B<If> the request has been B<a POST or PUT> (B<but not a GET>)The AAA function will be called a second time just before the response to client will be sent out, the module checks for changes in session by concurrent requests that would have executed in meanwhile, and merges their changes with current one by a smart recursive data structure merge routine. Then it will call the AAA function again with the session key as first argument, and a serialized string of the B<session> branch as second (as you would have modified it inside your called function). This way if your AAA function gets called with only one paramenter it is the begin of the request cycle, and you have to retrieve and check the session saved in your storage of chose (memcached, database, whatever), if it gets called with two arguments you can save the updated session object (already serialized as JSON) to the storage under the given key. The B<session> key of JSONP object will be reserved for session tracking, everything you will save in that branch will be passed serialized to your AAA function right before the response to client. It will be also populated after the serialized string you will return from your AAA function at the beginning of the request cycle. The login function will get called with the current session key (from cookie or newly created) as parameter, you can retrieve the username and password passed by the query method, as all other parameters. This way you will be free to give whatever name you like to those two parameters. Return the outcome of login attempt in order to pass back to login javascript call the state of authentication. Whatever value that evaluates to true will be seen as "authentication ok", whatever value that Perl evaluates to false will be seen as "authentication failed". Subsequent calls (after authentication) will track the authentication status by mean of the session string you return from AAA function.
270 If you need to add a method/call/feature to your application you have only to add a sub with same name you will pass under I<req> parameter from frontend.
271  
272 =head2 METHODS
273  
274 =cut
275  
276 sub import {
277 1 ▶ my ($self, $name) = @_;
Subroutine import: called CC=4 SCAR=17.9
278 1 ▶ return if $ENV{MOD_PERL};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"MOD_PERL"} 0 1 1
279 1 ▶ return unless $name;
Branch: 1 branch
BranchTrueFalseTotal
unless $name 1 0 1
280 0 ▶ die 'not valid variable name' unless $name =~ /^[a-z][0-9a-zA-Z_]{0,63}$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /^[a-z][0-9a-zA-Z_]{0,63}$/ 0 0 0
281 0 my $symbol = caller() . '::' . $name;
282 {
283 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
284 0 *$symbol = \JSONP->new;
285 }
286 }
287  
288 =head3 new
289  
290 class constructor. The options have to be set by calling correspondant methods (see below). You can pass a Perl object reference (hash or array) or a JSON string to the constructor, and it will populate automatically the objext, note that when you are using the object as a manager for a web service, <Bit must be an hash>.
291  
292 my $h = {
293 a => 1,
294 b => 2
295 }:
296 my $j = JSONP->new($h);
297 say $j->serialize;
298  
299 my $a = ['a', 'b', 'c'];
300 my $j = JSONP->new($a);
301 say $j->serialize;
302  
303 my $json = '{"a" : 1, "b" : 2}';
304 my $j = JSONP->new($json);
305 say $j->serialize;
306  
307 =cut
308  
309 sub new {
310 4 ▶ my ($class, $json) = @_;
Subroutine new: called CC=7 SCAR=29.6
Pod documented
311  
312 4 ▶ return bless {}, $class unless defined $json;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json 1 3 4
313  
314 3 ▶ my $type = reftype($json) // '';
Condition50%1/2
builtin::reftype($json) // ""
l!l
30
MC/DC0%0/1
builtin::reftype($json) // ""
builtin::reftype($json)
Truth table50%1/2
A
A= builtin::reftype($json)
Aresult
11
00
315 3 ▶ if ($type eq 'HASH' || $type eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "HASH" or $type eq "ARRAY") 3 0 3
Condition33%1/3
$type eq "HASH" or $type eq "ARRAY"
l!l&&r!l&&!r
300
MC/DC0%0/2
$type eq "HASH" or $type eq "ARRAY"
$type eq "HASH" $type eq "ARRAY"
Truth table33%1/3
A or B
A= $type eq "HASH"B= $type eq "ARRAY"
ABresult
1X1
011
000
316 # shallow blessing to avoid constructor overhead on large data structures
317 # on-fly blessing is performed on dynamic traversal in AUTOLOAD and loop
318 3 return bless $json, $class;
319 }
320  
321 0 ▶ if ($type eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "") 0 0 0
322 0 eval{
323 0 local $SIG{'__DIE__'};
324 0 $json = JSON->new->decode($json);
325 };
326  
327 0 ▶ unless($@) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($@) 0 0 0
328 # shallow blessing to avoid constructor overhead on large data structures
329 # on-fly blessing is performed on dynamic traversal in AUTOLOAD and loop
330 0 return bless $json, $class;
331 }
332 }
333  
334 0 my $self = bless {}, $class;
335 0 $self->raiseError('incorrect argument (JSON string or Perl data structure) passed to JSONP constructor');
336 0 $self;
337 }
338  
339 =head3 run
340  
341 executes the subroutine specified by req paramenter, if it exists, and returns the JSON output object to the calling browser. This have to be the last method called from JSONP object, because it will call the requested function and return the set object as JSON one.
342  
343 =cut
344  
345 sub _auth {
346 0 ▶ my ($self, $sid, $session) = @_;
Subroutine _auth: not called CC=3 SCAR=24.8
347 0 my $authenticated = eval {
348 0 local $SIG{'__DIE__'};
349 0 $self->{_aaa_sub}->($sid, $session);
350 };
351  
352 0 ▶ if($@){
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
353 0 ▶ $self->{eval} = $@ if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 0 0
354 0 $self->raiseError('unclassified error');
355 0 $authenticated = 0;
356 }
357  
358 0 $authenticated;
359 }
360  
361 sub run {
362 0 ▶ my $self = shift;
Subroutine run: not called CC=60 SCAR=81.7
Pod documented
363 0 $self->{_is_root_element} = 1;
364 0 ▶ return $self unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
365 0 $self->{_authenticated} = 0;
366 0 $self->{error} = \0;
367 0 $self->errors = [];
368 0 $self->{_passthrough} = 0;
369 0 $self->{_mimetype} = 'text/html';
370 0 $self->{_html} = 0;
371 0 $self->{_mod_perl} = defined $ENV{MOD_PERL};
372 0 $self->{_jsonp_version} = $VERSION;
373 # File::Temp will remove the tempdir and its content on after request end
374 0 $self->{_tempdir} = File::Temp->newdir;
375 0 my $curdir = Cwd::cwd;
376 # Taint mode
377 0 ▶ $curdir = $curdir =~ m{(/.*)} ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$curdir =~ m[(/.*)] ? : 0 0 0
378 0 $self->{_curdir} = $curdir;
379 #$ENV{PATH} = '' if $self->{_taint_mode} = ${^TAINT};
380 0 ▶ die "you have to provide an AAA function" unless $self->{_aaa_sub};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_aaa_sub"} 0 0 0
381 0 my $r = CGI->new;
382 0 $$self{_cgi} = $r;
383 # this will enable us to give back the unblessed reference
384 0 my %params = $r->Vars;
385 # we assume all inputs are UTF-8, (XHR default encoding anyway) but check if params are already decoded for safety
386 0 for (keys %params) {
387 0 ▶ next if utf8::is_utf8($params{$_});
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($params{$_}) 0 0 0
388 # be wary on input UTF-8 format (use strict UTF-8 mode, not loose utf8)
389 0 $params{$_} = Encode::decode('UTF-8', $params{$_});
390 }
391 0 ▶ my $contype = $r->content_type // '';
Condition0%0/2
$r->content_type // ""
l!l
00
MC/DC0%0/1
$r->content_type // ""
$r->content_type
Truth table0%0/2
A
A= $r->content_type
Aresult
11
00
392 0 my $method = $r->request_method;
393 0 $self->{_request_method} = $method;
394 0 ▶ if($contype =~ m{application/json} && scalar keys %params == 1){
Branch: 1 branch
BranchTrueFalseTotal
if ($contype =~ m[application/json] and scalar keys %params == 1) { } 0 0 0
Condition0%0/3
$contype =~ m[application/json] and scalar keys %params == 1
!ll&&!rl&&r
000
MC/DC0%0/2
$contype =~ m[application/json] and scalar keys %params == 1
$contype =~ m[application/json] scalar keys %params == 1
Truth table0%0/3
A and B
A= $contype =~ m[application/json]B= scalar keys %params == 1
ABresult
0X0
100
111
395 0 my $payload;
396 0 ▶ if($method eq 'POST'){
Branch: 2 branches
BranchTrueFalseTotal
if ($method eq 'POST') { } 0 0 0
elsif ($method eq 'PUT') { } 0 0 0
397 0 $payload = $params{POSTDATA};
398 } elsif ($method eq 'PUT'){
399 0 $payload = $params{PUTDATA};
400 } else {
401 0 $payload = '{}'; # dummy one, fallback for invalid requests
402 }
403  
404 0 my $success = $self->graft('params', $payload);
405  
406 0 ▶ unless($success){
Branch: 1 branch
BranchTrueFalseTotal
unless ($success) 0 0 0
407 0 $self->raiseError('invalid input JSON');
408 }
409  
410 } else {
411 0 $self->params = \%params;
412 }
413  
414 0 ▶ unless((reftype $self->params // '') eq 'HASH'){
Branch: 1 branch
BranchTrueFalseTotal
unless ((builtin::reftype($self->params) // "") eq "HASH") 0 0 0
Condition0%0/2
builtin::reftype($self->params) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self->params) // ""
builtin::reftype($self->params)
Truth table0%0/2
A
A= builtin::reftype($self->params)
Aresult
11
00
415 0 $self->params = {};
416 0 $self->raiseError('invalid input JSON type (array)');
417 }
418  
419 0 ▶ if($self->{_rest}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_rest"}) 0 0 0
420 0 my $name = $0;
421 0 $name =~ m{([^/]+)$};
422 0 ▶ $name = $1 // '';
Condition0%0/2
$1 // ""
l!l
00
MC/DC0%0/1
$1 // ""
$1
Truth table0%0/2
A
A= $1
Aresult
11
00
423 0 $self->{params}->{req} = $name;
424 }
425  
426 0 ▶ my $req = $self->{params}->{req} // '';
Condition0%0/2
$self->{"params"}{"req"} // ""
l!l
00
MC/DC0%0/1
$self->{"params"}{"req"} // ""
$self->{"params"}{"req"}
Truth table0%0/2
A
A= $self->{"params"}{"req"}
Aresult
11
00
427 0 ▶ $req =~ /^([a-z][0-9a-zA-Z_\.]{1,63})$/; $req = $1 // '';
Condition0%0/2
$1 // ""
l!l
00
MC/DC0%0/1
$1 // ""
$1
Truth table0%0/2
A
A= $1
Aresult
11
00
428 0 my $sid = $r->cookie('sid');
429  
430 0 my $map = caller() . '::' . $req;
431 0 my $session = $self->_auth($sid);
432 0 $self->{_authenticated} = ! ! $session;
433 0 ▶ if($self->{_authenticated}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_authenticated'}) { } 0 0 0
434 0 ▶ $self->session = {} unless $self->graft('session', $session);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->graft("session", $session) 0 0 0
435 } else {
436 0 $self->session = {};
437 }
438  
439 0 my $isloginsub = \&$map == $self->{_login_sub};
440  
441 0 my $header = {-type => 'application/javascript', -charset => 'UTF-8'};
442 0 ▶ unless ( $sid && !$isloginsub) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sid and not $isloginsub) 0 0 0
Condition0%0/3
$sid and not $isloginsub
!ll&&!rl&&r
000
MC/DC0%0/2
$sid and not $isloginsub
$sid not $isloginsub
Truth table0%0/3
A and not(B)
A= $sidB= not $isloginsub
ABresult
0X0
100
111
443 0 my $h = Digest::SHA->new(256);
444 0 my @us = gettimeofday;
445 0 ▶ $h->add(@us, map($r->http($_) , $r->http() )) if $self->{_insecure_session};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_insecure_session"} 0 0 0
446 0 ▶ $h->add(@us, map($r->https($_), $r->https())) unless $self->{_insecure_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_insecure_session"} 0 0 0
447 0 $sid = $h->hexdigest;
448 0 my $current_path = $r->url(-absolute=>1);
449 0 $current_path =~ s|/[^/]*$||;
450 my $cookie = {
451 -name => 'sid',
452 -value => $sid,
453 -path => $current_path,
454 -secure => !$self->{_insecure_session},
455 0 -httponly => 1,
456 # TODO test SameSite on IE11 on Windows 8 and Safari on MacOS X
457 #-samesite => 'Strict'
458 };
459 0 ▶ $cookie->{-expires} = "+$$self{_session_expiration}s" if $self->{_session_expiration};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_session_expiration"} 0 0 0
460 0 $header->{-cookie} = $r->cookie($cookie);
461 }
462  
463 0 ▶ if (! ! $session && defined &$map || $isloginsub) {
Branch: 2 branches
BranchTrueFalseTotal
if (not !$session and defined &$map or $isloginsub) { } 0 0 0
elsif (not $req) { } 0 0 0
Condition0%0/6
not !$session and defined &$map or $isloginsub
l!l&&r!l&&!r
000
not !$session and defined &$map
!ll&&!rl&&r
000
MC/DC0%0/3
not !$session and defined &$map or $isloginsub
not !$session defined &$map $isloginsub
Truth table0%0/5
A and B or C
A= not !$sessionB= defined &$mapC= $isloginsub
ABCresult
11X1
0X11
1011
0X00
1000
464 0 eval {
465 0 local $SIG{'__DIE__'};
466 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
467 0 my $outcome = &$map($sid);
468 0 ▶ $self->{_authenticated} = $outcome if $isloginsub;
Branch: 1 branch
BranchTrueFalseTotal
if $isloginsub 0 0 0
469 };
470  
471 0 ▶ if($@){
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
472 0 ▶ $self->{eval} = $@ if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 0 0
473 0 $self->raiseError('unclassified error');
474 }
475  
476 # save back the session only during responses to PUT and POST HTTP methods
477 0 ▶ if($self->{_authenticated} && ($method eq 'POST' || $method eq 'PUT')){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_authenticated"} and $method eq "POST" || $method eq "PUT") 0 0 0
Condition0%0/6
$self->{"_authenticated"} and $method eq "POST" || $method eq "PUT"
!ll&&!rl&&r
000
$method eq "POST" or $method eq "PUT"
l!l&&r!l&&!r
000
MC/DC0%0/3
$self->{"_authenticated"} and $method eq "POST" || $method eq "PUT"
$self->{"_authenticated"} $method eq "POST" $method eq "PUT"
Truth table0%0/4
A and B or C
A= $self->{"_authenticated"}B= $method eq "POST"C= $method eq "PUT"
ABCresult
0XX0
1000
11X1
1011
478 # get session last changes made by concurrent requests
479 # and merge them with current session right before to
480 # pass it back to aaa sub that will save it to storage
481 # note that current session keys/values will override
482 # concurrent ones, see _merge function for details
483 0 my $concurrentSession = $self->_auth($sid);
484 0 my $thisSession = $self->session->serialize;
485 0 $self->graft('thisSession', $thisSession);
486 0 delete $self->{session};
487 0 $self->graft('session', $concurrentSession);
488 0 $self->_merge($self->session, $self->thisSession);
489 0 delete $self->{thisSession};
490 0 $self->_auth($sid, $self->session->serialize);
491 }
492  
493 } elsif (! $req) {
494 0 $self->raiseError('invalid request');
495 } else {
496 0 $self->raiseError('forbidden');
497 }
498  
499 # give a nice JSON "true"/"false" output for authentication
500 0 ▶ $self->authenticated = $self->{_authenticated} ? \1 : \0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'_authenticated'} ? : 0 0 0
501 0 ▶ $header->{'-status'} = $self->{_status_code} || 200;
Condition0%0/2
$self->{'_status_code'} || 200
l!l
00
MC/DC0%0/1
$self->{'_status_code'} || 200
$self->{'_status_code'}
Truth table0%0/2
A
A= $self->{'_status_code'}
Aresult
11
00
502 0 $header->{"$_"} = $self->{_headers}->{$_} for keys %{$self->{_headers}};
503 0 my $callback;
504  
505 # debug
506 # my @layers = PerlIO::get_layers(select);
507  
508 0 my $ofh = select;
509 # avoid putting multiple encoding layers on STDOUT
510 0 ▶ binmode($ofh) && binmode($ofh, ':encoding(UTF-8)');
Branch: 1 branch
BranchTrueFalseTotal
binmode $ofh and binmode $ofh, ":encoding(UTF-8)" 0 0 0
511 0 ▶ unless($self->{_passthrough}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_passthrough'}) { } 0 0 0
512 0 ▶ $callback = $self->params->callback if $self->{_request_method} eq 'GET';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_request_method"} eq "GET" 0 0 0
513 0 ▶ if($callback){
Branch: 1 branch
BranchTrueFalseTotal
if ($callback) 0 0 0
514 0 ▶ $callback = $callback =~ /^([a-z][0-9a-zA-Z_]{1,63})$/ ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$callback =~ /^([a-z][0-9a-zA-Z_]{1,63})$/ ? : 0 0 0
515 0 ▶ $self->raiseError('invalid callback') unless $callback;
Branch: 1 branch
BranchTrueFalseTotal
unless $callback 0 0 0
516 }
517  
518 0 ▶ $self->{_mimetype} = $callback ? 'application/javascript' : 'application/json';
Branch: 1 branch
BranchTrueFalseTotal
$callback ? : 0 0 0
519 0 $header->{'-type'} = $self->{_mimetype};
520 0 print $r->header($header);
521 0 ▶ print "$callback(" if $callback;
Branch: 1 branch
BranchTrueFalseTotal
if $callback 0 0 0
522 0 print $self->serialize;
523 0 ▶ print ')' if $callback;
Branch: 1 branch
BranchTrueFalseTotal
if $callback 0 0 0
524 } else {
525 0 $header->{'-type'} = $self->{_mimetype};
526 0 ▶ $header->{'-content-length'} = $self->{_blobsize} if $self->{_blobsize};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_blobsize"} 0 0 0
527 0 ▶ if ($self->{_html}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'_html'}) { } 0 0 0
elsif ($self->{'_sendblob'}) { } 0 0 0
528 0 print $r->header($header);
529 0 print $self->{_html};
530 } elsif ($self->{_sendblob}) {
531 0 ▶ if ($self->{_inline}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_inline'}) { } 0 0 0
532 0 $header->{'-disposition'} = 'inline';
533 } else {
534 0 $header->{'-attachment'} = $self->{_blobname};
535 }
536 0 print $r->header($header);
537 0 binmode $ofh;
538 0 print $self->{_sendblob};
539 0 delete $self->{_sendblob}; # release memory ASAP
540 } else {
541 0 ▶ if ($self->{_inline}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_inline'}) { } 0 0 0
542 0 $header->{'-disposition'} = 'inline';
543 } else {
544 0 ▶ $header->{'-attachment'} = ($self->{_sendfile} // '') =~ /([^\/]+)$/ ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
($self->{'_sendfile'} // '') =~ m[([^/]+)$] ? : 0 0 0
Condition0%0/2
$self->{"_sendfile"} // ""
l!l
00
MC/DC0%0/1
$self->{"_sendfile"} // ""
$self->{"_sendfile"}
Truth table0%0/2
A
A= $self->{"_sendfile"}
Aresult
11
00
545 }
546 0 print $r->header($header);
547 0 binmode $ofh;
548 0 print $self->_slurp($self->{_sendfile});
549 unlink $self->{_sendfile} if $self->{_delete_after_download}
550 0 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_delete_after_download"} 0 0 0
551 }
552  
553 # exit any eventual temp directory before it is removed by File::Temp
554 0 chdir $self->{_curdir};
555  
556 0 ▶ if($self->{_mod_perl}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_mod_perl"}) 0 0 0
557 0 my $rh = $r->r;
558 # suppress default Apache response
559 0 ▶ $rh->custom_response($self->{_status_code} || 200, '');
Condition0%0/2
$self->{'_status_code'} || 200
l!l
00
MC/DC0%0/1
$self->{'_status_code'} || 200
$self->{'_status_code'}
Truth table0%0/2
A
A= $self->{'_status_code'}
Aresult
11
00
560 0 $rh->rflush;
561 }
562  
563 0 delete $self->{$_} for keys %$self; # force Perl to release memory in persistent environments
564  
565 0 $self;
566 }
567  
568 sub _slurp {
569 0 ▶ my ($self, $filename) = @_;
Subroutine _slurp: not called CC=3 SCAR=24.8
570 0 ▶ return '' unless $filename && -e -f -r $filename;
Branch: 1 branch
BranchTrueFalseTotal
unless $filename and -e -f -r $filename 0 0 0
Condition0%0/3
$filename and -e -f -r $filename
!ll&&!rl&&r
000
MC/DC0%0/2
$filename and -e -f -r $filename
$filename -e -f -r $filename
Truth table0%0/3
A and B
A= $filenameB= -e -f -r $filename
ABresult
0X0
100
111
571 0 open my $fh, '<', $filename;
572 0 local $/;
573 0 <$fh>;
574 }
575  
576 sub _merge {
577 # merge $_[2] into $_[1]
578 # you must use params directly to make changes
579 # directly on referenced objects, otherwise
580 # perl will work on local copies of them
581  
582 0 ▶ unless((reftype $_[1] // '') eq 'HASH'){
Subroutine _merge: not called CC=10 SCAR=47.0
Branch: 1 branch
BranchTrueFalseTotal
unless ((builtin::reftype($_[1]) // "") eq "HASH") 0 0 0
Condition0%0/2
builtin::reftype($_[1]) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($_[1]) // ""
builtin::reftype($_[1])
Truth table0%0/2
A
A= builtin::reftype($_[1])
Aresult
11
00
583 0 $_[1] = $_[2];
584 0 return;
585 } # if $_[0] points to a scalar or array, $_[1] will prevail
586  
587 0 ▶ unless(scalar keys %{$_[1]}){
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar keys %{$_[1];}) 0 0 0
588 0 $_[1] = $_[2];
589 0 return;
590 } # if $_[0] is an empty hash, $_[1] will prevail
591  
592 0 my @keys = keys %{$_[1]};
593 0 push @keys, keys %{$_[2]};
594 0 my $resultOK = 1;
595 0 for(@keys){
596 0 ▶ if((reftype $_[1]->{$_} // '') ne 'HASH' || (reftype $_[2]->{$_} // '') ne 'HASH'){
Branch: 1 branch
BranchTrueFalseTotal
if ((builtin::reftype($_[1]{$_}) // "") ne "HASH" or (builtin::reftype($_[2]{$_}) // "") ne "HASH") 0 0 0
Condition0%0/7
(builtin::reftype($_[1]{$_}) // "") ne "HASH" or (builtin::reftype($_[2]{$_}) // "") ne "HASH"
l!l&&r!l&&!r
000
builtin::reftype($_[1]{$_}) // ""
l!l
00
builtin::reftype($_[2]{$_}) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($_[1]{$_}) // "") ne "HASH" or (builtin::reftype($_[2]{$_}) // "") ne "HASH"
builtin::reftype($_[1]{$_}) builtin::reftype($_[2]{$_})
Truth table0%0/3
A or B
A= builtin::reftype($_[1]{$_})B= builtin::reftype($_[2]{$_})
ABresult
1X1
011
000
597 0 ▶ $_[1]->{$_} = defined $_[2]->{$_} ? $_[2]->{$_} : $_[1]->{$_};
Branch: 1 branch
BranchTrueFalseTotal
defined $_[2]{$_} ? : 0 0 0
598 0 next;
599 }
600 0 $_[0]->_merge($_[1]->{$_}, $_[2]->{$_});
601 }
602 }
603  
604 =head3 html
605  
606 use this method if you need to return HTML instead of JSON, pass the HTML string as argument
607  
608 yoursubname
609 {
610 ...
611 $j->html($html);
612 }
613  
614 =cut
615  
616 sub html {
617 0 ▶ my ($self, $html, $mime) = @_;
Subroutine html: not called CC=4 SCAR=30.0
Pod documented
618 0 ▶ return $self unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
619 0 $self->{_mimetype} = $mime;
620 0 $self->{_passthrough} = 1;
621 0 $self->{_html} = $html;
622 0 $self;
623 }
624  
625 =head3 sendblob
626  
627 use this method if you need to return a file held in memory instead of JSON, pass the bin/string blob as argument. MIME type will be set always to I<application/octet-stream>.
628  
629 yoursubname
630 {
631 ...
632 $j->sendblob($fullfilepath, $isTmpFileToDelete);
633 }
634  
635 =cut
636  
637 sub sendblob {
638 0 ▶ my ($self, $blob, $attachmentName, $size, $inline) = @_;
Subroutine sendblob: not called CC=6 SCAR=37.4
Pod documented
639 0 ▶ return $self unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
640 0 $self->{_passthrough} = 1;
641 0 $self->{_mimetype} = 'application/octet-stream';
642 0 ▶ $self->{_sendblob} = $blob // '';
Condition0%0/2
$blob // ""
l!l
00
MC/DC0%0/1
$blob // ""
$blob
Truth table0%0/2
A
A= $blob
Aresult
11
00
643 0 ▶ $self->{_blobname} = $attachmentName || 'file';
Condition0%0/2
$attachmentName || 'file'
l!l
00
MC/DC0%0/1
$attachmentName || 'file'
$attachmentName
Truth table0%0/2
A
A= $attachmentName
Aresult
11
00
644 0 $self->{_blobsize} = 0 + $size;
645 0 $self->{_inline} = ! ! $inline;
646 0 $self;
647 }
648  
649 =head3 sendfile
650  
651 use this method if you need to return a file instead of JSON, pass the full file path as as argument. MIME type will be set always to I<application/octet-stream>. The last parameter is evaluated as boolean and if true will make JSONP to delete the passed file after it has been downloaded.
652  
653 yoursubname
654 {
655 ...
656 $j->sendfile($fullfilepath, $isTmpFileToDelete);
657 }
658  
659 =cut
660  
661 sub sendfile {
662 0 ▶ my ($self, $filepath, $isTmpFileToDelete) = @_;
Subroutine sendfile: not called CC=4 SCAR=30.0
Pod documented
663 0 ▶ return $self unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
664 0 $self->{_passthrough} = 1;
665 0 $self->{_mimetype} = 'application/octet-stream';
666 0 $self->{_sendfile} = $filepath;
667 0 $self->{_delete_after_download} = ! ! $isTmpFileToDelete;
668 0 $self;
669 }
670  
671 =head3 file
672  
673 call this method to send a file with custom MIME type and/or if you want to set it as inline. The last parameter is evaluated as boolean and if true will make JSONP to delete the passed file after it has been downloaded.
674  
675 $j->file('path to file', $mimetype, $isInline, $isTmpFileToDelete);
676  
677 =cut
678  
679 sub file {
680 0 ▶ my ($self, $filepath, $mime, $inline, $isTmpFileToDelete) = @_;
Subroutine file: not called CC=4 SCAR=30.0
Pod documented
681 0 ▶ return $self unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
682 0 $self->{_passthrough} = 1;
683 0 $self->{_mimetype} = $mime;
684 0 $self->{_sendfile} = $filepath;
685 0 $self->{_inline} = ! ! $inline;
686 0 $self->{_delete_after_download} = ! ! $isTmpFileToDelete;
687 0 $self;
688 }
689  
690 =head3 debug
691  
692 call this method before to call C<run> to enable debug mode in a test environment, basically this one will output pretty printed JSON instead of "compressed" one. Furthermore with debug mode turned on the content of session will be returned to the calling page in its own json branch. You can pass a switch to this method (that will be parsed as bool) to set it I<on> or I<off>. It could be useful if you want to pass a variable. If no switch (or undefined one) is passed, the switch will be set as true. Example:
693  
694 $j->debug->run;
695  
696 is the same as:
697  
698 $j->debug(1)->run;
699  
700 =cut
701  
702 sub debug {
703 0 ▶ my ($self, $switch) = @_;
Subroutine debug: not called CC=4 SCAR=30.0
Pod documented
704 0 ▶ return $self unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
705 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
706 0 $self->{_debug} = $switch;
707 0 $self->{_pretty} = $switch;
708 0 $self;
709 }
710  
711 =head3 pretty
712  
713 call this method before to call C<run> to enable pretty output on I<serialize> method, basically this one will output pretty printed JSON instead of "compressed" one. You can pass a switch to this method (that will be parsed as bool) to set it I<on> or I<off>. It could be useful if you want to pass a variable. If no switch (or undefined one) is passed, the switch will be set as true. Example:
714  
715 $j->pretty->run;
716  
717 is the same as:
718  
719 $j->pretty(1)->run;
720  
721 =cut
722  
723 sub pretty {
724 0 ▶ my ($self, $switch) = @_;
Subroutine pretty: not called CC=4 SCAR=30.0
Pod documented
725 0 ▶ return $self unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
726 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
727 0 $self->{_pretty} = $switch;
728 0 $self;
729 }
730  
731 =head3 insecure
732  
733 call this method if you are going to deploy the script under plain http protocol instead of https. This method can be useful during testing of your application. You can pass a switch to this method (that will parsed as bool) to set it on or off. It could be useful if you want to pass a variable. If no switch (or undefined one) is passed, the switch will be set as true.
734  
735 =cut
736  
737 sub insecure {
738 0 ▶ my ($self, $switch) = @_;
Subroutine insecure: not called CC=4 SCAR=30.0
Pod documented
739 0 ▶ return $self unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
740 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
741 0 $self->{_insecure_session} = $switch;
742 0 $self;
743 }
744  
745 =head3 rest
746  
747 call this method if you want to omit the I<req> parameter and want that a sub with same name of the script will be called instead, so if your script will be I</somepath/cgi-bin/myscript> the sub I<myscript> will be called instead of the one passed with I<req> (that can be omitted at this point). You can pass a switch to this method (that will parsed as bool) to set it on or off. It could be useful if you want to pass a variable. If no switch (or undefined one) is passed, the switch will be set as true.
748  
749 =cut
750  
751 sub rest {
752 0 ▶ my ($self, $switch) = @_;
Subroutine rest: not called CC=4 SCAR=30.0
Pod documented
753 0 ▶ return $self unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
754 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
755 0 $self->{_rest} = $switch;
756 0 $self;
757 }
758  
759 =head3 set_session_expiration
760  
761 call this method with desired expiration time for cookie in B<seconds>, the default behavior is to keep the cookie until the end of session (until the browser is closed).
762  
763 =cut
764  
765 sub set_session_expiration {
766 0 ▶ my ($self, $expiration) = @_;
Subroutine set_session_expiration: not called CC=3 SCAR=24.8
Pod documented
767 0 ▶ return $self unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
768 0 $self->{_session_expiration} = $expiration;
769 0 $self;
770 }
771  
772 =head3 query
773  
774 call this method to retrieve a named parameter, $jsonp->query(paramenter_name) will return the value of paramenter_name from query string. The method called without arguments returns all parameters in hash form
775  
776 =cut
777  
778 # TODO remove query method, now it is useless
779 sub query {
780 0 ▶ my ($self, $param) = @_;
Subroutine query: not called CC=2 SCAR=17.9
Pod documented
781 0 ▶ $param ? $self->params->{$param} : $self->params;
Branch: 1 branch
BranchTrueFalseTotal
$param ? : 0 0 0
782 }
783  
784 =head3 plain_json
785  
786 B<this function is deprecated and has no effect anymore, now a plain JSON request will be returned if no I<callback> parameter will be provided.>
787 call this function to enable output in simple JSON format (not enclosed within jquery_callback_name()... ). Do this only when your script is on the same domain of static content. This method can be useful also during testing of your application. You can pass a switch to this method (that will parsed as bool) to set it on or off. It could be useful if you want to pass a variable. If no switch (or undefined one) is passed, the switch will be set as true.
788  
789 =cut
790  
791 sub plain_json {
792 0 ▶ my ($self, $switch) = @_;
Subroutine plain_json: not called CC=4 SCAR=30.0
Pod documented
793 0 ▶ return $self unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
794 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
795 0 $self->{_plain_json} = $switch;
796 0 $self;
797 }
798  
799 =head3 aaa
800  
801 pass to this method the reference (or the name, either way will work) of the function under which you will manage AAA stuff, like session check, tracking and expiration, and ACL to exposed methods
802  
803 =cut
804  
805 sub aaa {
806 0 ▶ my ($self, $sub) = @_;
Subroutine aaa: not called CC=3 SCAR=20.3
Pod documented
807 0 ▶ if (ref $sub eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sub eq 'CODE') { } 0 0 0
808 0 $self->{_aaa_sub} = $sub;
809 }
810 else {
811 0 my $map = caller() . '::' . $sub;
812 {
813 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
814 0 ▶ die "given AAA function does not exist" unless defined &$map;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$map 0 0 0
815 0 $self->{_aaa_sub} = \&$map;
816 }
817 }
818 0 $self;
819 }
820  
821 =head3 login
822  
823 pass to this method the reference (or the name, either way will work) of the function under which you will manage the login process. The function will be called with the current session key (from cookie or automatically created). It will be your own business to save the key-value pair to the storage you choose (database, memcached, NoSQL, and so on). It is advised to keep the initial value associated with the key void, as the serialized I<session> branch of JSONP object will be automatically passed to your aaa function at the end or request cycle, so you should save it from that place. If you want to access/modify the session value do it through the I<session> branch via I<$jsonp-E<gt>session-E<gt>whatever(value)> or I<$jsonp-E<gt>{session}{whatever} = value> or I<$jsonp-E<gt>{session}-E<gt>{whatever} = value> calls.
824  
825 =cut
826  
827 sub login {
828 0 ▶ my ($self, $sub) = @_;
Subroutine login: not called CC=3 SCAR=20.3
Pod documented
829 0 ▶ if (ref $sub eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sub eq 'CODE') { } 0 0 0
830 0 $self->{_login_sub} = $sub;
831 }
832 else {
833 0 my $map = caller() . '::' . $sub;
834 {
835 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
836 0 ▶ die "given login function does not exist" unless defined &$map;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$map 0 0 0
837 0 $self->{_login_sub} = \&$map;
838 }
839 }
840 0 $self;
841 }
842  
843 =head3 logout
844  
845 pass to this method the reference (or the name, either way will work) of the function under which you will manage the logout process. The function will be called with the current session key (from cookie or automatically created). It will be your own business to delete the key-value pair from the storage you choose (database, memcached, NoSQL, and so on).
846  
847 =cut
848  
849 sub logout {
850 0 ▶ my ($self, $sub) = @_;
Subroutine logout: not called CC=3 SCAR=20.3
Pod documented
851 0 ▶ if (ref $sub eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sub eq 'CODE') { } 0 0 0
852 0 $self->{_logout_sub} = $sub;
853 }
854 else {
855 0 my $map = caller() . '::' . $sub;
856 {
857 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
858 0 ▶ die "given logout function does not exist" unless defined &$map;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$map 0 0 0
859 0 $self->{_logout_sub} = \&$map;
860 }
861 }
862 0 $self;
863 }
864  
865 =head3 raiseError
866  
867 call this method in order to return an error message to the calling page. You can add as much messages you want, calling the method several times, it will be returned an array of messages to the calling page. The first argument could be either a string or a B<strings array reference>. The second argument is an optional HTTP status code, the default will be 200.
868  
869 =cut
870  
871 sub raiseError {
872 2 ▶ my ($self, $message, $code, $customHeaders) = @_;
Subroutine raiseError: called CC=7 SCAR=19.7
Pod documented
873 2 ▶ return $self unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 2 2
Condition50%1/2
builtin::reftype($self) // ""
l!l
20
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table50%1/2
A
A= builtin::reftype($self)
Aresult
11
00
874 2 $self->error = \1;
875 2 ▶ push @{$self->{errors}}, (reftype $message // '') eq 'ARRAY' ? @$message : $message;
Branch: 1 branch
BranchTrueFalseTotal
(builtin::reftype($message) // '') eq 'ARRAY' ? : 1 1 2
Condition100%2/2
builtin::reftype($message) // ""
l!l
11
MC/DC100%1/1
builtin::reftype($message) // ""
builtin::reftype($message)
Truth table100%2/2
A
A= builtin::reftype($message)
Aresult
11
00
876 2 ▶ $self->{_status_code} = $code if defined $code;
Branch: 1 branch
BranchTrueFalseTotal
if defined $code 1 1 2
877 2 ▶ $self->{_headers} = $customHeaders if defined $customHeaders;
Branch: 1 branch
BranchTrueFalseTotal
if defined $customHeaders 0 2 2
878  
879 2 $self;
880 }
881  
882 =head3 graft
883  
884 call this method to append a JSON object as a perl subtree on a node. This is a native method, only function notation is supported, lvalue assignment notation is reserved to autovivification shortcut feature. Examples:
885 $j->subtree->graft('newbranchname', '{"name" : "JSON object", "count" : 2}');
886 print $j->subtree->newbranchname->name; # will print "JSON object"
887 $j->sublist->graft->('newbranchname', '[{"name" : "first one"}, {"name" : "second one"}]');
888 print $j->sublist->newbranchname->[1]->name; will print "second one"
889 my $index = 1; print $j->sublist->newbranchname->$index->name; will print "second one" as well
890  
891 This method will return the reference to the newly added element if added successfully, a false value otherwise.
892  
893 =cut
894  
895 sub graft {
896 0 ▶ my ($self, $name, $json) = @_;
Subroutine graft: not called CC=4 SCAR=30.0
Pod documented
897  
898 0 ▶ return 0 unless (reftype $self // '') eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
899  
900 0 eval{
901 0 local $SIG{'__DIE__'};
902 0 $self->{$name} = JSON->new->decode($json);
903 };
904  
905 0 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
906  
907 #_bless_tree returns the node passed to it blessed as JSONP
908 0 $self->_bless_tree($self->{$name});
909 }
910  
911 =head3 stack
912  
913 call this method to add a JSON object to a node-array. This is a native method, only function notation is supported, lvalue assignment notation is reserved to autovivification shortcut feature. Examples:
914  
915 $j->first->second = [{a => 1}, {b = 2}];
916 $j->first->second->stack('{"c":"3"}');
917 say $j->first->second->[2]->c; # will print 3;
918 my $index = 2; say $j->first->second->$index->c; # will print 3 as well
919  
920 this method of course works only with nodes that are arrays. Be warned that the decoded JSON string will be added as B<element> to the array, so depending of the JSON string you pass, you can have an element that is an hashref (another "node"), a scalar (a "value") or an arrayref (array of arrays, if you want). This method will return the reference to the newly added element if added successfully, a false value otherwise. Combining this to graft method you can do crazy things like this:
921  
922 my $j = JSONP->new;
923 $j->firstnode->graft('secondnode', '{"a" : 1}')->thirdnode = [];
924 $j->firstnode->secondnode->thirdnode->stack('{"b" : 9}')->fourthnode = 10;
925 say $j->firstnode->secondnode->a; # will print 1
926 say $j->firstnode->secondnode->thirdnode->[0]->b; # will print 9
927 say $j->firstnode->secondnode->thirdnode->[0]->fourthnode; # will print 10
928 my $index = 0; say $j->firstnode->secondnode->thirdnode->$index->fourthnode; # will print 10 as well
929  
930 =cut
931  
932 sub stack {
933 0 ▶ my ($self, $json) = @_;
Subroutine stack: not called CC=4 SCAR=30.0
Pod documented
934  
935 0 ▶ return 0 unless (reftype $self // '') eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "ARRAY" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
936  
937 0 eval{
938 0 local $SIG{'__DIE__'};
939 0 push @$self, JSON->new->decode($json);
940 };
941 0 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
942  
943 #_bless_tree returns the node passed to it blessed as JSONP
944 0 $self->_bless_tree($self->[$#{$self}]);
945 }
946  
947 =head3 append
948  
949 call this method to add a Perl object to a node-array. This is a native method, only function notation is supported, lvalue assignment notation is reserved to autovivification shortcut feature. Examples:
950  
951 $j->first->second = [{a => 1}, {b = 2}];
952 $j->first->second->append({c => 3});
953 say $j->first->second->[2]->c; # will print 3;
954  
955 this method of course works only with nodes that are arrays. Be warned that the element will be added as B<element> to the array, so depending of the element you pass, you can have an element that is an hashref (another "node"), a scalar (a "value") or an arrayref (array of arrays, if you want). This method will return the reference to the newly added element if added successfully, a false value otherwise. You can do crazy things like this:
956  
957 my $j = JSONP->new;
958 $j->firstnode->secondnode->a = 1;
959 $j->firstnode->secondnode->thirdnode = [];
960 $j->firstnode->secondnode->thirdnode->append({b => 9})->fourthnode = 10;
961 say $j->firstnode->secondnode->a; # will print 1
962 say $j->firstnode->secondnode->thirdnode->[0]->b; # will print 9
963 say $j->firstnode->secondnode->thirdnode->[0]->fourthnode; # will print 10
964  
965 =cut
966  
967 sub append {
968 0 ▶ my ($self, $el) = @_;
Subroutine append: not called CC=3 SCAR=24.8
Pod documented
969  
970 0 ▶ return 0 unless (reftype $self // '') eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "ARRAY" 0 0 0
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
971  
972 0 push @$self, $el;
973  
974 #_bless_tree returns the node passed to it blessed as JSONP
975 0 $self->_bless_tree($self->[$#{$self}]);
976 }
977  
978 =head3 loop
979  
980 when called from an array node it will loop over its elements returning the B<I<reference>> to the current one, so I<you can change it in place>
981 or copy its value to perform calculation with a copy. Returning the reference assure that loops over arrays items that evaluate as false
982 won't stop until actual array end.
983 Of course this method has the overhead of a function call on every cycle, so use it for convenience on small arrays when performance is not critical.
984 You can also want to use this when the operation to perform on each cycle take a significant amount of time where the overhead becomes negligible.
985 In general avoid to use it in tight high-performance needing loops. Note that the returned item will be a JSONP object (or a JSONP derived type if you subclass it) B<only if it is a non-blessed HASH or ARRAY reference, already blessed as other class object>, in case the returned item is a raw HASH or ARRAY, it will be blessed with the same class of the array we are looping onto (typically JSONP itself), so the item will hold all the JSONP syntactic sugar and methods.
986 Never exit $array->loop cycles using I<last> to avoid memory leaks, you should avoid to use this method when you expect to early exit the cycle.
987  
988 my $j = JSONP->new;
989 $j->an->array = [
990 [11, 12],
991 [21, 22]
992 ];
993  
994 say $j->an->pretty->serialize;
995  
996 while (my $row = $j->an->array->loop) {
997 while (my $field = $$row->loop){
998 my $acopy = $$field;
999 $$field++;
1000 }
1001 }
1002  
1003 say $j->an->pretty->serialize;
1004  
1005 =cut
1006  
1007 sub loop {
1008 0 ▶ my ($self) = @_;
Subroutine loop: not called CC=6 SCAR=37.4
Pod documented
1009 0 ▶ my $refself = reftype $self // '';
Condition0%0/2
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table0%0/2
A
A= builtin::reftype($self)
Aresult
11
00
1010 0 my $class = ref $self; # bless in cases we have not a deep recursive blessing
1011 0 ▶ return undef unless $refself eq 'ARRAY'; ## no critic
Branch: 1 branch
BranchTrueFalseTotal
unless $refself eq "ARRAY" 0 0 0
1012 # use different counter for every array
1013 0 state $indexes = {};
1014 0 my $addr = 0 + $self;
1015 0 my $index = $indexes->{$addr};
1016 0 $index += 0;
1017 # array can change during loop
1018 0 my $size = @$self;
1019  
1020 0 ▶ if ($index < $size){
Branch: 1 branch
BranchTrueFalseTotal
if ($index < $size) { } 0 0 0
1021 # refs are never undef so we can loop
1022 # over false scalar items as well
1023 0 my $item = $self->[$indexes->{$addr}++];
1024 0 my $reftype = ref $item;
1025 # bless the item if it is an unblessed hash or array reference (avoid to touch blessed objects)
1026 0 ▶ bless $item, $class if $reftype eq 'HASH' || $reftype eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if $reftype eq "HASH" or $reftype eq "ARRAY" 0 0 0
Condition0%0/3
$reftype eq "HASH" or $reftype eq "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/2
$reftype eq "HASH" or $reftype eq "ARRAY"
$reftype eq "HASH" $reftype eq "ARRAY"
Truth table0%0/3
A or B
A= $reftype eq "HASH"B= $reftype eq "ARRAY"
ABresult
1X1
011
000
1027 0 return \$item;
1028 } else {
1029 # reset counter for next loops
1030 # and avoid memory leaks...
1031 # note that the loops exited with "last"
1032 # will leak few bytes until program end,
1033 # with about 8 bytes per loop it's safe
1034 0 delete $indexes->{$addr};
1035 0 return undef; ## no critic
1036 }
1037 }
1038  
1039 =head3 serialize
1040  
1041 call this method to serialize and output a subtree:
1042  
1043 $j->subtree->graft('newbranchname', '{"name" : "JSON object", "count" : 2}');
1044 print $j->subtree->newbranchname->name; # will print "JSON object"
1045 $j->sublist->graft->('newbranchname', '[{"name" : "first one"}, {"name" : "second one"}]');
1046 print $j->sublist->newbranchname->[1]->name; will print "second one"
1047 $j->subtree->newbranchname->graft('subtree', '{"name" : "some string", "count" : 4}');
1048 print $j->subtree->newbranchname->subtree->serialize; # will print '{"name" : "some string", "count" : 4}'
1049  
1050 if you have a JSONP ARRAY object I<pretty> call won't be effective. To circumvent this limitation you can pass an override I<pretty> switch to serialize:
1051  
1052 $j = JSONP->new(['one', 'two', 'three']);
1053 print $j->serialize(1);
1054  
1055 IMPORTANT NOTE: do not assign any reference to a sub to any node, example:
1056  
1057 $j->donotthis = sub { ... };
1058  
1059 for now the module does assume that nodes/leafs will be scalars/hashes/arrays, so same thing is valid for filehandles.
1060  
1061 =cut
1062  
1063 sub serialize {
1064 10 ▶ my ($self, $prettyoverride, $canonical) = @_;
Subroutine serialize: called CC=7 SCAR=21.3
Pod documented
1065 10 $canonical = !! $canonical;
1066 # $prettyoverride to be used with ARRAY objects where we cannot have _pretty member
1067 10 ▶ $prettyoverride //= 0;
Condition50%1/2
$prettyoverride //= 0
l!l
100
MC/DC0%0/1
$prettyoverride //= 0
$prettyoverride
Truth table50%1/2
A
A= $prettyoverride
Aresult
11
00
1068 10 my $out;
1069 10 ▶ my $pretty = (reftype $self // '') eq 'HASH' && $self->{_pretty} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
(builtin::reftype($self) // '') eq 'HASH' && $self->{'_pretty'} ? : 0 10 10
Condition60%3/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_pretty"}
!ll&&!rl&&r
280
builtin::reftype($self) // ""
l!l
100
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_pretty"}
builtin::reftype($self) $self->{"_pretty"}
Truth table33%1/3
A and B
A= builtin::reftype($self)B= $self->{"_pretty"}
ABresult
0X0
100
111
1070 10 ▶ $pretty ||= $prettyoverride;
Condition33%1/3
$pretty ||= $prettyoverride
l!l&&r!l&&!r
0010
MC/DC0%0/2
$pretty ||= $prettyoverride
$pretty $prettyoverride
Truth table33%1/3
A ||= B
A= $prettyB= $prettyoverride
ABresult
1X1
011
000
1071  
1072 10 ▶ eval{
Branch: 1 branch
BranchTrueFalseTotal
eval { do { local $SIG{"__DIE__"}; $out = "JSON"->new->canonical($canonical)->pretty($pretty)->allow_unknown->allow_blessed->convert_blessed->encode($self) } } or $@ 0 10 10
1073 10 local $SIG{'__DIE__'};
1074 10 $out = JSON->new->canonical($canonical)->pretty($pretty)->allow_unknown->allow_blessed->convert_blessed->encode($self);
1075 } || $@;
1076 }
1077  
1078 =head3 tempdir
1079  
1080 returns a temporary directory whose content will be removed at the request end.
1081 if you pass a relative path, it will be created under the random tmp directory.
1082 if creation fails, a boolean false will be retured (void string).
1083  
1084 my $path = $j->tempdir; # will return something like /tmp/systemd-private-af123/tmp/nRmseALe8H
1085 my $path = $j->tempdir('DIRNAME'); # will return something like /tmp/systemd-private-af123/tmp/nRmseALe8H/DIRNAME
1086  
1087 =cut
1088  
1089 sub tempdir {
1090 0 ▶ my ($self, $path) = @_;
Subroutine tempdir: not called CC=5 SCAR=34.0
Pod documented
1091 0 ▶ return '' unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
1092 0 ▶ return $self->{_tempdir}->dirname unless $path;
Branch: 1 branch
BranchTrueFalseTotal
unless $path 0 0 0
1093 0 return $self->_makePath($path);
1094 }
1095  
1096 =head3 ctwd
1097  
1098 changes current working directory to a random temporary directory whose content will be removed at the request end.
1099 if you pass a path, it will be appended to the temporary directory before cwd'ing on it, bool outcome will be returned.
1100 if creation fails, a boolean false will be returned (void string).
1101  
1102 my $cwdOK = $j->ctwd;
1103  
1104 =cut
1105  
1106 sub ctwd {
1107 0 ▶ my ($self, $path) = @_;
Subroutine ctwd: not called CC=6 SCAR=37.4
Pod documented
1108 0 ▶ return '' unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
1109 0 ▶ return chdir $self->{_tempdir} unless $path;
Branch: 1 branch
BranchTrueFalseTotal
unless $path 0 0 0
1110 0 $path = $self->_makePath($path);
1111 0 ▶ return $path ? chdir $path : '';
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 0 0 0
1112 }
1113  
1114 sub _makePath {
1115 0 ▶ my ($self, $path) = @_;
Subroutine _makePath: not called CC=6 SCAR=37.4
1116 0 ▶ return '' unless (reftype $self // '') eq 'HASH' && $self->{_is_root_element};
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"} 0 0 0
Condition0%0/5
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
!ll&&!rl&&r
000
builtin::reftype($self) // ""
l!l
00
MC/DC0%0/2
(builtin::reftype($self) // "") eq "HASH" and $self->{"_is_root_element"}
builtin::reftype($self) $self->{"_is_root_element"}
Truth table0%0/3
A and B
A= builtin::reftype($self)B= $self->{"_is_root_element"}
ABresult
0X0
100
111
1117 0 my $mkdirerr;
1118 0 $path = "$$self{_tempdir}/$path";
1119 0 File::Path::make_path($path, {error => \$mkdirerr});
1120 0 ▶ if(@$mkdirerr){
Branch: 1 branch
BranchTrueFalseTotal
if (@$mkdirerr) 0 0 0
1121 0 for my $direrr (@$mkdirerr){
1122 0 my ($curdir, $curmessage) = %$direrr;
1123 0 say STDERR "error while attempting to create $curdir: $curmessage";
1124 }
1125  
1126 # if creation fails set $path to a "false" string
1127 0 $path = '';
1128 }
1129  
1130 0 $path;
1131 }
1132  
1133 sub _bless_tree {
1134 183 ▶ my ($self, $node) = @_;
Subroutine _bless_tree: called CC=8 SCAR=20.8
1135 183 my $class = ref $self;
1136 183 my $refnode = ref $node;
1137 # proceed only with hashes or arrays not already blessed
1138 183 ▶ return $node if $refnode eq $class;
Branch: 1 branch
BranchTrueFalseTotal
if $refnode eq $class 93 90 183
1139 #my $reftype = reftype($node) // '';
1140 #return unless $reftype eq 'HASH' || $reftype eq 'ARRAY';
1141 # to not change class to objects grafted to JSONP tree
1142 90 ▶ return $node unless $refnode eq 'HASH' || $refnode eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless $refnode eq "HASH" or $refnode eq "ARRAY" 65 25 90
Condition100%3/3
$refnode eq "HASH" or $refnode eq "ARRAY"
l!l&&r!l&&!r
17865
MC/DC100%2/2
$refnode eq "HASH" or $refnode eq "ARRAY"
$refnode eq "HASH" $refnode eq "ARRAY"
Truth table100%3/3
A or B
A= $refnode eq "HASH"B= $refnode eq "ARRAY"
ABresult
1X1
011
000
1143 25 bless $node, $class;
1144 25 ▶ if ($refnode eq 'HASH'){
Branch: 1 branch
BranchTrueFalseTotal
if ($refnode eq "HASH") 17 8 25
1145 17 $self->_bless_tree($node->{$_}) for keys %$node;
1146 }
1147 25 ▶ if ($refnode eq 'ARRAY'){
Branch: 1 branch
BranchTrueFalseTotal
if ($refnode eq "ARRAY") 8 17 25
1148 8 $self->_bless_tree($_) for @$node;
1149 }
1150 25 $node;
1151 }
1152  
1153 sub TO_JSON {
1154 10 ▶ my $self = shift;
Subroutine TO_JSON: called CC=11 SCAR=30.1
Pod undocumented
1155 10 my $output;
1156  
1157 10 ▶ return [@$self] if (reftype $self // '') eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::reftype($self) // "") eq "ARRAY" 2 8 10
Condition50%1/2
builtin::reftype($self) // ""
l!l
100
MC/DC0%0/1
builtin::reftype($self) // ""
builtin::reftype($self)
Truth table50%1/2
A
A= builtin::reftype($self)
Aresult
11
00
1158  
1159 8 $output = {};
1160 8 for(keys %$self){
1161 24 my $skip = 0;
1162  
1163 24 ▶ unless($self->{_debug}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_debug"}) 24 0 24
1164 24 ▶ if($self->{_is_root_element}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_is_root_element"}) 0 24 24
1165 0 ▶ $skip++ if $_ =~ /_sub$/;
Branch: 1 branch
BranchTrueFalseTotal
if $_ =~ /_sub$/ 0 0 0
1166 0 ▶ $skip++ if $_ eq 'session';
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq "session" 0 0 0
1167 0 ▶ $skip++ if $_ eq 'params';
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq "params" 0 0 0
1168 }
1169 24 ▶ $skip++ if $_ =~ /^_/;
Branch: 1 branch
BranchTrueFalseTotal
if $_ =~ /^_/ 0 24 24
1170 }
1171  
1172 24 ▶ next if $skip;
Branch: 1 branch
BranchTrueFalseTotal
if $skip 0 24 24
1173  
1174 24 $output->{$_} = $self->{$_};
1175 }
1176 8 return $output;
1177 }
1178  
1179 # avoid calling AUTOLOAD on destroy
1180 ▶sub DESTROY{}
Subroutine DESTROY: not called CC=1 SCAR=0.0
1181  
1182 sub AUTOLOAD : lvalue {
1183 149 ▶ my $classname = ref $_[0];
Subroutine AUTOLOAD: called CC=16 SCAR=32.8
1184 149 my $validname = q{[^:'[:cntrl:]]{0,1024}};
1185 149 our $AUTOLOAD =~ /^${classname}::($validname)$/;
1186 149 my $key = $1;
1187 149 ▶ die "illegal key name, must be of $validname form\n$AUTOLOAD" unless $key;
Branch: 1 branch
BranchTrueFalseTotal
unless $key 0 149 149
1188 149 ▶ my $arraynode = (reftype($_[0]) // '') eq 'ARRAY';
Condition50%1/2
builtin::reftype($_[0]) // ""
l!l
1490
MC/DC0%0/1
builtin::reftype($_[0]) // ""
builtin::reftype($_[0])
Truth table50%1/2
A
A= builtin::reftype($_[0])
Aresult
11
00
1189 149 ▶ die "array indexes must be unsigned integers" if $arraynode && $key !~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $arraynode and not $key =~ /^\d+$/ 0 149 149
Condition33%1/3
$arraynode and not $key =~ /^\d+$/
!ll&&!rl&&r
14900
MC/DC0%0/2
$arraynode and not $key =~ /^\d+$/
$arraynode not $key =~ /^\d+$/
Truth table33%1/3
A and not(B)
A= $arraynodeB= not $key =~ /^\d+$/
ABresult
0X0
100
111
1190 149 ▶ my $miss = want('OBJECT') ? {} : undef;
Branch: 1 branch
BranchTrueFalseTotal
want('OBJECT') ? : 86 63 149
1191 149 ▶ my $retval = $arraynode ? $_[0]->[$key] : $_[0]->{$key}; # can be undef
Branch: 1 branch
BranchTrueFalseTotal
$arraynode ? : 0 149 149
1192 149 ▶ $retval = $_[1] // $retval // $miss;
Condition100%6/6
($_[1] // $retval) // $miss
l!l&&r!l&&!r
13469
$_[1] // $retval
l!l&&r!l&&!r
512915
MC/DC100%3/3
($_[1] // $retval) // $miss
$_[1] $retval $miss
Truth table100%4/4
A // B // C
A= $_[1]B= $retvalC= $miss
ABCresult
1XX1
01X1
0011
0000
1193 149 ▶ return '' if want('RVALUE') && ! defined $retval;
Branch: 1 branch
BranchTrueFalseTotal
if want("RVALUE") and not defined $retval 0 149 149
Condition66%2/3
want("RVALUE") and not defined $retval
!ll&&!rl&&r
14450
MC/DC0%0/2
want("RVALUE") and not defined $retval
want("RVALUE") not defined $retval
Truth table66%2/3
A and not(B)
A= want("RVALUE")B= not defined $retval
ABresult
0X0
100
111
1194 149 ▶ return $$retval if want('BOOL') && (reftype($retval) // '') eq 'SCALAR' && $$retval == $$retval % 2;
Branch: 1 branch
BranchTrueFalseTotal
if want("BOOL") and (builtin::reftype($retval) // "") eq "SCALAR" and $$retval == $$retval % 2 0 149 149
Condition25%2/8
want("BOOL") and (builtin::reftype($retval) // "") eq "SCALAR" and $$retval == $$retval % 2
!ll&&!rl&&r
14900
want("BOOL") and (builtin::reftype($retval) // "") eq "SCALAR"
!ll&&!rl&&r
14900
builtin::reftype($retval) // ""
l!l
00
MC/DC0%0/3
want("BOOL") and (builtin::reftype($retval) // "") eq "SCALAR" and $$retval == $$retval % 2
want("BOOL") builtin::reftype($retval) $$retval == $$retval % 2
Truth table25%1/4
A and B and C
A= want("BOOL")B= builtin::reftype($retval)C= $$retval == $$retval % 2
ABCresult
0XX0
10X0
1100
1111
1195  
1196 149 ▶ if ($arraynode){
Branch: 1 branch
BranchTrueFalseTotal
if ($arraynode) { } 0 149 149
1197 0 $_[0]->[$key] = $retval;
1198 0 $_[0]->_bless_tree($_[0]->[$key]);
1199 0 return $_[0]->[$key];
1200 } else {
1201 149 $_[0]->{$key} = $retval;
1202 149 $_[0]->_bless_tree($_[0]->{$key});
1203 149 return $_[0]->{$key};
1204 }
1205 }
1206  
1207 =head1 NOTES
1208  
1209 =head2 NOTATION CONVENIENCE FEATURES
1210  
1211 In order to achieve autovivification notation shortcut, this module does not make use of perlfilter but does rather some gimmick with AUTOLOAD. Because of this, when you are using the convenience shortcut notation you cannot use all the names of public methods of this module (such I<new>, I<import>, I<run>, and others previously listed on this document) as hash keys, and you must always use hash keys composed from any Unicode char that is not a posix defined control char, ' (apostrophe) and : (colon). You can also use keys composed of only digits, but then it must not be a literal, put it in a variable. In that case the key wil be interpreted as array index or hash key depending of the type of node you are calling it upon. The total lenght of the key must be not bigger than 1024 Unicode chars, this is an artificial limit set for security purposes. You can still set/access hash branches of whatever name using the brace notation. It is nonetheless highly discouraged the usage of underscore beginning keys through brace notation, at least at the top level of response hash hierarchy, in order to avoid possible clashes with private variable members of this very module.
1212  
1213 =head2 MINIMAL REQUIREMENTS
1214  
1215 this module requires at least perl 5.10 for its usage of "defined or" // operator
1216  
1217 =head2 DEPENDENCIES
1218  
1219 JSON and Want are the only non-core module used by this one, use of JSON::XS is strongly advised for the sake of performance. JSON::XS is been loaded transparently by JSON module when installed. CGI module is a core one at the moment of writing, but deprecated and likely to be removed from core modules in next versions of Perl.
1220  
1221 =head1 SECURITY
1222  
1223 Remember to always:
1224  
1225 =over 4
1226  
1227 =item 1. use taint mode
1228  
1229 =item 2. use parametrized queries to access databases via DBI
1230  
1231 =item 3. avoid as much as possible I<qx>, I<system>, I<exec>, and so on
1232  
1233 =item 4. use SSL when you are keeping track of sessions
1234  
1235 =back
1236  
1237 =head1 HELP and development
1238  
1239 the author would be happy to receive suggestions and bug notification. If somebody would like to send code and automated tests for this module, I will be happy to integrate it.
1240 The code for this module is tracked on this L<GitHub page|https://github.com/ANSI-C/JSONP>.
1241  
1242 =head1 LICENSE
1243  
1244 This library is free software and is distributed under same terms as Perl itself.
1245  
1246 =head1 COPYRIGHT
1247  
1248 Copyright 2014-2038 by Anselmo Canfora.
1249  
1250 =cut
1251  
1252 1 1;
↑ Summary