lib/PSGI/Handy.pm

filter: Statementstmt 87.3% 433 / 496 Branchbran 64.2% 140 / 218 Conditioncond 50.7% 32 / 63 MC/DCmcdc 28.2% 11 / 39 Subroutinesub 81.3% 74 / 91 Podpod 3.1% 2 / 64 totaltotal 71.2% 692 / 971 CC 144 SCAR 16.7
CC
144
Cov
78%
_dispatch
16.3
render
11.5
cookie
11.1
CRAP 5.3
↑ Summary
1 package PSGI::Handy;
2 ######################################################################
3 #
4 # PSGI::Handy - a tiny dependency-free PSGI web framework for Perl 5.005_03+
5 #
6 # A single-file micro framework: a router, request/response objects and
7 # a per-request context are wired into one PSGI-subset application via
8 # to_app(). Templates (HP::Handy) and a database handle (DB::Handy) are
9 # injected, keeping this layer decoupled and testable.
10 #
11 # All component classes (PSGI::Handy::Response, ::Request, ::Router and
12 # ::Context) live in THIS file; there are no separate PSGI/Handy/*.pm
13 # files. They are laid out below in dependency order. This module loads
14 # nothing outside the Perl core.
15 #
16 # 5.005_03 safe: no //, say, state, our, 3-arg open, lexical FH, and no
17 # named regex captures anywhere in the distribution.
18 #
19 ######################################################################
20 4 ▶use 5.00503; # Universal Consensus 1998 for primetools
Subroutine BEGIN: called CC=1 SCAR=0.0
21 # Perl 5.005_03 compatibility for historical toolchains
22 # use 5.008001; # Lancaster Consensus 2013 for toolchains
23  
24 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 0 ▶BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
Subroutine BEGIN: called CC=3 SCAR=16.5
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.006" and not defined &warnings::import) 0 4 4
Condition33%1/3
$] < "5.006" and not defined &warnings::import
!ll&&!rl&&r
400
MC/DC0%0/2
$] < "5.006" and not defined &warnings::import
$] < "5.006" not defined &warnings::import
Truth table33%1/3
A and not(B)
A= $] < "5.006"B= not defined &warnings::import
ABresult
0X0
100
111
26 4 ▶use warnings; local $^W = 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 4 ▶BEGIN { pop @INC if $INC[-1] eq '.' }
Subroutine BEGIN: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $INC[-1] eq "." 0 4 4
28 4 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
29 4 $VERSION = '0.01';
30 4 $VERSION = $VERSION;
31 # $VERSION self-assignment suppresses "used only once" warning under strict.
32 4 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
33 # croak() is called as Carp::croak() throughout so that one "use Carp"
34 # serves every package in this single file (a bareword croak would only
35 # be imported into the package current at the point of "use Carp").
36  
37 ######################################################################
38 # PSGI::Handy::Response - tiny PSGI response builder
39 #
40 # Builds the PSGI three-element response [ $status, \@headers, \@body ]
41 # with an incremental, chainable API plus class shortcuts for the common
42 # response types (text, html, json, redirect).
43 ######################################################################
44 package PSGI::Handy::Response;
45  
46 # Byte-accurate length for Content-Length. The bytes pragma does not exist
47 # on Perl 5.005_03 (and there are no wide-character strings there), so we
48 # probe for it once and call bytes::length() as a function (no lexical
49 # pragma needed) on Perls that have it.
50 4 my $HAS_BYTES;
51 4 ▶BEGIN { $HAS_BYTES = eval { require bytes; 1 } ? 1 : 0; }
Subroutine BEGIN: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require bytes; 1 } } ? : 4 0 4
52  
53 22 ▶sub _byte_length {
Subroutine _byte_length: called CC=3 SCAR=11.7
54 22 my ($s) = @_;
55 22 ▶ return 0 unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 22 22
56 22 ▶ return $HAS_BYTES ? bytes::length($s) : length($s);
Branch: 1 branch
BranchTrueFalseTotal
$HAS_BYTES ? : 22 0 22
57 }
58  
59 # Strip CR/LF from header keys and values to prevent header injection.
60 62 ▶sub _crlf_safe {
Subroutine _crlf_safe: called CC=2 SCAR=7.0
61 62 my ($s) = @_;
62 62 ▶ return $s unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 62 62
63 62 $s =~ s/[\r\n]//g;
64 62 return $s;
65 }
66  
67 # --------------------------------------------------------------------
68 # new(%args) - status => 200, type => 'text/html; charset=utf-8',
69 # body => $scalar_or_arrayref
70 # --------------------------------------------------------------------
71 24 ▶sub new {
Subroutine new: called CC=3 SCAR=11.0
Pod undocumented
72 24 my ($class, %args) = @_;
73 my $self = {
74 status => (defined $args{status} ? $args{status} : 200),
75 headers => [], # list of [ key, value ]
76 24 ▶ body => _body_to_array($args{body}),
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'status'} ? : 21 3 24
77 };
78 24 bless $self, $class;
79 24 ▶ $self->set_header('Content-Type', $args{type}) if defined $args{type};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"type"} 21 3 24
80 24 return $self;
81 }
82  
83 # --- class shortcuts (return a Response object) ---------------------
84 7 ▶sub html {
Subroutine html: called CC=2 SCAR=7.2
Pod undocumented
85 7 my ($class, $str, $code) = @_;
86 7 ▶ return $class->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $code ? : 0 7 7
87 status => (defined $code ? $code : 200),
88 type => 'text/html; charset=utf-8',
89 body => $str,
90 );
91 }
92  
93 11 ▶sub text {
Subroutine text: called CC=2 SCAR=6.9
Pod undocumented
94 11 my ($class, $str, $code) = @_;
95 11 ▶ return $class->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $code ? : 7 4 11
96 status => (defined $code ? $code : 200),
97 type => 'text/plain; charset=utf-8',
98 body => $str,
99 );
100 }
101  
102 # JSON string must already be encoded by the caller (e.g. via mb::JSON).
103 2 ▶sub json {
Subroutine json: called CC=3 SCAR=11.1
Pod undocumented
104 2 my ($class, $str, $code) = @_;
105 2 ▶ !ref($str)
Branch: 1 branch
BranchTrueFalseTotal
ref $str and Carp::croak("json: body must be a pre-encoded JSON string, not a reference") 1 1 2
106 or Carp::croak "json: body must be a pre-encoded JSON string, not a reference";
107 1 ▶ return $class->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $code ? : 0 1 1
108 status => (defined $code ? $code : 200),
109 type => 'application/json',
110 body => $str,
111 );
112 }
113  
114 2 ▶sub redirect {
Subroutine redirect: called CC=3 SCAR=11.3
Pod undocumented
115 2 my ($class, $location, $code) = @_;
116 2 ▶ defined $location or Carp::croak "redirect: location is required";
Branch: 1 branch
BranchTrueFalseTotal
defined $location or Carp::croak("redirect: location is required") 2 0 2
117 2 ▶ my $self = $class->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $code ? : 0 2 2
118 status => (defined $code ? $code : 302),
119 type => 'text/plain; charset=utf-8',
120 body => "Redirect to $location",
121 );
122 2 $self->set_header('Location', $location);
123 2 return $self;
124 }
125  
126 # --- accessors / mutators (mutators return $self for chaining) ------
127 0 ▶sub status {
Subroutine status: not called CC=1 SCAR=6.9
Pod undocumented
128 0 my $self = shift;
129 0 return $self->{status};
130 }
131  
132 1 ▶sub set_status {
Subroutine set_status: called CC=1 SCAR=0.0
Pod undocumented
133 1 my ($self, $code) = @_;
134 1 $self->{status} = $code;
135 1 return $self;
136 }
137  
138 0 ▶sub body {
Subroutine body: not called CC=1 SCAR=6.9
Pod undocumented
139 0 my $self = shift;
140 0 return $self->{body};
141 }
142  
143 1 ▶sub set_body {
Subroutine set_body: called CC=1 SCAR=0.0
Pod undocumented
144 1 my ($self, $content) = @_;
145 1 $self->{body} = _body_to_array($content);
146 1 return $self;
147 }
148  
149 # Append a header (allows duplicates, e.g. several Set-Cookie lines).
150 2 ▶sub header {
Subroutine header: called CC=1 SCAR=0.0
Pod undocumented
151 2 my ($self, $key, $value) = @_;
152 2 push @{ $self->{headers} }, [ _crlf_safe($key), _crlf_safe($value) ];
153 2 return $self;
154 }
155  
156 # Replace any existing header(s) of this name, then set it.
157 29 ▶sub set_header {
Subroutine set_header: called CC=1 SCAR=0.0
Pod undocumented
158 29 my ($self, $key, $value) = @_;
159 29 $key = _crlf_safe($key);
160 29 $value = _crlf_safe($value);
161 29 my $lc = lc($key);
162 29 my @kept = grep { lc($_->[0]) ne $lc } @{ $self->{headers} };
163 29 push @kept, [ $key, $value ];
164 29 $self->{headers} = [ @kept ];
165 29 return $self;
166 }
167  
168 0 ▶sub remove_header {
Subroutine remove_header: not called CC=1 SCAR=6.9
Pod undocumented
169 0 my ($self, $key) = @_;
170 0 my $lc = lc($key);
171 0 $self->{headers} = [ grep { lc($_->[0]) ne $lc } @{ $self->{headers} } ];
172 0 return $self;
173 }
174  
175 1 ▶sub content_type {
Subroutine content_type: called CC=1 SCAR=0.0
Pod undocumented
176 1 my ($self, $type) = @_;
177 1 return $self->set_header('Content-Type', $type);
178 }
179  
180 # Add a Set-Cookie header. %opts: path, domain, max_age, expires,
181 # secure (bool), httponly (bool).
182 1 ▶sub cookie {
Subroutine cookie: called CC=9 SCAR=24.1
Pod undocumented
183 1 my ($self, $name, $value, %opts) = @_;
184 1 ▶ defined $name or Carp::croak "cookie: name is required";
Branch: 1 branch
BranchTrueFalseTotal
defined $name or Carp::croak("cookie: name is required") 1 0 1
185 1 ▶ $value = '' unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 1 1
186 1 my $c = $name . '=' . _cookie_encode($value);
187 1 ▶ $c .= '; Path=' . $opts{path} if defined $opts{path};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"path"} 1 0 1
188 1 ▶ $c .= '; Domain=' . $opts{domain} if defined $opts{domain};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"domain"} 0 1 1
189 1 ▶ $c .= '; Max-Age=' . $opts{max_age} if defined $opts{max_age};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"max_age"} 0 1 1
190 1 ▶ $c .= '; Expires=' . $opts{expires} if defined $opts{expires};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"expires"} 0 1 1
191 1 ▶ $c .= '; Secure' if $opts{secure};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"secure"} 0 1 1
192 1 ▶ $c .= '; HttpOnly' if $opts{httponly};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"httponly"} 0 1 1
193 1 return $self->header('Set-Cookie', $c);
194 }
195  
196 # --------------------------------------------------------------------
197 # finalize - produce the PSGI array [ $status, \@flat_headers, \@body ]
198 # Content-Length is computed from the body unless already present.
199 # --------------------------------------------------------------------
200 24 ▶sub finalize {
Subroutine finalize: called CC=5 SCAR=16.1
Pod undocumented
201 24 my $self = shift;
202 24 my @flat;
203 24 my $has_length = 0;
204 24 my $pair;
205 24 for $pair (@{ $self->{headers} }) {
206 30 push @flat, $pair->[0], $pair->[1];
207 30 ▶ $has_length = 1 if lc($pair->[0]) eq 'content-length';
Branch: 1 branch
BranchTrueFalseTotal
if lc $pair->[0] eq "content-length" 0 30 30
208 }
209 24 ▶ unless ($has_length) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_length) 24 0 24
210 24 my $len = 0;
211 24 my $chunk;
212 24 for $chunk (@{ $self->{body} }) {
213 22 $len += _byte_length($chunk);
214 }
215 24 push @flat, 'Content-Length', $len;
216 }
217 24 return [ $self->{status}, \@flat, [ @{ $self->{body} } ] ];
218 }
219  
220 # --- internals ------------------------------------------------------
221 25 ▶sub _body_to_array {
Subroutine _body_to_array: called CC=3 SCAR=11.0
222 25 my ($content) = @_;
223 25 ▶ return [] unless defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 3 22 25
224 22 ▶ return [ @$content ] if ref($content) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $content eq "ARRAY" 0 22 22
225 22 return [ $content ];
226 }
227  
228 1 ▶sub _cookie_encode {
Subroutine _cookie_encode: called CC=1 SCAR=0.0
229 1 my ($s) = @_;
230 1 $s =~ s/([^A-Za-z0-9_\-.~])/sprintf('%%%02X', ord($1))/eg;
231 1 return $s;
232 }
233  
234 ######################################################################
235 # PSGI::Handy::Request - tiny PSGI env wrapper
236 #
237 # Wraps a PSGI %env and exposes method, path, query/body parameters
238 # (merged), headers, cookies and the raw body. Query- and body-parameter
239 # parsing and percent-decoding are implemented here in pure Perl.
240 ######################################################################
241 package PSGI::Handy::Request;
242  
243 # --------------------------------------------------------------------
244 # new($env) - wrap a PSGI environment hash reference
245 # --------------------------------------------------------------------
246 28 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod undocumented
247 28 my ($class, $env) = @_;
248 28 ▶ ref($env) eq 'HASH' or Carp::croak "new: a PSGI env hash reference is required";
Branch: 1 branch
BranchTrueFalseTotal
ref $env eq "HASH" or Carp::croak("new: a PSGI env hash reference is required") 28 0 28
249 28 my $self = { env => $env };
250 28 return bless $self, $class;
251 }
252  
253 # --- request line -----------------------------------------------------
254 25 ▶sub method {
Subroutine method: called CC=2 SCAR=7.1
Pod undocumented
255 25 my $self = shift;
256 25 my $m = $self->{env}{REQUEST_METHOD};
257 25 ▶ return defined $m ? $m : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $m ? : 25 0 25
258 }
259  
260 19 ▶sub path {
Subroutine path: called CC=2 SCAR=7.1
Pod undocumented
261 19 my $self = shift;
262 19 my $p = $self->{env}{PATH_INFO};
263 19 ▶ return defined $p ? $p : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $p ? : 19 0 19
264 }
265  
266 7 ▶sub query_string {
Subroutine query_string: called CC=2 SCAR=7.1
Pod undocumented
267 7 my $self = shift;
268 7 my $q = $self->{env}{QUERY_STRING};
269 7 ▶ return defined $q ? $q : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $q ? : 7 0 7
270 }
271  
272 7 ▶sub content_type {
Subroutine content_type: called CC=2 SCAR=7.1
Pod undocumented
273 7 my $self = shift;
274 7 my $t = $self->{env}{CONTENT_TYPE};
275 7 ▶ return defined $t ? $t : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $t ? : 7 0 7
276 }
277  
278 4 ▶sub content_length {
Subroutine content_length: called CC=3 SCAR=12.5
Pod undocumented
279 4 my $self = shift;
280 4 my $l = $self->{env}{CONTENT_LENGTH};
281 4 ▶ return (defined $l && $l ne '') ? int($l) : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $l && $l ne '' ? : 4 0 4
Condition33%1/3
defined $l and $l ne ""
!ll&&!rl&&r
004
MC/DC0%0/2
defined $l and $l ne ""
defined $l $l ne ""
Truth table33%1/3
A and B
A= defined $lB= $l ne ""
ABresult
0X0
100
111
282 }
283  
284 0 ▶sub env {
Subroutine env: not called CC=1 SCAR=6.9
Pod undocumented
285 0 my $self = shift;
286 0 return $self->{env};
287 }
288  
289 # --- headers ----------------------------------------------------------
290 # Accepts 'Content-Type', 'content_type', 'X-Forwarded-For', etc.
291 2 ▶sub header {
Subroutine header: called CC=4 SCAR=14.0
Pod undocumented
292 2 my ($self, $name) = @_;
293 2 ▶ return undef unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 2 2
294 2 my $key = uc($name);
295 2 $key =~ s/-/_/g;
296 2 ▶ if ($key eq 'CONTENT_TYPE' || $key eq 'CONTENT_LENGTH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "CONTENT_TYPE" or $key eq "CONTENT_LENGTH") 1 1 2
Condition66%2/3
$key eq "CONTENT_TYPE" or $key eq "CONTENT_LENGTH"
l!l&&r!l&&!r
101
MC/DC50%1/2
$key eq "CONTENT_TYPE" or $key eq "CONTENT_LENGTH"
$key eq "CONTENT_TYPE" $key eq "CONTENT_LENGTH"
Truth table66%2/3
A or B
A= $key eq "CONTENT_TYPE"B= $key eq "CONTENT_LENGTH"
ABresult
1X1
011
000
297 1 return $self->{env}{$key};
298 }
299 1 return $self->{env}{'HTTP_' . $key};
300 }
301  
302 # --- raw body (read once from psgi.input, then cached) ---------------
303 4 ▶sub body {
Subroutine body: called CC=6 SCAR=18.3
Pod undocumented
304 4 my $self = shift;
305 4 ▶ return $self->{_body} if exists $self->{_body};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"_body"} 0 4 4
306 4 my $buf = '';
307 4 my $len = $self->content_length;
308 4 my $input = $self->{env}{'psgi.input'};
309 4 ▶ if ($len > 0 && $input) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len > 0 and $input) 4 0 4
Condition33%1/3
$len > 0 and $input
!ll&&!rl&&r
004
MC/DC0%0/2
$len > 0 and $input
$len > 0 $input
Truth table33%1/3
A and B
A= $len > 0B= $input
ABresult
0X0
100
111
310 # psgi.input->read may return fewer bytes than requested, so loop
311 # until CONTENT_LENGTH bytes are read or the stream ends.
312 4 my $chunk;
313 4 my $got = 0;
314 4 ▶ while ($got < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($got < $len) 4 4 8
315 4 my $n = $input->read($chunk, $len - $got);
316 4 ▶ last unless $n; # EOF or error: keep what we have
Branch: 1 branch
BranchTrueFalseTotal
unless $n 0 4 4
317 4 $buf .= $chunk;
318 4 $got += $n;
319 }
320 }
321 4 $self->{_body} = $buf;
322 4 return $buf;
323 }
324  
325 # --- parameters (query string merged with urlencoded body) -----------
326 9 ▶sub param {
Subroutine param: called CC=3 SCAR=11.0
Pod undocumented
327 9 my ($self, $name) = @_;
328 9 $self->_build_params;
329 9 ▶ return undef unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 9 9
330 9 my $v = $self->{_params}{$name};
331 9 ▶ return undef unless $v;
Branch: 1 branch
BranchTrueFalseTotal
unless $v 1 8 9
332 8 return $v->[0];
333 }
334  
335 1 ▶sub param_all {
Subroutine param_all: called CC=3 SCAR=11.2
Pod undocumented
336 1 my ($self, $name) = @_;
337 1 $self->_build_params;
338 1 ▶ return () unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 1 1
339 1 my $v = $self->{_params}{$name};
340 1 ▶ return () unless $v;
Branch: 1 branch
BranchTrueFalseTotal
unless $v 0 1 1
341 1 return @$v;
342 }
343  
344 0 ▶sub param_names {
Subroutine param_names: not called CC=1 SCAR=6.9
Pod undocumented
345 0 my $self = shift;
346 0 $self->_build_params;
347 0 return keys %{ $self->{_params} };
348 }
349  
350 # Flat hash reference: name => first value.
351 0 ▶sub params {
Subroutine params: not called CC=2 SCAR=17.9
Pod undocumented
352 0 my $self = shift;
353 0 $self->_build_params;
354 0 my %flat;
355 my $k;
356 0 for $k (keys %{ $self->{_params} }) {
357 0 $flat{$k} = $self->{_params}{$k}[0];
358 }
359 0 return { %flat };
360 }
361  
362 # --- cookies ----------------------------------------------------------
363 2 ▶sub cookie {
Subroutine cookie: called CC=2 SCAR=7.0
Pod undocumented
364 2 my ($self, $name) = @_;
365 2 $self->_parse_cookies;
366 2 ▶ return undef unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 2 2
367 2 return $self->{_cookies}{$name};
368 }
369  
370 0 ▶sub cookies {
Subroutine cookies: not called CC=1 SCAR=6.9
Pod undocumented
371 0 my $self = shift;
372 0 $self->_parse_cookies;
373 0 my %copy = %{ $self->{_cookies} };
374 0 return { %copy };
375 }
376  
377 # --- internals --------------------------------------------------------
378 10 ▶sub _build_params {
Subroutine _build_params: called CC=6 SCAR=18.0
379 10 my $self = shift;
380 10 ▶ return if $self->{_params};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_params"} 3 7 10
381 7 my %merged;
382  
383 7 my %q = _parse_query($self->query_string);
384 7 %merged = _merge_into({ %merged }, { %q });
385  
386 7 my $method = uc($self->method);
387 7 my $ct = $self->content_type;
388 7 ▶ if (($method eq 'POST' || $method eq 'PUT' || $method eq 'PATCH')
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "POST" || $method eq "PUT" || $method eq "PATCH" and $ct =~ m[\Aapplication/x-www-form-urlencoded]i) 3 4 7
Condition77%7/9
$method eq "POST" || $method eq "PUT" || $method eq "PATCH" and $ct =~ m[\Aapplication/x-www-form-urlencoded]i
!ll&&!rl&&r
313
$method eq "POST" or $method eq "PUT" or $method eq "PATCH"
l!l&&r!l&&!r
403
$method eq "POST" or $method eq "PUT"
l!l&&r!l&&!r
403
MC/DC50%2/4
$method eq "POST" || $method eq "PUT" || $method eq "PATCH" and $ct =~ m[\Aapplication/x-www-form-urlencoded]i
$method eq "POST" $method eq "PUT" $method eq "PATCH" $ct =~ m[\Aapplication/x-www-form-urlencoded]i
Truth table42%3/7
A or B or C and D
A= $method eq "POST"B= $method eq "PUT"C= $method eq "PATCH"D= $ct =~ m[\Aapplication/x-www-form-urlencoded]i
ABCDresult
000X0
1XX00
01X00
00100
1XX11
01X11
00111
389 && $ct =~ m{\Aapplication/x-www-form-urlencoded}i) {
390 3 my %p = _parse_query($self->body);
391 3 %merged = _merge_into({ %merged }, { %p });
392 }
393  
394 7 $self->{_params} = { %merged };
395 }
396  
397 # Merge $parsed into a fresh copy of $merged and return the result as a
398 # hash whose values are always array references (so repeated keys are
399 # preserved in order). Returns a list, so callers reassign:
400 # %merged = _merge_into({ %merged }, { %parsed });
401 # A fresh copy is built rather than mutating the argument, keeping the
402 # style under the K2/K3 copy-idiom ({ %hash }, not \%hash).
403 10 ▶sub _merge_into {
Subroutine _merge_into: called CC=5 SCAR=16.7
404 10 my ($merged, $parsed) = @_;
405 10 my %out;
406 my $k;
407 10 for $k (keys %$merged) {
408 1 $out{$k} = [ @{ $merged->{$k} } ];
409 }
410 10 for $k (keys %$parsed) {
411 9 my $v = $parsed->{$k};
412 9 ▶ my @vals = (ref($v) eq 'ARRAY') ? @$v : ($v);
Branch: 1 branch
BranchTrueFalseTotal
ref $v eq 'ARRAY' ? : 9 0 9
413 9 ▶ if ($out{$k}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($out{$k}) { } 0 9 9
414 0 push @{ $out{$k} }, @vals;
415 }
416 else {
417 9 $out{$k} = [ @vals ];
418 }
419 }
420 10 return %out;
421 }
422  
423 # --- pure-Perl query parsing and percent-decoding -------------------
424 # Parse an application/x-www-form-urlencoded string into a hash whose
425 # values are array references (so repeated keys are preserved in order).
426 # '+' becomes a space and %XX byte escapes are decoded.
427 10 ▶sub _parse_query {
Subroutine _parse_query: called CC=8 SCAR=21.0
428 10 my ($string) = @_;
429 10 my %out;
430 10 ▶ return %out unless defined $string && length $string;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $string and length $string 3 7 10
Condition66%2/3
defined $string and length $string
!ll&&!rl&&r
037
MC/DC50%1/2
defined $string and length $string
defined $string length $string
Truth table66%2/3
A and B
A= defined $stringB= length $string
ABresult
0X0
100
111
431 7 my $pair;
432 7 for $pair (split /&/, $string) {
433 11 ▶ next if $pair eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $pair eq "" 0 11 11
434 11 my ($k, $v) = split /=/, $pair, 2;
435 11 ▶ next unless defined $k;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k 0 11 11
436 11 ▶ $v = defined $v ? $v : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 11 0 11
437 11 $k = _url_decode($k);
438 11 $v = _url_decode($v);
439 11 ▶ if ($out{$k}) { push @{ $out{$k} }, $v; }
Branch: 1 branch
BranchTrueFalseTotal
if ($out{$k}) { } 2 9 11
440 9 else { $out{$k} = [ $v ]; }
441 }
442 7 return %out;
443 }
444  
445 # Percent-decode one form-encoded token. 5.005_03 safe: tr///, s///e with
446 # chr/hex, and $1 only (no //, no \x{...}, no @- / @+).
447 24 ▶sub _url_decode {
Subroutine _url_decode: called CC=2 SCAR=7.2
448 24 my ($s) = @_;
449 24 ▶ return '' unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 24 24
450 24 $s =~ tr/+/ /;
451 0 $s =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
452 24 return $s;
453 }
454  
455 2 ▶sub _parse_cookies {
Subroutine _parse_cookies: called CC=7 SCAR=20.0
456 2 my $self = shift;
457 2 ▶ return if $self->{_cookies};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_cookies"} 1 1 2
458 1 my %c;
459 1 my $raw = $self->{env}{HTTP_COOKIE};
460 1 ▶ if (defined $raw && $raw ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $raw and $raw ne "") 1 0 1
Condition33%1/3
defined $raw and $raw ne ""
!ll&&!rl&&r
001
MC/DC0%0/2
defined $raw and $raw ne ""
defined $raw $raw ne ""
Truth table33%1/3
A and B
A= defined $rawB= $raw ne ""
ABresult
0X0
100
111
461 1 my $pair;
462 1 for $pair (split /;\s*/, $raw) {
463 2 my ($k, $v) = split /=/, $pair, 2;
464 2 ▶ next unless defined $k;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k 0 2 2
465 2 $k =~ s/\A\s+//;
466 2 $k =~ s/\s+\z//;
467 2 ▶ $v = defined $v ? $v : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 2 0 2
468 2 $c{$k} = _url_decode($v);
469 }
470 }
471 1 $self->{_cookies} = { %c };
472 }
473  
474 ######################################################################
475 # PSGI::Handy::Router - tiny PSGI route dispatcher
476 #
477 # Maps (HTTP method, PATH_INFO) to a handler code reference, with named
478 # path parameters (:name) and an optional trailing splat (*). No named
479 # captures (?<name>) (5.10+); positional captures plus a parallel name
480 # list are used instead.
481 ######################################################################
482 package PSGI::Handy::Router;
483  
484 # --------------------------------------------------------------------
485 # new - create an empty router
486 # --------------------------------------------------------------------
487 28 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
488 28 my $class = shift;
489 28 my $self = { routes => [] };
490 28 return bless $self, $class;
491 }
492  
493 # --------------------------------------------------------------------
494 # add - register a route
495 # $router->add($method, $pattern, $handler);
496 # $method : 'GET', 'POST', ... (case-insensitive, stored upper-case)
497 # $pattern : '/users/:id', '/files/*', '/' (must begin with '/')
498 # $handler : a CODE reference
499 # Returns $self for chaining.
500 # --------------------------------------------------------------------
501 99 ▶sub add {
Subroutine add: called CC=5 SCAR=16.6
Pod undocumented
502 99 my ($self, $method, $pattern, $handler) = @_;
503 99 ▶ defined $method or Carp::croak "add: method is required";
Branch: 1 branch
BranchTrueFalseTotal
defined $method or Carp::croak("add: method is required") 99 0 99
504 99 ▶ defined $pattern or Carp::croak "add: pattern is required";
Branch: 1 branch
BranchTrueFalseTotal
defined $pattern or Carp::croak("add: pattern is required") 99 0 99
505 99 ▶ ref($handler) eq 'CODE' or Carp::croak "add: handler must be a code reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $handler eq "CODE" or Carp::croak("add: handler must be a code reference") 99 0 99
506 99 ▶ $pattern =~ m{\A/} or Carp::croak "add: pattern must begin with '/' (got '$pattern')";
Branch: 1 branch
BranchTrueFalseTotal
$pattern =~ m[\A/] or Carp::croak("add: pattern must begin with '/' (got '${pattern}')") 99 0 99
507  
508 99 $method = uc($method);
509 99 my ($regex, $names) = _compile($pattern);
510 99 push @{ $self->{routes} }, {
511 method => $method,
512 pattern => $pattern,
513 regex => $regex,
514 names => $names,
515 handler => $handler,
516 };
517 99 return $self;
518 }
519  
520 # --------------------------------------------------------------------
521 # match - look up a route
522 # my $r = $router->match($method, $path);
523 # Returns:
524 # - on success : { handler => CODE, params => HASH }
525 # - path matched, method not (405) : { allowed => [ method, ... ] }
526 # - no match at all (404) : undef
527 # First registered matching route wins.
528 # --------------------------------------------------------------------
529 29 ▶sub match {
Subroutine match: called CC=8 SCAR=20.8
Pod undocumented
530 29 my ($self, $method, $path) = @_;
531 29 ▶ defined $method or Carp::croak "match: method is required";
Branch: 1 branch
BranchTrueFalseTotal
defined $method or Carp::croak("match: method is required") 29 0 29
532 29 ▶ defined $path or Carp::croak "match: path is required";
Branch: 1 branch
BranchTrueFalseTotal
defined $path or Carp::croak("match: path is required") 29 0 29
533 29 $method = uc($method);
534  
535 29 my @allowed;
536 my $route;
537 29 for $route (@{ $self->{routes} }) {
538 74 my @caps = ($path =~ $route->{regex});
539 74 ▶ next unless @caps; # this pattern did not match the path
Branch: 1 branch
BranchTrueFalseTotal
unless @caps 49 25 74
540  
541 25 ▶ if ($route->{method} eq $method) {
Branch: 1 branch
BranchTrueFalseTotal
if ($route->{"method"} eq $method) 20 5 25
542 20 my %params;
543 20 my $names = $route->{names};
544 20 my $i;
545 20 ▶ for ($i = 0; $i < scalar(@$names); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @$names) 5 20 25
546 5 $params{ $names->[$i] } = $caps[$i];
547 }
548 20 return { handler => $route->{handler}, params => { %params } };
549 }
550 5 push @allowed, $route->{method}; # remember for a possible 405
551 }
552  
553 9 ▶ if (@allowed) {
Branch: 1 branch
BranchTrueFalseTotal
if (@allowed) 4 5 9
554 4 my %seen;
555 4 my @uniq = grep { !$seen{$_}++ } @allowed;
556 4 return { allowed => \@uniq };
557 }
558 5 return undef;
559 }
560  
561 # --------------------------------------------------------------------
562 # routes - return the internal route list (array reference).
563 # Mainly for introspection and testing.
564 # --------------------------------------------------------------------
565 0 ▶sub routes {
Subroutine routes: not called CC=1 SCAR=6.9
Pod undocumented
566 0 my $self = shift;
567 0 return $self->{routes};
568 }
569  
570 # --------------------------------------------------------------------
571 # _compile - turn a path pattern into (qr//, \@param_names)
572 #
573 # A pattern is split on '/' into segments. Each segment becomes:
574 # ':name' -> ([^/]+) and records the parameter name 'name'
575 # '*' (only as the LAST segment) -> (.*) recorded as 'splat'
576 # anything else -> quotemeta (literal, dots are NOT wildcards)
577 # The whole thing is anchored with \A ... \z so matching is exact.
578 # --------------------------------------------------------------------
579 99 ▶sub _compile {
Subroutine _compile: called CC=5 SCAR=16.1
580 99 my ($pattern) = @_;
581 99 my @segs = split m{/}, $pattern, -1; # -1 keeps trailing empty fields
582 99 my @names;
583 my @parts;
584 99 my $last = $#segs;
585 99 my $i;
586 99 ▶ for ($i = 0; $i <= $last; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $last) 214 99 313
587 214 my $seg = $segs[$i];
588 214 ▶ if ($seg eq '*' && $i == $last) {
Branch: 2 branches
BranchTrueFalseTotal
if ($seg eq '*' and $i == $last) { } 1 213 214
elsif ($seg =~ /\A:([A-Za-z_]\w*)\z/) { } 15 198 213
Condition66%2/3
$seg eq "*" and $i == $last
!ll&&!rl&&r
21301
MC/DC50%1/2
$seg eq "*" and $i == $last
$seg eq "*" $i == $last
Truth table66%2/3
A and B
A= $seg eq "*"B= $i == $last
ABresult
0X0
100
111
589 1 push @parts, '(.*)';
590 1 push @names, 'splat';
591 }
592 elsif ($seg =~ /\A:([A-Za-z_]\w*)\z/) {
593 15 push @parts, '([^/]+)';
594 15 push @names, $1;
595 }
596 else {
597 198 push @parts, quotemeta($seg);
598 }
599 }
600 99 my $source = '\\A' . join('/', @parts) . '\\z';
601 99 my $regex = qr{$source};
602 99 return ($regex, \@names);
603 }
604  
605 ######################################################################
606 # PSGI::Handy::Context - per-request context object
607 #
608 # Passed as the single argument to every route handler. Gives access to
609 # the request, the matched path parameters, a per-request stash, the
610 # injected database handle, response shortcuts, and template rendering.
611 ######################################################################
612 package PSGI::Handy::Context;
613  
614 17 ▶sub new {
Subroutine new: called CC=2 SCAR=7.1
Pod undocumented
615 17 my ($class, %args) = @_;
616 my $self = {
617 app => $args{app},
618 req => $args{req},
619 17 ▶ params => (defined $args{params} ? $args{params} : {}),
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'params'} ? : 17 0 17
620 stash => {},
621 };
622 17 return bless $self, $class;
623 }
624  
625 # --- accessors --------------------------------------------------------
626 1 ▶sub req {
Subroutine req: called CC=1 SCAR=0.0
Pod undocumented
627 1 my $self = shift;
628 1 return $self->{req};
629 }
630  
631 0 ▶sub app {
Subroutine app: not called CC=1 SCAR=6.9
Pod undocumented
632 0 my $self = shift;
633 0 return $self->{app};
634 }
635  
636 # All matched path parameters (hash reference).
637 0 ▶sub params {
Subroutine params: not called CC=1 SCAR=6.9
Pod undocumented
638 0 my $self = shift;
639 0 return $self->{params};
640 }
641  
642 # A single value: a matched path parameter wins over query/body params.
643 2 ▶sub param {
Subroutine param: called CC=3 SCAR=11.0
Pod undocumented
644 2 my ($self, $name) = @_;
645 2 ▶ return undef unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 2 2
646 2 ▶ return $self->{params}{$name} if exists $self->{params}{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"params"}{$name} 1 1 2
647 1 return $self->{req}->param($name);
648 }
649  
650 # The injected database handle (whatever was passed to PSGI::Handy->new).
651 1 ▶sub db {
Subroutine db: called CC=1 SCAR=0.0
Pod undocumented
652 1 my $self = shift;
653 1 return $self->{app}->db;
654 }
655  
656 # Configuration: $c->config or $c->config($key)
657 1 ▶sub config {
Subroutine config: called CC=1 SCAR=0.0
Pod undocumented
658 1 my ($self, $key) = @_;
659 1 return $self->{app}->config($key);
660 }
661  
662 # --- stash ------------------------------------------------------------
663 # $c->stash -> hashref of everything
664 # $c->stash('key') -> one value
665 # $c->stash(k1 => v1, ...) -> set, returns $c
666 1 ▶sub stash {
Subroutine stash: called CC=4 SCAR=14.0
Pod undocumented
667 1 my $self = shift;
668 1 ▶ return $self->{stash} if @_ == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 0 1 1
669 1 ▶ return $self->{stash}{ $_[0] } if @_ == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 0 1 1
670 1 my %kv = @_;
671 1 my $k;
672 1 for $k (keys %kv) {
673 1 $self->{stash}{$k} = $kv{$k};
674 }
675 1 return $self;
676 }
677  
678 # --- response shortcuts (return a PSGI::Handy::Response object) -------
679 3 ▶sub html { my $self = shift; return PSGI::Handy::Response->html(@_); }
Subroutine html: called CC=1 SCAR=0.0
Pod undocumented
680 6 ▶sub text { my $self = shift; return PSGI::Handy::Response->text(@_); }
Subroutine text: called CC=1 SCAR=0.0
Pod undocumented
681 0 ▶sub json { my $self = shift; return PSGI::Handy::Response->json(@_); }
Subroutine json: not called CC=1 SCAR=6.9
Pod undocumented
682 1 ▶sub redirect { my $self = shift; return PSGI::Handy::Response->redirect(@_); }
Subroutine redirect: called CC=1 SCAR=0.0
Pod undocumented
683 0 ▶sub res { my $self = shift; return PSGI::Handy::Response->new(@_); }
Subroutine res: not called CC=1 SCAR=6.9
Pod undocumented
684  
685 # --- template rendering ----------------------------------------------
686 # Uses the renderer injected into PSGI::Handy->new(renderer => ...).
687 # The renderer is either:
688 # - a CODE reference: $renderer->($template, \%vars) -> string
689 # - an object with a render() method: $r->render($template, \%vars)
690 # Stash values are passed to the template, overridden by $vars.
691 # Returns a PSGI::Handy::Response (text/html).
692 1 ▶sub render {
Subroutine render: called CC=8 SCAR=24.4
Pod undocumented
693 1 my ($self, $template, $vars) = @_;
694 1 my $renderer = $self->{app}->renderer;
695 1 ▶ defined $renderer
Branch: 1 branch
BranchTrueFalseTotal
defined $renderer or Carp::croak("render: no renderer configured (pass renderer => ... to PSGI::Handy->new)") 1 0 1
696 or Carp::croak "render: no renderer configured (pass renderer => ... to PSGI::Handy->new)";
697  
698 1 my %merged = %{ $self->{stash} };
699 1 ▶ if ($vars) {
Branch: 1 branch
BranchTrueFalseTotal
if ($vars) 1 0 1
700 1 my $k;
701 1 for $k (keys %$vars) {
702 1 $merged{$k} = $vars->{$k};
703 }
704 }
705  
706 1 my $out;
707 1 ▶ if (ref($renderer) eq 'CODE') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $renderer eq 'CODE') { } 1 0 1
elsif (ref $renderer and UNIVERSAL::can($renderer, 'render')) { } 0 0 0
708 1 $out = $renderer->($template, { %merged });
709 }
710 ▶ elsif (ref($renderer) && UNIVERSAL::can($renderer, 'render')) {
Condition0%0/3
ref $renderer and UNIVERSAL::can($renderer, "render")
!ll&&!rl&&r
000
MC/DC0%0/2
ref $renderer and UNIVERSAL::can($renderer, "render")
ref $renderer UNIVERSAL::can($renderer, "render")
Truth table0%0/3
A and B
A= ref $rendererB= UNIVERSAL::can($renderer, "render")
ABresult
0X0
100
111
711 0 $out = $renderer->render($template, { %merged });
712 }
713 else {
714 0 Carp::croak "render: renderer must be a code reference or an object with a render() method";
715 }
716  
717 1 ▶ my $body = defined $out ? "$out" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $out ? : 1 0 1
718 1 return PSGI::Handy::Response->html($body);
719 }
720  
721 ######################################################################
722 # PSGI::Handy - the application class (facade). Wires the component
723 # classes above into a single PSGI-subset $app via to_app().
724 ######################################################################
725 package PSGI::Handy;
726  
727 # --------------------------------------------------------------------
728 # new(%args)
729 # renderer => CODE or object with render() (for $c->render)
730 # db => any database handle (for $c->db)
731 # config => hash reference (for $c->config)
732 # not_found => CODE handler for 404 (optional)
733 # --------------------------------------------------------------------
734 16 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
735 16 my ($class, %args) = @_;
736 my $self = {
737 router => PSGI::Handy::Router->new,
738 renderer => $args{renderer},
739 db => $args{db},
740 config => (defined $args{config} ? $args{config} : {}),
741 not_found => $args{not_found},
742 16 ▶ before => [],
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'config'} ? : 1 15 16
743 after => [],
744 };
745 16 return bless $self, $class;
746 }
747  
748 # --- injected dependencies (getters / setters) ----------------------
749 1 ▶sub renderer {
Subroutine renderer: called CC=2 SCAR=7.1
Pod documented
750 1 my $self = shift;
751 1 ▶ $self->{renderer} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 1 1
752 1 return $self->{renderer};
753 }
754  
755 3 ▶sub db {
Subroutine db: called CC=2 SCAR=7.1
Pod undocumented
756 3 my $self = shift;
757 3 ▶ $self->{db} = shift if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 3 3
758 3 return $self->{db};
759 }
760  
761 1 ▶sub config {
Subroutine config: called CC=2 SCAR=7.1
Pod undocumented
762 1 my ($self, $key) = @_;
763 1 ▶ return $self->{config} unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 1 1
764 1 return $self->{config}{$key};
765 }
766  
767 0 ▶sub router {
Subroutine router: not called CC=1 SCAR=6.9
Pod undocumented
768 0 my $self = shift;
769 0 return $self->{router};
770 }
771  
772 # --- route registration ---------------------------------------------
773 80 ▶sub route {
Subroutine route: called CC=1 SCAR=0.0
Pod undocumented
774 80 my ($self, $method, $pattern, $handler) = @_;
775 80 $self->{router}->add($method, $pattern, $handler);
776 80 return $self;
777 }
778  
779 69 ▶sub get { my $self = shift; return $self->route('GET', @_); }
Subroutine get: called CC=1 SCAR=0.0
Pod undocumented
780 11 ▶sub post { my $self = shift; return $self->route('POST', @_); }
Subroutine post: called CC=1 SCAR=0.0
Pod undocumented
781 0 ▶sub put { my $self = shift; return $self->route('PUT', @_); }
Subroutine put: not called CC=1 SCAR=6.9
Pod undocumented
782 0 ▶sub patch { my $self = shift; return $self->route('PATCH', @_); }
Subroutine patch: not called CC=1 SCAR=6.9
Pod undocumented
783 0 ▶sub del { my $self = shift; return $self->route('DELETE', @_); }
Subroutine del: not called CC=1 SCAR=6.9
Pod undocumented
784 0 ▶sub head { my $self = shift; return $self->route('HEAD', @_); }
Subroutine head: not called CC=1 SCAR=6.9
Pod undocumented
785  
786 # Register a handler for every common method.
787 1 ▶sub any {
Subroutine any: called CC=2 SCAR=6.9
Pod undocumented
788 1 my ($self, $pattern, $handler) = @_;
789 1 my $m;
790 1 for $m (qw(GET POST PUT PATCH DELETE HEAD OPTIONS)) {
791 7 $self->{router}->add($m, $pattern, $handler);
792 }
793 1 return $self;
794 }
795  
796 # --- hooks ------------------------------------------------------------
797 # before($c): return a Response/arrayref to short-circuit, else nothing.
798 # after($c, $out): return a value to replace $out, else it is unchanged.
799 1 ▶sub before {
Subroutine before: called CC=2 SCAR=7.0
Pod undocumented
800 1 my ($self, $code) = @_;
801 1 ▶ ref($code) eq 'CODE' or Carp::croak "before: a code reference is required";
Branch: 1 branch
BranchTrueFalseTotal
ref $code eq "CODE" or Carp::croak("before: a code reference is required") 1 0 1
802 1 push @{ $self->{before} }, $code;
803 1 return $self;
804 }
805  
806 1 ▶sub after {
Subroutine after: called CC=2 SCAR=7.0
Pod undocumented
807 1 my ($self, $code) = @_;
808 1 ▶ ref($code) eq 'CODE' or Carp::croak "after: a code reference is required";
Branch: 1 branch
BranchTrueFalseTotal
ref $code eq "CODE" or Carp::croak("after: a code reference is required") 1 0 1
809 1 push @{ $self->{after} }, $code;
810 1 return $self;
811 }
812  
813 # --- build the PSGI application -------------------------------------
814 17 ▶sub to_app {
Subroutine to_app: called CC=1 SCAR=0.0
Pod undocumented
815 17 my $self = shift;
816 17 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
817 17 my $env = shift;
818 17 return $self->_dispatch($env);
819 17 };
820 }
821  
822 # --------------------------------------------------------------------
823 # _dispatch - turn one PSGI env into one PSGI response
824 # --------------------------------------------------------------------
825 17 ▶sub _dispatch {
Subroutine _dispatch: called CC=16 SCAR=27.9
826 17 my ($self, $env) = @_;
827 17 my $req = PSGI::Handy::Request->new($env);
828 17 my $method = uc($req->method);
829 17 my $path = $req->path;
830  
831 17 my $found = $self->{router}->match($method, $path);
832 17 ▶ if ($method eq 'HEAD' && !($found && $found->{handler})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "HEAD" and not $found && $found->{"handler"}) 1 16 17
Condition50%3/6
$method eq "HEAD" and not $found && $found->{"handler"}
!ll&&!rl&&r
1601
$found && $found->{'handler'}
!ll&&!rl&&r
010
MC/DC33%1/3
$method eq "HEAD" and not $found && $found->{"handler"}
$method eq "HEAD" $found $found->{'handler'}
Truth table50%2/4
A and not(B && C)
A= $method eq "HEAD"B= $foundC= $found->{'handler'}
ABCresult
0XX0
1110
10X1
1101
833 1 my $g = $self->{router}->match('GET', $path); # HEAD falls back to GET
834 1 ▶ $found = $g if $g && $g->{handler};
Branch: 1 branch
BranchTrueFalseTotal
if $g and $g->{"handler"} 1 0 1
Condition33%1/3
$g and $g->{"handler"}
!ll&&!rl&&r
001
MC/DC0%0/2
$g and $g->{"handler"}
$g $g->{"handler"}
Truth table33%1/3
A and B
A= $gB= $g->{"handler"}
ABresult
0X0
100
111
835 }
836  
837 my $c = PSGI::Handy::Context->new(
838 app => $self,
839 req => $req,
840 params => ($found && $found->{params}) ? $found->{params} : {},
841 17 ▶ );
Branch: 1 branch
BranchTrueFalseTotal
$found && $found->{'params'} ? : 13 4 17
Condition100%3/3
$found and $found->{"params"}
!ll&&!rl&&r
2213
MC/DC100%2/2
$found and $found->{"params"}
$found $found->{"params"}
Truth table100%3/3
A and B
A= $foundB= $found->{"params"}
ABresult
0X0
100
111
842  
843 17 my $out;
844 17 ▶ if ($found && $found->{handler}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($found and $found->{'handler'}) { } 13 4 17
elsif ($found and $found->{'allowed'}) { } 2 2 4
Condition100%3/3
$found and $found->{"handler"}
!ll&&!rl&&r
2213
MC/DC100%2/2
$found and $found->{"handler"}
$found $found->{"handler"}
Truth table100%3/3
A and B
A= $foundB= $found->{"handler"}
ABresult
0X0
100
111
845 13 my $short = $self->_run_before($c);
846 13 ▶ if (defined $short) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $short) { } 1 12 13
847 1 $out = $short;
848 }
849 else {
850 12 $out = eval { $found->{handler}->($c) };
851 12 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 11 12
852 1 _log_error($env, $@);
853 1 $out = PSGI::Handy::Response->text('Internal Server Error', 500);
854 }
855 }
856 }
857 ▶ elsif ($found && $found->{allowed}) {
Condition66%2/3
$found and $found->{"allowed"}
!ll&&!rl&&r
202
MC/DC50%1/2
$found and $found->{"allowed"}
$found $found->{"allowed"}
Truth table66%2/3
A and B
A= $foundB= $found->{"allowed"}
ABresult
0X0
100
111
858 2 my @allow = _augment_allowed($found->{allowed});
859 2 ▶ if ($method eq 'OPTIONS') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq 'OPTIONS') { } 1 1 2
860 # No explicit OPTIONS route: answer the preflight ourselves.
861 1 $out = PSGI::Handy::Response->text('', 204)
862 ->set_header('Allow', join(', ', @allow));
863 }
864 else {
865 1 $out = PSGI::Handy::Response->text('Method Not Allowed', 405)
866 ->set_header('Allow', join(', ', @allow));
867 }
868 }
869 else {
870 2 $out = $self->_handle_not_found($c, $env);
871 }
872  
873 17 $out = $self->_run_after($c, $out);
874  
875 17 my $psgi = $self->_finalize_output($out);
876  
877 # Correct HEAD semantics: keep headers (incl. Content-Length), drop body.
878 17 ▶ if ($method eq 'HEAD') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "HEAD") 1 16 17
879 1 return [ $psgi->[0], $psgi->[1], [] ];
880 }
881 16 return $psgi;
882 }
883  
884 2 ▶sub _handle_not_found {
Subroutine _handle_not_found: called CC=4 SCAR=14.6
885 2 my ($self, $c, $env) = @_;
886 2 ▶ if ($self->{not_found}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"not_found"}) 1 1 2
887 1 my $out = eval { $self->{not_found}->($c) };
888 1 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
889 0 _log_error($env, $@);
890 0 return PSGI::Handy::Response->text('Not Found', 404);
891 }
892 1 ▶ return defined $out ? $out : PSGI::Handy::Response->text('Not Found', 404);
Branch: 1 branch
BranchTrueFalseTotal
defined $out ? : 1 0 1
893 }
894 1 return PSGI::Handy::Response->text('Not Found', 404);
895 }
896  
897 # Augment a router 'allowed' list for the Allow header. HEAD is implied
898 # wherever GET is served (the dispatcher serves HEAD via the GET handler),
899 # and OPTIONS is always answerable here. Order is preserved; the two
900 # implied methods are appended once if missing.
901 2 ▶sub _augment_allowed {
Subroutine _augment_allowed: called CC=6 SCAR=18.7
902 2 my ($allowed) = @_;
903 2 my %seen;
904 my @out;
905 2 my $m;
906 2 for $m (@$allowed) {
907 2 ▶ push @out, $m unless $seen{$m}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$m}++ 2 0 2
908 }
909 2 ▶ if ($seen{'GET'} && !$seen{'HEAD'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen{"GET"} and not $seen{"HEAD"}) 2 0 2
Condition33%1/3
$seen{"GET"} and not $seen{"HEAD"}
!ll&&!rl&&r
002
MC/DC0%0/2
$seen{"GET"} and not $seen{"HEAD"}
$seen{"GET"} not $seen{"HEAD"}
Truth table33%1/3
A and not(B)
A= $seen{"GET"}B= not $seen{"HEAD"}
ABresult
0X0
100
111
910 2 push @out, 'HEAD';
911 2 $seen{'HEAD'} = 1;
912 }
913 2 ▶ unless ($seen{'OPTIONS'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($seen{"OPTIONS"}) 2 0 2
914 2 push @out, 'OPTIONS';
915 2 $seen{'OPTIONS'} = 1;
916 }
917 2 return @out;
918 }
919  
920 13 ▶sub _run_before {
Subroutine _run_before: called CC=4 SCAR=14.5
921 13 my ($self, $c) = @_;
922 13 my $hook;
923 13 for $hook (@{ $self->{before} }) {
924 1 my $r = $hook->($c);
925 1 ▶ return $r if defined $r && ref($r); # a ref means "use this as the response"
Branch: 1 branch
BranchTrueFalseTotal
if defined $r and ref $r 1 0 1
Condition33%1/3
defined $r and ref $r
!ll&&!rl&&r
001
MC/DC0%0/2
defined $r and ref $r
defined $r ref $r
Truth table33%1/3
A and B
A= defined $rB= ref $r
ABresult
0X0
100
111
926 }
927 12 return undef;
928 }
929  
930 17 ▶sub _run_after {
Subroutine _run_after: called CC=3 SCAR=11.0
931 17 my ($self, $c, $out) = @_;
932 17 my $hook;
933 17 for $hook (@{ $self->{after} }) {
934 1 my $r = $hook->($c, $out);
935 1 ▶ $out = $r if defined $r;
Branch: 1 branch
BranchTrueFalseTotal
if defined $r 1 0 1
936 }
937 17 return $out;
938 }
939  
940 # Accept a Response object, a raw PSGI arrayref, or a plain string.
941 17 ▶sub _finalize_output {
Subroutine _finalize_output: called CC=5 SCAR=16.7
942 17 my ($self, $out) = @_;
943 17 ▶ if (ref($out) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $out eq "ARRAY") 1 16 17
944 1 return $out;
945 }
946 16 ▶ if (UNIVERSAL::isa($out, 'PSGI::Handy::Response')) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($out, "PSGI::Handy::Response")) 15 1 16
947 15 return $out->finalize;
948 }
949 1 ▶ if (!ref($out) && defined $out) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $out and defined $out) 1 0 1
Condition33%1/3
not ref $out and defined $out
!ll&&!rl&&r
001
MC/DC0%0/2
not ref $out and defined $out
not ref $out defined $out
Truth table33%1/3
not(A) and B
A= not ref $outB= defined $out
ABresult
0X0
100
111
950 1 return PSGI::Handy::Response->html($out)->finalize;
951 }
952 0 return PSGI::Handy::Response->text('Internal Server Error', 500)->finalize;
953 }
954  
955 1 ▶sub _log_error {
Subroutine _log_error: called CC=4 SCAR=23.3
956 1 my ($env, $msg) = @_;
957 1 my $fh = $env->{'psgi.errors'};
958 1 ▶ return unless $fh;
Branch: 1 branch
BranchTrueFalseTotal
unless $fh 1 0 1
959 0 my $line = "[PSGI::Handy] handler error: $msg\n";
960 # PSGI guarantees psgi.errors supports a print() method, so prefer the
961 # method call (UNIVERSAL::can is used as a plain function so it is safe
962 # on unblessed glob references, where it simply returns false). Plain
963 # glob filehandles such as \*STDERR fall back to the block-handle form.
964 0 ▶ if (ref($fh) && UNIVERSAL::can($fh, 'print')) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $fh and UNIVERSAL::can($fh, 'print')) { } 0 0 0
Condition0%0/3
ref $fh and UNIVERSAL::can($fh, "print")
!ll&&!rl&&r
000
MC/DC0%0/2
ref $fh and UNIVERSAL::can($fh, "print")
ref $fh UNIVERSAL::can($fh, "print")
Truth table0%0/3
A and B
A= ref $fhB= UNIVERSAL::can($fh, "print")
ABresult
0X0
100
111
965 0 $fh->print($line);
966 }
967 else {
968 0 print {$fh} $line;
969 }
970 }
971  
972 # --------------------------------------------------------------------
973 # All component classes are defined above, in this one file. Mark their
974 # module names as already loaded so that "use PSGI::Handy::Router" (and
975 # "require ...") elsewhere is a successful no-op, and give each the
976 # distribution $VERSION from the single source above (there is no
977 # per-package version literal that could drift out of step).
978 # --------------------------------------------------------------------
979 {
980 4 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
981 4 ▶ my $loaded = defined $INC{'PSGI/Handy.pm'} ? $INC{'PSGI/Handy.pm'} : __FILE__;
Branch: 1 branch
BranchTrueFalseTotal
defined $INC{'PSGI/Handy.pm'} ? : 4 0 4
982 4 my $name;
983 4 for $name (qw(Response Request Router Context)) {
984 16 ${ 'PSGI::Handy::' . $name . '::VERSION' } = $VERSION;
985 16 $INC{ 'PSGI/Handy/' . $name . '.pm' } = $loaded;
986 }
987 }
988  
989 4 1;
990  
991 __END__
↑ Summary