blib/lib/JSONP.pm

filter: Statementstmt 31.4% 146 / 465 Branchbran 18.1% 44 / 242 Conditioncond 18.1% 30 / 165 MC/DCmcdc 8.6% 7 / 81 Subroutinesub 54.3% 31 / 57 Podpod 96.0% 24 / 25 totaltotal 27.2% 282 / 1035 CC 198 SCAR 67.5
CC
198
Cov
25%
run
3532.5
_merge
110.0
sendblob
42.0
CRAP 851.5
↑ 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 1 ▶ 'ne' => sub {! _compare(@_)};
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
22  
23 sub _compare {
24 12 ▶ my ($self, $other, $swap) = @_;
Subroutine _compare: called CC=8 SCAR=20.9
25 12 ▶ return 0 unless defined $other;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $other 2 10 12
26 10 my $reftype_self = reftype $self;
27 10 my $reftype_other = reftype $other;
28 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
29 10 my $j = JSON->new->canonical;
30 10 ▶ unless ($reftype_other) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($reftype_other) 4 6 10
31 4 eval{
32 4 local $SIG{'__DIE__'};
33 4 $other = JSON->new->decode($other);
34 };
35 4 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 2 4
36 }
37  
38 8 my $canonother;
39 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
40 2 $canonother = $other->serialize(0, 1);
41 } else {
42 6 $canonother = $j->encode($other);
43 }
44  
45 8 my $canonself = $self->serialize(0, 1);
46 8 return $canonself eq $canonother;
47 }
48  
49 1 our $VERSION = '2.22';
50  
51 =encoding utf8
52  
53 =head1 NAME
54  
55 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.
56  
57 =head1 SYNOPSIS
58  
59 =over 2
60  
61 =item * under CGI environment:
62  
63 You can pass the name of instance variable, skipping the I<-E<gt>new> call.
64 If you prefer, you can use I<-E<gt>new> just passing nothing in I<use>.
65  
66 use JSONP 'jsonp';
67 $jsonp->run;
68  
69 ...
70  
71 sub yoursubname
72 {
73 $j->table->fields = $sh->{NAME};
74 $j->table->data = $sh->fetchall_arrayref;
75 }
76  
77 OR
78  
79 use JSONP;
80  
81 my $j = JSONP->new;
82 $j->run;
83  
84 ...
85  
86 sub yoursubname
87 {
88 $j->table->fields = $sh->{NAME};
89 $j->table->data = $sh->fetchall_arrayref;
90 }
91  
92 =item * under mod_perl:
93  
94 You must declare the instance variable, remember to use I<local our>.
95  
96 use JSONP;
97 local our $j = JSONP->new;
98 $j->run;
99  
100 ...
101  
102 sub yoursubname
103 {
104 my $namedparam = $j->params->namedparam;
105 $j->table->fields = $sh->{NAME};
106 $j->table->data = $sh->fetchall_arrayref;
107 }
108  
109 option setting methods allow for chained calls:
110  
111 use JSONP;
112 local our $j = JSONP->new;
113 $j->aaa('your_session_sub')->login('your_login_sub')->debug->insecure->run;
114  
115 ...
116  
117 sub yoursubname
118 {
119 my $namedparam = $j->params->namedparam;
120 $j->table->fields = $sh->{NAME};
121 $j->table->data = $sh->fetchall_arrayref;
122 }
123  
124 just make sure I<run> it is the last element in chain.
125  
126 =back
127  
128 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.
129 The jQuery call:
130  
131 // note that jQuery will automatically chose a non-clashing callback name when you insert callback=? in request
132 $.getJSON(yourwebserverhost + '?req=yoursubname&firstparam=firstvalue&...&callback=?', function(data){
133 //your callback code
134 });
135  
136 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.
137  
138 you can autovivify the response hash omiting braces
139  
140 $jsonp->firstlevelhashvalue = 'I am a first level hash value';
141 $jsonp->first->second = 'I am a second level hash value';
142  
143 you can then access hash values either with or without braces notation
144  
145 $jsonp->firstlevelhashvalue = 5;
146 print $jsonp->firstlevelhashvalue; # will print 5
147  
148 it is equivalent to:
149  
150 $jsonp->{firstlevelhashvalue} = 5;
151 print $jsonp->{firstlevelhashvalue};
152  
153 you can even build a tree:
154  
155 $jsonp->first->second = 'hello!';
156 print $jsonp->first->second; # will print "hello!"
157  
158 it is the same as:
159  
160 $jsonp->{first}->{second} = 'hello!';
161 print $jsonp->{first}->{second};
162  
163 or (the perl "array rule"):
164  
165 $jsonp->{first}{second} = 'hello!';
166 print $jsonp->{first}{second};
167  
168 or even (deference ref):
169  
170 $$jsonp{first}{second} = 'hello!';
171 print $$jsonp{first}{second};
172  
173 you can insert hashes at any level of structure and they will become callable with the built-in convenience shortcut:
174  
175 my $obj = {a => 1, b => 2};
176 $jsonp->first->second = $obj;
177 print $jsonp->first->second->b; # will print 2
178 $jsonp->first->second->b = 3;
179 print $jsonp->first->second->b; # will print 3
180  
181 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:
182  
183 my $ary = [{a => 1}, 2];
184 $jsonp->first->second = $ary;
185 print $jsonp->first->second->[1]; # will print 2
186 print $jsonp->first->second->[0]->a; # will print 1
187 $jsonp->first->second->[0]->a = 9;
188 print $jsonp->first->second->[0]->a; # will print 9 now
189  
190 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:
191  
192 my $j = JSONP->new;
193 $j->firstnode->a = 5;
194 $j->firstnode->b = 9;
195 $j->secondnode->thirdnode->a = 7;
196 delete $j->secondnode->{thirdnode}; # will delete thirdnode as expected in hash structures.
197  
198 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:
199  
200 my $j = JSONP->new(
201 {
202 firstkey => 5,
203 secondkey => [1, 2, 3],
204 thirdkey => {
205 nested => \1
206 }
207 }
208 );
209  
210 my $json = '
211 {
212 "thirdkey": {"nested": true},
213 "firstkey": 5,
214 "secondkey": [1, 2, 3]
215 }
216 ';
217  
218 say $j eq $json ? 'the same' : 'different'; # will print 'the same'
219 say $j ne $json ? 'different' : 'the same'; # will print 'the same'
220 say $j eq 'a random string, not a valid JSON' ? 'the same' : 'different'; # will print 'different'
221 say $j eq '{"akey": "something"}' ? 'the same' : 'different'; # will print 'different'
222  
223 TODO: will investigate if possible to implement deletion using exclusively the convenience notation feature.
224  
225 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.
226  
227 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:
228  
229 my $j = JSONP->new;
230 $j->firstnode = 5;
231 my $branch = {};
232 $branch->{debug} = 0; # debug is a native method name
233 $branch->{serialize} = 1; # serialize is a native method name
234 $j->secondnode = $branch; # $branch structure will be grafted and relative nodes blessed accordingly
235 say $j->secondnode->{serialize}; # will print 1
236  
237 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.
238  
239 $j->graft('testbool', q|{"true": true, "false":false}|);
240 say $j->testbool->true;
241 say $j->testbool->false;
242 say !! $j->testbool->true;
243 say !! $j->testbool->false;
244  
245 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>:
246  
247 my $j = JSONP->new->debug;
248 $j->firstnode->a = 5;
249 $j->firstnode->b = 9;
250 $j->secondnode->thirdnode->a = 7;
251 my $pretty = $j->serialize; # will get a pretty print
252 my $deepser = $j->firstnode->serialize; # won't get a pretty print, because deeper than root
253 my $prettydeeper = $j->firstnode->pretty->serialize; # will get a pretty print, because we called I<pretty> first
254  
255 my $j = JSONP->new(['one', 'two', 'three']);
256 $j->serialize(1); # will get a pretty print
257 $j->serialize; # will get a normal print
258 $j->pretty->serialize; # ->pretty call will be ignored cause $j is an array, you will get a normal print
259  
260 =head1 DESCRIPTION
261  
262 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).
263 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).
264 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.
265 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.
266 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.
267  
268 =head2 METHODS
269  
270 =cut
271  
272 sub import {
273 1 ▶ my ($self, $name) = @_;
Subroutine import: called CC=4 SCAR=17.9
274 1 ▶ return if $ENV{MOD_PERL};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"MOD_PERL"} 0 1 1
275 1 ▶ return unless $name;
Branch: 1 branch
BranchTrueFalseTotal
unless $name 1 0 1
276 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
277 0 my $symbol = caller() . '::' . $name;
278 {
279 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
280 0 *$symbol = \JSONP->new;
281 }
282 }
283  
284 =head3 new
285  
286 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>.
287  
288 my $h = {
289 a => 1,
290 b => 2
291 }:
292 my $j = JSONP->new($h);
293 say $j->serialize;
294  
295 my $a = ['a', 'b', 'c'];
296 my $j = JSONP->new($a);
297 say $j->serialize;
298  
299 my $json = '{"a" : 1, "b" : 2}';
300 my $j = JSONP->new($json);
301 say $j->serialize;
302  
303 =cut
304  
305 sub new {
306 4 ▶ my ($class, $json) = @_;
Subroutine new: called CC=7 SCAR=28.7
Pod documented
307  
308 4 ▶ return bless {}, $class unless defined $json;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $json 1 3 4
309  
310 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
311 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
312 # shallow blessing to avoid constructor overhead on large data structures
313 # on-fly blessing is performed on dynamic traversal in AUTOLOAD and loop
314 3 return bless $json, $class;
315 }
316  
317 0 ▶ if ($type eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "") 0 0 0
318 0 eval{
319 0 local $SIG{'__DIE__'};
320 0 $json = JSON->new->decode($json);
321 };
322  
323 0 ▶ unless($@) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($@) 0 0 0
324 # shallow blessing to avoid constructor overhead on large data structures
325 # on-fly blessing is performed on dynamic traversal in AUTOLOAD and loop
326 0 return bless $json, $class;
327 }
328 }
329  
330 0 return 0;
331 }
332  
333 =head3 run
334  
335 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.
336  
337 =cut
338  
339 sub _auth {
340 0 ▶ my ($self, $sid, $session) = @_;
Subroutine _auth: not called CC=3 SCAR=24.8
341 0 my $authenticated = eval {
342 0 local $SIG{'__DIE__'};
343 0 $self->{_aaa_sub}->($sid, $session);
344 };
345  
346 0 ▶ if($@){
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
347 0 ▶ $self->{eval} = $@ if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 0 0
348 0 $self->raiseError('unclassified error');
349 0 $authenticated = 0;
350 }
351  
352 0 $authenticated;
353 }
354  
355 sub run {
356 0 ▶ my $self = shift;
Subroutine run: not called CC=60 SCAR=81.7
Pod documented
357 0 $self->{_is_root_element} = 1;
358 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
359 0 $self->{_authenticated} = 0;
360 0 $self->{error} = \0;
361 0 $self->errors = [];
362 0 $self->{_passthrough} = 0;
363 0 $self->{_mimetype} = 'text/html';
364 0 $self->{_html} = 0;
365 0 $self->{_mod_perl} = defined $ENV{MOD_PERL};
366 0 $self->{_jsonp_version} = $VERSION;
367 # File::Temp will remove the tempdir and its content on after request end
368 0 $self->{_tempdir} = File::Temp->newdir;
369 0 my $curdir = Cwd::cwd;
370 # Taint mode
371 0 ▶ $curdir = $curdir =~ m{(/.*)} ? $1 : '';
Branch: 1 branch
BranchTrueFalseTotal
$curdir =~ m[(/.*)] ? : 0 0 0
372 0 $self->{_curdir} = $curdir;
373 #$ENV{PATH} = '' if $self->{_taint_mode} = ${^TAINT};
374 0 ▶ die "you have to provide an AAA function" unless $self->{_aaa_sub};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_aaa_sub"} 0 0 0
375 0 my $r = CGI->new;
376 0 $$self{_cgi} = $r;
377 # this will enable us to give back the unblessed reference
378 0 my %params = $r->Vars;
379 # we assume all inputs are UTF-8, (XHR default encoding anyway) but check if params are already decoded for safety
380 0 for (keys %params) {
381 0 ▶ next if utf8::is_utf8($params{$_});
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($params{$_}) 0 0 0
382 # be wary on input UTF-8 format (use strict UTF-8 mode, not loose utf8)
383 0 $params{$_} = Encode::decode('UTF-8', $params{$_});
384 }
385 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
386 0 my $method = $r->request_method;
387 0 $self->{_request_method} = $method;
388 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
389 0 my $payload;
390 0 ▶ if($method eq 'POST'){
Branch: 2 branches
BranchTrueFalseTotal
if ($method eq 'POST') { } 0 0 0
elsif ($method eq 'PUT') { } 0 0 0
391 0 $payload = $params{POSTDATA};
392 } elsif ($method eq 'PUT'){
393 0 $payload = $params{PUTDATA};
394 } else {
395 0 $payload = '{}'; # dummy one, fallback for invalid requests
396 }
397  
398 0 my $success = $self->graft('params', $payload);
399  
400 0 ▶ unless($success){
Branch: 1 branch
BranchTrueFalseTotal
unless ($success) 0 0 0
401 0 $self->raiseError('invalid input JSON');
402 }
403  
404 } else {
405 0 $self->params = \%params;
406 }
407  
408 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
409 0 $self->params = {};
410 0 $self->raiseError('invalid input JSON type (array)');
411 }
412  
413 0 ▶ if($self->{_rest}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_rest"}) 0 0 0
414 0 my $name = $0;
415 0 $name =~ m{([^/]+)$};
416 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
417 0 $self->{params}->{req} = $name;
418 }
419  
420 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
421 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
422 0 my $sid = $r->cookie('sid');
423  
424 0 my $map = caller() . '::' . $req;
425 0 my $session = $self->_auth($sid);
426 0 $self->{_authenticated} = ! ! $session;
427 0 ▶ if($self->{_authenticated}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_authenticated'}) { } 0 0 0
428 0 ▶ $self->session = {} unless $self->graft('session', $session);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->graft("session", $session) 0 0 0
429 } else {
430 0 $self->session = {};
431 }
432  
433 0 my $isloginsub = \&$map == $self->{_login_sub};
434  
435 0 my $header = {-type => 'application/javascript', -charset => 'UTF-8'};
436 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
437 0 my $h = Digest::SHA->new(256);
438 0 my @us = gettimeofday;
439 0 ▶ $h->add(@us, map($r->http($_) , $r->http() )) if $self->{_insecure_session};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_insecure_session"} 0 0 0
440 0 ▶ $h->add(@us, map($r->https($_), $r->https())) unless $self->{_insecure_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_insecure_session"} 0 0 0
441 0 $sid = $h->hexdigest;
442 0 my $current_path = $r->url(-absolute=>1);
443 0 $current_path =~ s|/[^/]*$||;
444 my $cookie = {
445 -name => 'sid',
446 -value => $sid,
447 -path => $current_path,
448 -secure => !$self->{_insecure_session},
449 0 -httponly => 1,
450 # TODO test SameSite on IE11 on Windows 8 and Safari on MacOS X
451 #-samesite => 'Strict'
452 };
453 0 ▶ $cookie->{-expires} = "+$$self{_session_expiration}s" if $self->{_session_expiration};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_session_expiration"} 0 0 0
454 0 $header->{-cookie} = $r->cookie($cookie);
455 }
456  
457 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
458 0 eval {
459 0 local $SIG{'__DIE__'};
460 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
461 0 my $outcome = &$map($sid);
462 0 ▶ $self->{_authenticated} = $outcome if $isloginsub;
Branch: 1 branch
BranchTrueFalseTotal
if $isloginsub 0 0 0
463 };
464  
465 0 ▶ if($@){
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
466 0 ▶ $self->{eval} = $@ if $self->{_debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_debug"} 0 0 0
467 0 $self->raiseError('unclassified error');
468 }
469  
470 # save back the session only during responses to PUT and POST HTTP methods
471 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
472 # get session last changes made by concurrent requests
473 # and merge them with current session right before to
474 # pass it back to aaa sub that will save it to storage
475 # note that current session keys/values will override
476 # concurrent ones, see _merge function for details
477 0 my $concurrentSession = $self->_auth($sid);
478 0 my $thisSession = $self->session->serialize;
479 0 $self->graft('thisSession', $thisSession);
480 0 delete $self->{session};
481 0 $self->graft('session', $concurrentSession);
482 0 $self->_merge($self->session, $self->thisSession);
483 0 delete $self->{thisSession};
484 0 $self->_auth($sid, $self->session->serialize);
485 }
486  
487 } elsif (! $req) {
488 0 $self->raiseError('invalid request');
489 } else {
490 0 $self->raiseError('forbidden');
491 }
492  
493 # give a nice JSON "true"/"false" output for authentication
494 0 ▶ $self->authenticated = $self->{_authenticated} ? \1 : \0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'_authenticated'} ? : 0 0 0
495 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
496 0 $header->{"$_"} = $self->{_headers}->{$_} for keys %{$self->{_headers}};
497 0 my $callback;
498  
499 # debug
500 # my @layers = PerlIO::get_layers(select);
501  
502 0 my $ofh = select;
503 # avoid putting multiple encoding layers on STDOUT
504 0 ▶ binmode($ofh) && binmode($ofh, ':encoding(UTF-8)');
Branch: 1 branch
BranchTrueFalseTotal
binmode $ofh and binmode $ofh, ":encoding(UTF-8)" 0 0 0
505 0 ▶ unless($self->{_passthrough}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_passthrough'}) { } 0 0 0
506 0 ▶ $callback = $self->params->callback if $self->{_request_method} eq 'GET';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_request_method"} eq "GET" 0 0 0
507 0 ▶ if($callback){
Branch: 1 branch
BranchTrueFalseTotal
if ($callback) 0 0 0
508 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
509 0 ▶ $self->raiseError('invalid callback') unless $callback;
Branch: 1 branch
BranchTrueFalseTotal
unless $callback 0 0 0
510 }
511  
512 0 ▶ $self->{_mimetype} = $callback ? 'application/javascript' : 'application/json';
Branch: 1 branch
BranchTrueFalseTotal
$callback ? : 0 0 0
513 0 $header->{'-type'} = $self->{_mimetype};
514 0 print $r->header($header);
515 0 ▶ print "$callback(" if $callback;
Branch: 1 branch
BranchTrueFalseTotal
if $callback 0 0 0
516 0 print $self->serialize;
517 0 ▶ print ')' if $callback;
Branch: 1 branch
BranchTrueFalseTotal
if $callback 0 0 0
518 } else {
519 0 $header->{'-type'} = $self->{_mimetype};
520 0 ▶ $header->{'-content-length'} = $self->{_blobsize} if $self->{_blobsize};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_blobsize"} 0 0 0
521 0 ▶ if ($self->{_html}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'_html'}) { } 0 0 0
elsif ($self->{'_sendblob'}) { } 0 0 0
522 0 print $r->header($header);
523 0 print $self->{_html};
524 } elsif ($self->{_sendblob}) {
525 0 ▶ if ($self->{_inline}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_inline'}) { } 0 0 0
526 0 $header->{'-disposition'} = 'inline';
527 } else {
528 0 $header->{'-attachment'} = $self->{_blobname};
529 }
530 0 print $r->header($header);
531 0 binmode $ofh;
532 0 print $self->{_sendblob};
533 0 delete $self->{_sendblob}; # release memory ASAP
534 } else {
535 0 ▶ if ($self->{_inline}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'_inline'}) { } 0 0 0
536 0 $header->{'-disposition'} = 'inline';
537 } else {
538 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
539 }
540 0 print $r->header($header);
541 0 binmode $ofh;
542 0 print $self->_slurp($self->{_sendfile});
543 unlink $self->{_sendfile} if $self->{_delete_after_download}
544 0 ▶ }
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_delete_after_download"} 0 0 0
545 }
546  
547 # exit any eventual temp directory before it is removed by File::Temp
548 0 chdir $self->{_curdir};
549  
550 0 ▶ if($self->{_mod_perl}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_mod_perl"}) 0 0 0
551 0 my $rh = $r->r;
552 # suppress default Apache response
553 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
554 0 $rh->rflush;
555 }
556  
557 0 delete $self->{$_} for keys %$self; # force Perl to release memory in persistent environments
558  
559 0 $self;
560 }
561  
562 sub _slurp {
563 0 ▶ my ($self, $filename) = @_;
Subroutine _slurp: not called CC=3 SCAR=24.8
564 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
565 0 open my $fh, '<', $filename;
566 0 local $/;
567 0 <$fh>;
568 }
569  
570 sub _merge {
571 # merge $_[2] into $_[1]
572 # you must use params directly to make changes
573 # directly on referenced objects, otherwise
574 # perl will work on local copies of them
575  
576 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
577 0 $_[1] = $_[2];
578 0 return;
579 } # if $_[0] points to a scalar or array, $_[1] will prevail
580  
581 0 ▶ unless(scalar keys %{$_[1]}){
Branch: 1 branch
BranchTrueFalseTotal
unless (scalar keys %{$_[1];}) 0 0 0
582 0 $_[1] = $_[2];
583 0 return;
584 } # if $_[0] is an empty hash, $_[1] will prevail
585  
586 0 my @keys = keys %{$_[1]};
587 0 push @keys, keys %{$_[2]};
588 0 my $resultOK = 1;
589 0 for(@keys){
590 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
591 0 ▶ $_[1]->{$_} = defined $_[2]->{$_} ? $_[2]->{$_} : $_[1]->{$_};
Branch: 1 branch
BranchTrueFalseTotal
defined $_[2]{$_} ? : 0 0 0
592 0 next;
593 }
594 0 $_[0]->_merge($_[1]->{$_}, $_[2]->{$_});
595 }
596 }
597  
598 =head3 html
599  
600 use this method if you need to return HTML instead of JSON, pass the HTML string as argument
601  
602 yoursubname
603 {
604 ...
605 $j->html($html);
606 }
607  
608 =cut
609  
610 sub html {
611 0 ▶ my ($self, $html, $mime) = @_;
Subroutine html: not called CC=4 SCAR=30.0
Pod documented
612 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
613 0 $self->{_mimetype} = $mime;
614 0 $self->{_passthrough} = 1;
615 0 $self->{_html} = $html;
616 0 $self;
617 }
618  
619 =head3 sendblob
620  
621 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>.
622  
623 yoursubname
624 {
625 ...
626 $j->sendblob($fullfilepath, $isTmpFileToDelete);
627 }
628  
629 =cut
630  
631 sub sendblob {
632 0 ▶ my ($self, $blob, $attachmentName, $size, $inline) = @_;
Subroutine sendblob: not called CC=6 SCAR=37.4
Pod documented
633 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
634 0 $self->{_passthrough} = 1;
635 0 $self->{_mimetype} = 'application/octet-stream';
636 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
637 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
638 0 $self->{_blobsize} = 0 + $size;
639 0 $self->{_inline} = ! ! $inline;
640 0 $self;
641 }
642  
643 =head3 sendfile
644  
645 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.
646  
647 yoursubname
648 {
649 ...
650 $j->sendfile($fullfilepath, $isTmpFileToDelete);
651 }
652  
653 =cut
654  
655 sub sendfile {
656 0 ▶ my ($self, $filepath, $isTmpFileToDelete) = @_;
Subroutine sendfile: not called CC=4 SCAR=30.0
Pod documented
657 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
658 0 $self->{_passthrough} = 1;
659 0 $self->{_mimetype} = 'application/octet-stream';
660 0 $self->{_sendfile} = $filepath;
661 0 $self->{_delete_after_download} = ! ! $isTmpFileToDelete;
662 0 $self;
663 }
664  
665 =head3 file
666  
667 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.
668  
669 $j->file('path to file', $mimetype, $isInline, $isTmpFileToDelete);
670  
671 =cut
672  
673 sub file {
674 0 ▶ my ($self, $filepath, $mime, $inline, $isTmpFileToDelete) = @_;
Subroutine file: not called CC=4 SCAR=30.0
Pod documented
675 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
676 0 $self->{_passthrough} = 1;
677 0 $self->{_mimetype} = $mime;
678 0 $self->{_sendfile} = $filepath;
679 0 $self->{_inline} = ! ! $inline;
680 0 $self->{_delete_after_download} = ! ! $isTmpFileToDelete;
681 0 $self;
682 }
683  
684 =head3 debug
685  
686 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:
687  
688 $j->debug->run;
689  
690 is the same as:
691  
692 $j->debug(1)->run;
693  
694 =cut
695  
696 sub debug {
697 0 ▶ my ($self, $switch) = @_;
Subroutine debug: not called CC=4 SCAR=30.0
Pod documented
698 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
699 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
700 0 $self->{_debug} = $switch;
701 0 $self->{_pretty} = $switch;
702 0 $self;
703 }
704  
705 =head3 pretty
706  
707 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:
708  
709 $j->pretty->run;
710  
711 is the same as:
712  
713 $j->pretty(1)->run;
714  
715 =cut
716  
717 sub pretty {
718 0 ▶ my ($self, $switch) = @_;
Subroutine pretty: not called CC=4 SCAR=30.0
Pod documented
719 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
720 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
721 0 $self->{_pretty} = $switch;
722 0 $self;
723 }
724  
725 =head3 insecure
726  
727 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.
728  
729 =cut
730  
731 sub insecure {
732 0 ▶ my ($self, $switch) = @_;
Subroutine insecure: not called CC=4 SCAR=30.0
Pod documented
733 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
734 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
735 0 $self->{_insecure_session} = $switch;
736 0 $self;
737 }
738  
739 =head3 rest
740  
741 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.
742  
743 =cut
744  
745 sub rest {
746 0 ▶ my ($self, $switch) = @_;
Subroutine rest: not called CC=4 SCAR=30.0
Pod documented
747 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
748 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
749 0 $self->{_rest} = $switch;
750 0 $self;
751 }
752  
753 =head3 set_session_expiration
754  
755 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).
756  
757 =cut
758  
759 sub set_session_expiration {
760 0 ▶ my ($self, $expiration) = @_;
Subroutine set_session_expiration: not called CC=3 SCAR=24.8
Pod documented
761 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
762 0 $self->{_session_expiration} = $expiration;
763 0 $self;
764 }
765  
766 =head3 query
767  
768 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
769  
770 =cut
771  
772 # TODO remove query method, now it is useless
773 sub query {
774 0 ▶ my ($self, $param) = @_;
Subroutine query: not called CC=2 SCAR=17.9
Pod documented
775 0 ▶ $param ? $self->params->{$param} : $self->params;
Branch: 1 branch
BranchTrueFalseTotal
$param ? : 0 0 0
776 }
777  
778 =head3 plain_json
779  
780 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.>
781 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.
782  
783 =cut
784  
785 sub plain_json {
786 0 ▶ my ($self, $switch) = @_;
Subroutine plain_json: not called CC=4 SCAR=30.0
Pod documented
787 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
788 0 ▶ $switch = defined $switch ? !!$switch : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $switch ? : 0 0 0
789 0 $self->{_plain_json} = $switch;
790 0 $self;
791 }
792  
793 =head3 aaa
794  
795 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
796  
797 =cut
798  
799 sub aaa {
800 0 ▶ my ($self, $sub) = @_;
Subroutine aaa: not called CC=3 SCAR=20.3
Pod documented
801 0 ▶ if (ref $sub eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sub eq 'CODE') { } 0 0 0
802 0 $self->{_aaa_sub} = $sub;
803 }
804 else {
805 0 my $map = caller() . '::' . $sub;
806 {
807 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
808 0 ▶ die "given AAA function does not exist" unless defined &$map;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$map 0 0 0
809 0 $self->{_aaa_sub} = \&$map;
810 }
811 }
812 0 $self;
813 }
814  
815 =head3 login
816  
817 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.
818  
819 =cut
820  
821 sub login {
822 0 ▶ my ($self, $sub) = @_;
Subroutine login: not called CC=3 SCAR=20.3
Pod documented
823 0 ▶ if (ref $sub eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sub eq 'CODE') { } 0 0 0
824 0 $self->{_login_sub} = $sub;
825 }
826 else {
827 0 my $map = caller() . '::' . $sub;
828 {
829 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
830 0 ▶ die "given login function does not exist" unless defined &$map;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$map 0 0 0
831 0 $self->{_login_sub} = \&$map;
832 }
833 }
834 0 $self;
835 }
836  
837 =head3 logout
838  
839 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).
840  
841 =cut
842  
843 sub logout {
844 0 ▶ my ($self, $sub) = @_;
Subroutine logout: not called CC=3 SCAR=20.3
Pod documented
845 0 ▶ if (ref $sub eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $sub eq 'CODE') { } 0 0 0
846 0 $self->{_logout_sub} = $sub;
847 }
848 else {
849 0 my $map = caller() . '::' . $sub;
850 {
851 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.2
852 0 ▶ die "given logout function does not exist" unless defined &$map;
Branch: 1 branch
BranchTrueFalseTotal
unless defined &$map 0 0 0
853 0 $self->{_logout_sub} = \&$map;
854 }
855 }
856 0 $self;
857 }
858  
859 =head3 raiseError
860  
861 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.
862  
863 =cut
864  
865 sub raiseError {
866 2 ▶ my ($self, $message, $code, $customHeaders) = @_;
Subroutine raiseError: called CC=7 SCAR=19.7
Pod documented
867 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
868 2 $self->error = \1;
869 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
870 2 ▶ $self->{_status_code} = $code if defined $code;
Branch: 1 branch
BranchTrueFalseTotal
if defined $code 1 1 2
871 2 ▶ $self->{_headers} = $customHeaders if defined $customHeaders;
Branch: 1 branch
BranchTrueFalseTotal
if defined $customHeaders 0 2 2
872  
873 2 $self;
874 }
875  
876 =head3 graft
877  
878 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:
879 $j->subtree->graft('newbranchname', '{"name" : "JSON object", "count" : 2}');
880 print $j->subtree->newbranchname->name; # will print "JSON object"
881 $j->sublist->graft->('newbranchname', '[{"name" : "first one"}, {"name" : "second one"}]');
882 print $j->sublist->newbranchname->[1]->name; will print "second one"
883 my $index = 1; print $j->sublist->newbranchname->$index->name; will print "second one" as well
884  
885 This method will return the reference to the newly added element if added successfully, a false value otherwise.
886  
887 =cut
888  
889 sub graft {
890 0 ▶ my ($self, $name, $json) = @_;
Subroutine graft: not called CC=4 SCAR=30.0
Pod documented
891  
892 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
893  
894 0 eval{
895 0 local $SIG{'__DIE__'};
896 0 $self->{$name} = JSON->new->decode($json);
897 };
898  
899 0 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
900  
901 #_bless_tree returns the node passed to it blessed as JSONP
902 0 $self->_bless_tree($self->{$name});
903 }
904  
905 =head3 stack
906  
907 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:
908  
909 $j->first->second = [{a => 1}, {b = 2}];
910 $j->first->second->stack('{"c":"3"}');
911 say $j->first->second->[2]->c; # will print 3;
912 my $index = 2; say $j->first->second->$index->c; # will print 3 as well
913  
914 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:
915  
916 my $j = JSONP->new;
917 $j->firstnode->graft('secondnode', '{"a" : 1}')->thirdnode = [];
918 $j->firstnode->secondnode->thirdnode->stack('{"b" : 9}')->fourthnode = 10;
919 say $j->firstnode->secondnode->a; # will print 1
920 say $j->firstnode->secondnode->thirdnode->[0]->b; # will print 9
921 say $j->firstnode->secondnode->thirdnode->[0]->fourthnode; # will print 10
922 my $index = 0; say $j->firstnode->secondnode->thirdnode->$index->fourthnode; # will print 10 as well
923  
924 =cut
925  
926 sub stack {
927 0 ▶ my ($self, $json) = @_;
Subroutine stack: not called CC=4 SCAR=30.0
Pod documented
928  
929 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
930  
931 0 eval{
932 0 local $SIG{'__DIE__'};
933 0 push @$self, JSON->new->decode($json);
934 };
935 0 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
936  
937 #_bless_tree returns the node passed to it blessed as JSONP
938 0 $self->_bless_tree($self->[$#{$self}]);
939 }
940  
941 =head3 append
942  
943 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:
944  
945 $j->first->second = [{a => 1}, {b = 2}];
946 $j->first->second->append({c => 3});
947 say $j->first->second->[2]->c; # will print 3;
948  
949 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:
950  
951 my $j = JSONP->new;
952 $j->firstnode->secondnode->a = 1;
953 $j->firstnode->secondnode->thirdnode = [];
954 $j->firstnode->secondnode->thirdnode->append({b => 9})->fourthnode = 10;
955 say $j->firstnode->secondnode->a; # will print 1
956 say $j->firstnode->secondnode->thirdnode->[0]->b; # will print 9
957 say $j->firstnode->secondnode->thirdnode->[0]->fourthnode; # will print 10
958  
959 =cut
960  
961 sub append {
962 0 ▶ my ($self, $el) = @_;
Subroutine append: not called CC=3 SCAR=24.8
Pod documented
963  
964 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
965  
966 0 push @$self, $el;
967  
968 #_bless_tree returns the node passed to it blessed as JSONP
969 0 $self->_bless_tree($self->[$#{$self}]);
970 }
971  
972 =head3 loop
973  
974 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>
975 or copy its value to perform calculation with a copy. Returning the reference assure that loops over arrays items that evaluate as false
976 won't stop until actual array end.
977 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.
978 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.
979 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.
980 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.
981  
982 my $j = JSONP->new;
983 $j->an->array = [
984 [11, 12],
985 [21, 22]
986 ];
987  
988 say $j->an->pretty->serialize;
989  
990 while (my $row = $j->an->array->loop) {
991 while (my $field = $$row->loop){
992 my $acopy = $$field;
993 $$field++;
994 }
995 }
996  
997 say $j->an->pretty->serialize;
998  
999 =cut
1000  
1001 sub loop {
1002 0 ▶ my ($self) = @_;
Subroutine loop: not called CC=6 SCAR=37.4
Pod documented
1003 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
1004 0 my $class = ref $self; # bless in cases we have not a deep recursive blessing
1005 0 ▶ return undef unless $refself eq 'ARRAY'; ## no critic
Branch: 1 branch
BranchTrueFalseTotal
unless $refself eq "ARRAY" 0 0 0
1006 # use different counter for every array
1007 0 state $indexes = {};
1008 0 my $addr = 0 + $self;
1009 0 my $index = $indexes->{$addr};
1010 0 $index += 0;
1011 # array can change during loop
1012 0 my $size = @$self;
1013  
1014 0 ▶ if ($index < $size){
Branch: 1 branch
BranchTrueFalseTotal
if ($index < $size) { } 0 0 0
1015 # refs are never undef so we can loop
1016 # over false scalar items as well
1017 0 my $item = $self->[$indexes->{$addr}++];
1018 0 my $reftype = ref $item;
1019 # bless the item if it is an unblessed hash or array reference (avoid to touch blessed objects)
1020 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
1021 0 return \$item;
1022 } else {
1023 # reset counter for next loops
1024 # and avoid memory leaks...
1025 # note that the loops exited with "last"
1026 # will leak few bytes until program end,
1027 # with about 8 bytes per loop it's safe
1028 0 delete $indexes->{$addr};
1029 0 return undef; ## no critic
1030 }
1031 }
1032  
1033 =head3 serialize
1034  
1035 call this method to serialize and output a subtree:
1036  
1037 $j->subtree->graft('newbranchname', '{"name" : "JSON object", "count" : 2}');
1038 print $j->subtree->newbranchname->name; # will print "JSON object"
1039 $j->sublist->graft->('newbranchname', '[{"name" : "first one"}, {"name" : "second one"}]');
1040 print $j->sublist->newbranchname->[1]->name; will print "second one"
1041 $j->subtree->newbranchname->graft('subtree', '{"name" : "some string", "count" : 4}');
1042 print $j->subtree->newbranchname->subtree->serialize; # will print '{"name" : "some string", "count" : 4}'
1043  
1044 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:
1045  
1046 $j = JSONP->new(['one', 'two', 'three']);
1047 print $j->serialize(1);
1048  
1049 IMPORTANT NOTE: do not assign any reference to a sub to any node, example:
1050  
1051 $j->donotthis = sub { ... };
1052  
1053 for now the module does assume that nodes/leafs will be scalars/hashes/arrays, so same thing is valid for filehandles.
1054  
1055 =cut
1056  
1057 sub serialize {
1058 10 ▶ my ($self, $prettyoverride, $canonical) = @_;
Subroutine serialize: called CC=7 SCAR=21.3
Pod documented
1059 10 $canonical = !! $canonical;
1060 # $prettyoverride to be used with ARRAY objects where we cannot have _pretty member
1061 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
1062 10 my $out;
1063 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
1064 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
1065  
1066 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
1067 10 local $SIG{'__DIE__'};
1068 10 $out = JSON->new->canonical($canonical)->pretty($pretty)->allow_unknown->allow_blessed->convert_blessed->encode($self);
1069 } || $@;
1070 }
1071  
1072 =head3 tempdir
1073  
1074 returns a temporary directory whose content will be removed at the request end.
1075 if you pass a relative path, it will be created under the random tmp directory.
1076 if creation fails, a boolean false will be retured (void string).
1077  
1078 my $path = $j->tempdir; # will return something like /tmp/systemd-private-af123/tmp/nRmseALe8H
1079 my $path = $j->tempdir('DIRNAME'); # will return something like /tmp/systemd-private-af123/tmp/nRmseALe8H/DIRNAME
1080  
1081 =cut
1082  
1083 sub tempdir {
1084 0 ▶ my ($self, $path) = @_;
Subroutine tempdir: not called CC=5 SCAR=34.0
Pod documented
1085 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
1086 0 ▶ return $self->{_tempdir}->dirname unless $path;
Branch: 1 branch
BranchTrueFalseTotal
unless $path 0 0 0
1087 0 return $self->_makePath($path);
1088 }
1089  
1090 =head3 ctwd
1091  
1092 changes current working directory to a random temporary directory whose content will be removed at the request end.
1093 if you pass a path, it will be appended to the temporary directory before cwd'ing on it, bool outcome will be returned.
1094 if creation fails, a boolean false will be returned (void string).
1095  
1096 my $cwdOK = $j->ctwd;
1097  
1098 =cut
1099  
1100 sub ctwd {
1101 0 ▶ my ($self, $path) = @_;
Subroutine ctwd: not called CC=6 SCAR=37.4
Pod documented
1102 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
1103 0 ▶ return chdir $self->{_tempdir} unless $path;
Branch: 1 branch
BranchTrueFalseTotal
unless $path 0 0 0
1104 0 $path = $self->_makePath($path);
1105 0 ▶ return $path ? chdir $path : '';
Branch: 1 branch
BranchTrueFalseTotal
$path ? : 0 0 0
1106 }
1107  
1108 sub _makePath {
1109 0 ▶ my ($self, $path) = @_;
Subroutine _makePath: not called CC=6 SCAR=37.4
1110 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
1111 0 my $mkdirerr;
1112 0 $path = "$$self{_tempdir}/$path";
1113 0 File::Path::make_path($path, {error => \$mkdirerr});
1114 0 ▶ if(@$mkdirerr){
Branch: 1 branch
BranchTrueFalseTotal
if (@$mkdirerr) 0 0 0
1115 0 for my $direrr (@$mkdirerr){
1116 0 my ($curdir, $curmessage) = %$direrr;
1117 0 say STDERR "error while attempting to create $curdir: $curmessage";
1118 }
1119  
1120 # if creation fails set $path to a "false" string
1121 0 $path = '';
1122 }
1123  
1124 0 $path;
1125 }
1126  
1127 sub _bless_tree {
1128 183 ▶ my ($self, $node) = @_;
Subroutine _bless_tree: called CC=8 SCAR=20.8
1129 183 my $class = ref $self;
1130 183 my $refnode = ref $node;
1131 # proceed only with hashes or arrays not already blessed
1132 183 ▶ return $node if $refnode eq $class;
Branch: 1 branch
BranchTrueFalseTotal
if $refnode eq $class 93 90 183
1133 #my $reftype = reftype($node) // '';
1134 #return unless $reftype eq 'HASH' || $reftype eq 'ARRAY';
1135 # to not change class to objects grafted to JSONP tree
1136 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
1137 25 bless $node, $class;
1138 25 ▶ if ($refnode eq 'HASH'){
Branch: 1 branch
BranchTrueFalseTotal
if ($refnode eq "HASH") 17 8 25
1139 17 $self->_bless_tree($node->{$_}) for keys %$node;
1140 }
1141 25 ▶ if ($refnode eq 'ARRAY'){
Branch: 1 branch
BranchTrueFalseTotal
if ($refnode eq "ARRAY") 8 17 25
1142 8 $self->_bless_tree($_) for @$node;
1143 }
1144 25 $node;
1145 }
1146  
1147 sub TO_JSON {
1148 10 ▶ my $self = shift;
Subroutine TO_JSON: called CC=11 SCAR=30.1
Pod undocumented
1149 10 my $output;
1150  
1151 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
1152  
1153 8 $output = {};
1154 8 for(keys %$self){
1155 24 my $skip = 0;
1156  
1157 24 ▶ unless($self->{_debug}){
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_debug"}) 24 0 24
1158 24 ▶ if($self->{_is_root_element}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_is_root_element"}) 0 24 24
1159 0 ▶ $skip++ if $_ =~ /_sub$/;
Branch: 1 branch
BranchTrueFalseTotal
if $_ =~ /_sub$/ 0 0 0
1160 0 ▶ $skip++ if $_ eq 'session';
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq "session" 0 0 0
1161 0 ▶ $skip++ if $_ eq 'params';
Branch: 1 branch
BranchTrueFalseTotal
if $_ eq "params" 0 0 0
1162 }
1163 24 ▶ $skip++ if $_ =~ /^_/;
Branch: 1 branch
BranchTrueFalseTotal
if $_ =~ /^_/ 0 24 24
1164 }
1165  
1166 24 ▶ next if $skip;
Branch: 1 branch
BranchTrueFalseTotal
if $skip 0 24 24
1167  
1168 24 $output->{$_} = $self->{$_};
1169 }
1170 8 return $output;
1171 }
1172  
1173 # avoid calling AUTOLOAD on destroy
1174 ▶sub DESTROY{}
Subroutine DESTROY: not called CC=1 SCAR=0.0
1175  
1176 sub AUTOLOAD : lvalue {
1177 149 ▶ my $classname = ref $_[0];
Subroutine AUTOLOAD: called CC=16 SCAR=32.8
1178 149 my $validname = q{[^:'[:cntrl:]]{0,1024}};
1179 149 our $AUTOLOAD =~ /^${classname}::($validname)$/;
1180 149 my $key = $1;
1181 149 ▶ die "illegal key name, must be of $validname form\n$AUTOLOAD" unless $key;
Branch: 1 branch
BranchTrueFalseTotal
unless $key 0 149 149
1182 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
1183 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
1184 149 ▶ my $miss = want('OBJECT') ? {} : undef;
Branch: 1 branch
BranchTrueFalseTotal
want('OBJECT') ? : 86 63 149
1185 149 ▶ my $retval = $arraynode ? $_[0]->[$key] : $_[0]->{$key}; # can be undef
Branch: 1 branch
BranchTrueFalseTotal
$arraynode ? : 0 149 149
1186 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
1187 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
1188 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
1189  
1190 149 ▶ if ($arraynode){
Branch: 1 branch
BranchTrueFalseTotal
if ($arraynode) { } 0 149 149
1191 0 $_[0]->[$key] = $retval;
1192 0 $_[0]->_bless_tree($_[0]->[$key]);
1193 0 return $_[0]->[$key];
1194 } else {
1195 149 $_[0]->{$key} = $retval;
1196 149 $_[0]->_bless_tree($_[0]->{$key});
1197 149 return $_[0]->{$key};
1198 }
1199 }
1200  
1201 =head1 NOTES
1202  
1203 =head2 NOTATION CONVENIENCE FEATURES
1204  
1205 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.
1206  
1207 =head2 MINIMAL REQUIREMENTS
1208  
1209 this module requires at least perl 5.10 for its usage of "defined or" // operator
1210  
1211 =head2 DEPENDENCIES
1212  
1213 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.
1214  
1215 =head1 SECURITY
1216  
1217 Remember to always:
1218  
1219 =over 4
1220  
1221 =item 1. use taint mode
1222  
1223 =item 2. use parametrized queries to access databases via DBI
1224  
1225 =item 3. avoid as much as possible I<qx>, I<system>, I<exec>, and so on
1226  
1227 =item 4. use SSL when you are keeping track of sessions
1228  
1229 =back
1230  
1231 =head1 HELP and development
1232  
1233 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.
1234 The code for this module is tracked on this L<GitHub page|https://github.com/ANSI-C/JSONP>.
1235  
1236 =head1 LICENSE
1237  
1238 This library is free software and is distributed under same terms as Perl itself.
1239  
1240 =head1 COPYRIGHT
1241  
1242 Copyright 2014-2038 by Anselmo Canfora.
1243  
1244 =cut
1245  
1246 1 1;
↑ Summary