Neaf/Request.pm

filter: Statementstmt 96.7% 453 / 468 Branchbran 76.1% 160 / 210 Conditioncond 58.3% 87 / 149 MC/DCmcdc 19.3% 17 / 88 Subroutinesub 96.0% 98 / 102 Podpod 100% 63 / 63 totaltotal 81.3% 878 / 1080 CC 167 SCAR 17.1
CC
167
Cov
85%
url_param
17.0
_mangle_headers
15.0
get_cookie
10.6
CRAP 5.6
« Neaf.pm ↑ Summary Neaf/Upload.pm »
1 package MVC::Neaf::Request;
2  
3 94 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 94 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 94 our $VERSION = '0.2901';
7  
8 =head1 NAME
9  
10 MVC::Neaf::Request - Request class for Not Even A Framework
11  
12 =head1 DESCRIPTION
13  
14 This is what your L<MVC::Neaf> application is going to get as its ONLY input.
15  
16 Here's a brief overview of what a Neaf request returns:
17  
18 # How the application was configured:
19 MVC::Neaf->route( "/matching/route" => sub { my $req = shift; ... },
20 path_info_regex => '.*' );
21  
22 # What was requested:
23 http(s)://server.name:1337/mathing/route/some/more/slashes?foo=1&bar=2
24  
25 # What is being returned:
26 $req->http_version = HTTP/1.0 or HTTP/1.1
27 $req->scheme = http or https
28 $req->method = GET
29 $req->hostname = server.name
30 $req->port = 1337
31 $req->path = /mathing/route/some/more/slashes
32 $req->prefix = /mathing/route
33 $req->postfix = some/more/slashes
34  
35 # params and cookies require a regex
36 $req->param( foo => '\d+' ) = 1
37  
38 =head1 REQUEST METHODS
39  
40 The actual Request object the application gets is going to be
41 a subclass of this.
42 Thus it is expected to have the following methods.
43  
44 =cut
45  
46 94 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 94 ▶use URI::Escape;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 94 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 94 ▶use HTTP::Headers::Fast;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 94 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
51 94 ▶use Sys::Hostname ();
Subroutine BEGIN: called CC=1 SCAR=0.0
52 94 ▶use Digest::MD5 qw(md5);
Subroutine BEGIN: called CC=1 SCAR=0.0
53  
54 94 ▶use MVC::Neaf::Util qw( JSON http_date run_all_nodie canonize_path encode_b64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
55 94 ▶use MVC::Neaf::Upload;
Subroutine BEGIN: called CC=1 SCAR=0.0
56 94 ▶use MVC::Neaf::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
57 94 ▶use MVC::Neaf::Route::PreRoute;
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 94 our %allow_helper;
60  
61 =head2 new()
62  
63 MVC::Neaf::Request->new( %arguments )
64  
65 The application is not supposed to make its own requests,
66 so this constructor is really for testing purposes only.
67  
68 For now, just swallows whatever is given to it.
69 Restrictions MAY BE added in the future though.
70  
71 =cut
72  
73 172 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
74 172 my ($class, %args) = @_;
75  
76 # TODO 0.30 restrict params
77 172 return bless \%args, $class;
78 };
79  
80 # TODO 0.90 A lot of copypasted methods down here.
81 # Should we join them all? Maybe...
82  
83 =head2 client_ip()
84  
85 Returns the IP of the client.
86 If C<X-Forwarded-For> header is set, returns that instead.
87  
88 =cut
89  
90 1 ▶sub client_ip {
Subroutine client_ip: called CC=5 SCAR=20.2
Pod documented
91 1 my $self = shift;
92  
93 1 ▶ return $self->{client_ip} ||= do {
Condition33%1/3
$self->{"client_ip"} ||= do { my(@fwd) = $self->header_in("X-Forwarded-For", ".*"); @fwd == 1 and $fwd[0] or $self->do_get_client_ip or "127.0.0.1" }
l!l&&r!l&&!r
010
MC/DC0%0/2
$self->{"client_ip"} ||= do { my(@fwd) = $self->header_in("X-Forwarded-For", ".*"); @fwd == 1 and $fwd[0] or $self->do_get_client_ip or "127.0.0.1" }
$self->{"client_ip"} do { my(@fwd) = $self->header_in("X-Forwarded-For", ".*"); @fwd == 1 and $fwd[0] or $self->do_get_client_ip or "127.0.0.1" }
Truth table33%1/3
A ||= B
A= $self->{"client_ip"}B= do { my(@fwd) = $self->header_in("X-Forwarded-For", ".*"); @fwd == 1 and $fwd[0] or $self->do_get_client_ip or "127.0.0.1" }
ABresult
1X1
011
000
94 1 my @fwd = $self->header_in( 'X-Forwarded-For', '.*' );
95 1 ▶ @fwd == 1 && $fwd[0] || $self->do_get_client_ip || "127.0.0.1";
Condition37%3/8
@fwd == 1 && $fwd[0] || $self->do_get_client_ip || '127.0.0.1'
l!l
01
@fwd == 1 and $fwd[0] or $self->do_get_client_ip
l!l&&r!l&&!r
001
@fwd == 1 and $fwd[0]
!ll&&!rl&&r
100
MC/DC0%0/3
@fwd == 1 && $fwd[0] || $self->do_get_client_ip || '127.0.0.1'
@fwd == 1 $fwd[0] $self->do_get_client_ip
Truth table20%1/5
A and B or C
A= @fwd == 1B= $fwd[0]C= $self->do_get_client_ip
ABCresult
11X1
0X11
1011
0X00
1000
96 };
97 };
98  
99 =head2 http_version()
100  
101 Returns version number of C<http> protocol.
102  
103 =cut
104  
105 2 ▶sub http_version {
Subroutine http_version: called CC=2 SCAR=7.0
Pod documented
106 2 my $self = shift;
107  
108 2 ▶ if (!exists $self->{http_version}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"http_version"}) 2 0 2
109 2 $self->{http_version} = $self->do_get_http_version;
110 };
111  
112 1 return $self->{http_version};
113 };
114  
115 =head2 scheme()
116  
117 Returns C<http> or C<https>, depending on how the request was done.
118  
119 =cut
120  
121 13 ▶sub scheme {
Subroutine scheme: called CC=3 SCAR=11.0
Pod documented
122 13 my $self = shift;
123  
124 13 ▶ if (!exists $self->{scheme}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"scheme"}) 9 4 13
125 9 ▶ $self->{scheme} = $self->do_get_scheme || 'http';
Condition100%2/2
$self->do_get_scheme || 'http'
l!l
25
MC/DC100%1/1
$self->do_get_scheme || 'http'
$self->do_get_scheme
Truth table100%2/2
A
A= $self->do_get_scheme
Aresult
11
00
126 };
127  
128 11 return $self->{scheme};
129 };
130  
131 =head2 secure()
132  
133 Returns true if C<https> is used, false otherwise.
134  
135 =cut
136  
137 # TODO 0.90 secure should be a flag, scheme should depend on it
138 3 ▶sub secure {
Subroutine secure: called CC=1 SCAR=0.0
Pod documented
139 3 my $self = shift;
140 3 return $self->scheme eq 'https';
141 };
142  
143 =head2 method()
144  
145 Return the C<HTTP> method being used.
146 C<GET> is the default value if cannot determine
147 (useful for command-line debugging).
148  
149 =cut
150  
151 347 ▶sub method {
Subroutine method: called CC=3 SCAR=11.1
Pod documented
152 347 my $self = shift;
153 347 ▶ return $self->{method} ||= $self->do_get_method || "GET";
Condition80%4/5
$self->{"method"} ||= $self->do_get_method || "GET"
l!l&&r!l&&!r
1871591
$self->do_get_method || 'GET'
l!l
1590
MC/DC0%0/2
$self->{"method"} ||= $self->do_get_method || "GET"
$self->{"method"} $self->do_get_method
Truth table66%2/3
A ||= B
A= $self->{"method"}B= $self->do_get_method
ABresult
1X1
011
000
154 };
155  
156 =head2 is_post()
157  
158 Alias for C<$self-E<gt>method eq 'POST'>.
159 May be useful in form submission, as in
160  
161 $form = $request->form( $validator );
162 if ($request->is_post and $form->is_valid) {
163 # save & redirect
164 };
165 # show form again
166  
167 =cut
168  
169 1 ▶sub is_post {
Subroutine is_post: called CC=1 SCAR=0.0
Pod documented
170 1 my $self = shift;
171 1 return $self->method eq 'POST';
172 };
173  
174 =head2 hostname()
175  
176 Returns the hostname that was requested, or C<localhost> if cannot detect.
177  
178 =cut
179  
180 4 ▶sub hostname {
Subroutine hostname: called CC=3 SCAR=11.7
Pod documented
181 4 my $self = shift;
182  
183 4 ▶ return $self->{hostname} ||= $self->do_get_hostname || "localhost";
Condition60%3/5
$self->{"hostname"} ||= $self->do_get_hostname || "localhost"
l!l&&r!l&&!r
031
$self->do_get_hostname || 'localhost'
l!l
30
MC/DC0%0/2
$self->{"hostname"} ||= $self->do_get_hostname || "localhost"
$self->{"hostname"} $self->do_get_hostname
Truth table33%1/3
A ||= B
A= $self->{"hostname"}B= $self->do_get_hostname
ABresult
1X1
011
000
184 # TODO 0.90 what if http://0/?
185 };
186  
187 =head2 port()
188  
189 Returns the port number.
190  
191 =cut
192  
193 5 ▶sub port {
Subroutine port: called CC=2 SCAR=6.9
Pod documented
194 5 my $self = shift;
195  
196 5 ▶ return $self->{port} ||= $self->do_get_port;
Condition100%3/3
$self->{"port"} ||= $self->do_get_port
l!l&&r!l&&!r
131
MC/DC100%2/2
$self->{"port"} ||= $self->do_get_port
$self->{"port"} $self->do_get_port
Truth table100%3/3
A ||= B
A= $self->{"port"}B= $self->do_get_port
ABresult
1X1
011
000
197 };
198  
199 =head2 path()
200  
201 Returns the path part of the URI. Path is guaranteed to start with a slash.
202  
203 =cut
204  
205 184 ▶sub path {
Subroutine path: called CC=2 SCAR=7.1
Pod documented
206 184 my $self = shift;
207  
208 184 ▶ return $self->{path} ||= $self->do_get_path;
Condition66%2/3
$self->{"path"} ||= $self->do_get_path
l!l&&r!l&&!r
271570
MC/DC0%0/2
$self->{"path"} ||= $self->do_get_path
$self->{"path"} $self->do_get_path
Truth table66%2/3
A ||= B
A= $self->{"path"}B= $self->do_get_path
ABresult
1X1
011
000
209 };
210  
211 =head2 route()
212  
213 A L<MVC::Neaf::Route> object that this request is being dispatched to.
214  
215 If request is not inside an application, returns a L<MVC::Neaf::Route::Null>
216 instead.
217  
218 =cut
219  
220 830 ▶sub route {
Subroutine route: called CC=2 SCAR=7.1
Pod documented
221 830 my $self = shift;
222 830 ▶ return $self->{route} ||= MVC::Neaf::Route::PreRoute->new(
Condition66%2/3
$self->{"route"} ||= "MVC::Neaf::Route::PreRoute"->new("method", "GET")
l!l&&r!l&&!r
82460
MC/DC0%0/2
$self->{"route"} ||= "MVC::Neaf::Route::PreRoute"->new("method", "GET")
$self->{"route"} "MVC::Neaf::Route::PreRoute"->new("method", "GET")
Truth table66%2/3
A ||= B
A= $self->{"route"}B= "MVC::Neaf::Route::PreRoute"->new("method", "GET")
ABresult
1X1
011
000
223 method => 'GET',
224 );
225 };
226  
227 =head2 set_path()
228  
229 $req->set_path( $new_path )
230  
231 Set path() to new value. This may be useful in C<pre_route> hook.
232  
233 Path will be canonized.
234  
235 If no argument given, or it is C<undef>, resets path() value to
236 underlying driver's C<do_get_path>.
237  
238 Returns self.
239  
240 =cut
241  
242 2 ▶sub set_path {
Subroutine set_path: called CC=2 SCAR=7.1
Pod documented
243 2 my ($self, $new_path) = @_;
244  
245 2 ▶ $self->{path} = defined $new_path
Branch: 1 branch
BranchTrueFalseTotal
defined $new_path ? : 2 0 2
246 ? canonize_path( $new_path, 1 )
247 : $self->do_get_path;
248  
249 2 $self;
250 };
251  
252 =head2 prefix()
253  
254 The part of the request that matched the route to the
255 application being executed.
256  
257 Guaranteed to start with slash.
258 Unless C<set_path> was called, it is a prefix of C<path()>.
259  
260 Not available before routing was applied to request.
261  
262 =cut
263  
264 5 ▶sub prefix {
Subroutine prefix: called CC=4 SCAR=15.6
Pod documented
265 5 my $self = shift;
266  
267 # TODO kill in 0.30
268 carp "NEAF: prefix() call before routing was applied is DEPRECATED: "
269 5 ▶ unless $self->{route} && $self->{route}->path =~ m,^(?:/|$),;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"route"} and $self->{"route"}->path =~ m[^(?:/|$)] 0 5 5
Condition33%1/3
$self->{"route"} and $self->{"route"}->path =~ m[^(?:/|$)]
!ll&&!rl&&r
005
MC/DC0%0/2
$self->{"route"} and $self->{"route"}->path =~ m[^(?:/|$)]
$self->{"route"} $self->{"route"}->path =~ m[^(?:/|$)]
Truth table33%1/3
A and B
A= $self->{"route"}B= $self->{"route"}->path =~ m[^(?:/|$)]
ABresult
0X0
100
111
270  
271 5 ▶ return $self->{prefix} ||= $self->path;
Condition66%2/3
$self->{"prefix"} ||= $self->path
l!l&&r!l&&!r
410
MC/DC0%0/2
$self->{"prefix"} ||= $self->path
$self->{"prefix"} $self->path
Truth table66%2/3
A ||= B
A= $self->{"prefix"}B= $self->path
ABresult
1X1
011
000
272 };
273  
274 =head2 get_url_base()
275  
276 Get scheme, server, and port of the application.
277  
278 B<[EXPERIMENTAL]> Name and meaning subject to change.
279  
280 =head2 get_url_rel( ... )
281  
282 =over
283  
284 =item * C<$req-E<gt>get_url_rel( %override )>
285  
286 =back
287  
288 Produce a relative link to the page being served,
289 possibly overriding some parameters.
290  
291 Parameter order is NOT preserved. If parameter is empty or C<undef>,
292 it is skipped.
293  
294 B<[CAUTION]> Multiple values are ignored, this MAY change in the future.
295  
296 B<[CAUTION]> For a POST request, normal parameters are used instead of URL
297 parameters (see C<url_param>). This MAY change in the future.
298  
299 B<[EXPERIMENTAL]> Name and meaning subject to change.
300  
301 =head2 get_url_full( ... )
302  
303 =over
304  
305 =item * C<$req-E<gt>get_url_full( %override )>
306  
307 =back
308  
309 Same as above, but prefixed with schema, server name, and port.
310  
311 B<[EXPERIMENTAL]> Name and meaning subject to change.
312  
313 =cut
314  
315 3 ▶sub get_url_rel {
Subroutine get_url_rel: called CC=2 SCAR=7.0
Pod documented
316 3 my ($self, %override) = @_;
317  
318 3 my %h = (%{ $self->_all_params }, %override );
319  
320 return $self->path . '?' . join '&'
321 4 , map { uri_escape_utf8($_) . "=" .uri_escape_utf8($h{$_}) }
322 3 ▶ grep { defined $h{$_} && length $h{$_} }
Condition66%2/3
defined $h{$_} && length $h{$_}
!ll&&!rl&&r
304
MC/DC50%1/2
defined $h{$_} && length $h{$_}
defined $h{$_} length $h{$_}
Truth table66%2/3
A && B
A= defined $h{$_}B= length $h{$_}
ABresult
0X0
100
111
323 sort keys %h;
324 };
325  
326 94 my %port_scheme = (
327 http => 80,
328 https => 443,
329 );
330  
331 3 ▶sub get_url_base {
Subroutine get_url_base: called CC=3 SCAR=11.1
Pod documented
332 3 my $self = shift;
333  
334 # skip well-known ports
335 3 ▶ my $port = ($self->port == ($port_scheme{ $self->scheme } || 0))
Branch: 1 branch
BranchTrueFalseTotal
$self->port == ($port_scheme{$self->scheme} || 0) ? : 2 1 3
Condition50%1/2
$port_scheme{$self->scheme} || 0
l!l
30
MC/DC0%0/1
$port_scheme{$self->scheme} || 0
$port_scheme{$self->scheme}
Truth table50%1/2
A
A= $port_scheme{$self->scheme}
Aresult
11
00
336 ? ''
337 : ':'.$self->port;
338  
339 3 return join "", $self->scheme, "://", $self->hostname, $port;
340 };
341  
342 3 ▶sub get_url_full {
Subroutine get_url_full: called CC=1 SCAR=0.0
Pod documented
343 3 my $self = shift;
344 3 return $self->get_url_base . $self->get_url_rel(@_);
345 };
346  
347 =head2 postfix()
348  
349 Returns the part of URI path beyond what matched the application's path.
350  
351 Contrary to the
352 L<CGI specification|https://tools.ietf.org/html/rfc3875#section-4.1.5>,
353 the leading slash is REMOVED.
354  
355 The validation regex for this value MUST be specified during application
356 setup as C<path_info_regex>. See C<route> in L<MVC::Neaf>.
357  
358 B<[EXPERIMENTAL]> This part of API is undergoing changes.
359  
360 =cut
361  
362 18 ▶sub postfix {
Subroutine postfix: called CC=1 SCAR=0.0
Pod documented
363 18 my ($self) = @_;
364  
365 18 return $self->{postfix};
366 };
367  
368 =head2 splat()
369  
370 Return a list of matched capture groups found in path_info_regex, if any.
371  
372 =cut
373  
374 1 ▶sub splat {
Subroutine splat: called CC=2 SCAR=7.1
Pod documented
375 1 my $self = shift;
376  
377 1 ▶ return @{ $self->{path_info_split} || [] };
Condition50%1/2
$self->{'path_info_split'} || []
l!l
10
MC/DC0%0/1
$self->{'path_info_split'} || []
$self->{'path_info_split'}
Truth table50%1/2
A
A= $self->{'path_info_split'}
Aresult
11
00
378 };
379  
380 # This is somewhat ugly.
381 # When a route is matched, we'll store it
382 # and _also_ the leftovers of regex splitting that happens around that moment
383 293 ▶sub _import_route {
Subroutine _import_route: called CC=2 SCAR=6.9
384 293 my ($self, $route, $path, $path_info, $tail) = @_;
385  
386 293 $self->{route} = $route;
387 293 ▶ if (defined $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $path) 136 157 293
388 136 $self->{prefix} = $path;
389 136 $self->{postfix} = $path_info;
390 136 $self->{path_info_split} = $tail;
391 };
392  
393 293 return $self;
394 };
395  
396 =head2 set_path_info( ... )
397  
398 =over
399  
400 =item * C<$req-E<gt>set_path_info( $path_info )>
401  
402 =back
403  
404 Sets path_info to new value.
405  
406 Also updates path() value so that path = script_name + path_info
407 still holds.
408  
409 Returns self.
410  
411 =cut
412  
413 2 ▶sub set_path_info {
Subroutine set_path_info: called CC=3 SCAR=11.0
Pod documented
414 2 my ($self, $path_info) = @_;
415  
416 2 ▶ $path_info = '' unless defined $path_info;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path_info 1 1 2
417 # CANONIZE
418 2 $path_info =~ s#^/+##;
419  
420 2 $self->{postfix} = $path_info;
421 $self->{path} = $self->script_name
422 2 ▶ .(length $self->{postfix} ? "/$self->{postfix}" : '');
Branch: 1 branch
BranchTrueFalseTotal
length $self->{'postfix'} ? : 1 1 2
423  
424 2 return $self;
425 };
426  
427 =head2 param( ... )
428  
429 =over
430  
431 =item * $req->param( $name, $regex )
432  
433 =item * $req->param( $name, $regex, $default )
434  
435 =back
436  
437 Return parameter, if it passes regex check, default value or C<undef> otherwise.
438  
439 The regular expression is applied to the WHOLE string,
440 from beginning to end, not just the middle.
441 Use '.*' if you really trust the data.
442  
443 Dies if regular expression didn't match and the route has the C<strict> flag.
444  
445 B<[EXPERIMENTAL]> If C<param_regex> hash was given during route definition,
446 C<$regex> MAY be omitted for params that were listed there.
447 This feature is not stable yet, though. Use with care.
448  
449 If method other than GET/HEAD is being used, whatever is in the
450 address line after ? is IGNORED.
451 Use L<url_param> (see below) if you intend to mix GET/POST parameters.
452  
453 B<[NOTE]> C<param()> ALWAYS returns a single value, even in list context.
454 Use C<multi_param()> (see below) if you really want a list.
455  
456 B<[NOTE]> C<param()> has I<nothing to do> with getting parameter list from request.
457 Instead, use form with wildcards:
458  
459 neaf form => "my_form" => [ [ 'guest\d+' => '.*'], [ 'arrival\d+' => '.*' ] ],
460 engine => 'Wildcard';
461  
462 # later in controller
463 my $guests = $req->form("my_form");
464 $guests->fields; # has guest1 & arrival1, guest2 & arrival2 etc
465 $guests->error; # hash with values that didn't match regex
466  
467 See L<MVC::Neaf::X::Form::Wildcard>.
468  
469 =cut
470  
471 43 ▶sub param {
Subroutine param: called CC=7 SCAR=19.5
Pod documented
472 43 my ($self, $name, $regex, $default) = @_;
473  
474 43 ▶ $regex ||= $self->{route}{param_regex}{$name};
Condition100%3/3
$regex ||= $self->{"route"}{"param_regex"}{$name}
l!l&&r!l&&!r
3652
MC/DC100%2/2
$regex ||= $self->{"route"}{"param_regex"}{$name}
$regex $self->{"route"}{"param_regex"}{$name}
Truth table100%3/3
A ||= B
A= $regexB= $self->{"route"}{"param_regex"}{$name}
ABresult
1X1
011
000
475  
476 43 ▶ $self->_croak( "NEAF: param(): a validation regex is REQUIRED" )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $regex 2 41 43
477 unless defined $regex;
478  
479 # Some write-through caching
480 41 my $value = $self->_all_params->{ $name };
481  
482 41 ▶ return $default if !defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 15 26 41
483 26 ▶ return $value if $value =~ /^(?:$regex)$/s;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /^(?:$regex)$/s 21 5 26
484  
485 5 ▶ if (length $value && $self->route->strict) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $value and $self->route->strict) 1 4 5
Condition100%3/3
length $value and $self->route->strict
!ll&&!rl&&r
131
MC/DC100%2/2
length $value and $self->route->strict
length $value $self->route->strict
Truth table100%3/3
A and B
A= length $valueB= $self->route->strict
ABresult
0X0
100
111
486 1 die 422; # TODO 0.30 configurable die message
487 };
488 4 return $default;
489 };
490  
491 =head2 url_param( ... )
492  
493 =over
494  
495 =item * C<$req-E<gt>url_param( name =E<gt> qr/regex/ )>
496  
497 =back
498  
499 If method is GET or HEAD, identical to C<param>.
500  
501 Otherwise would return the parameter from query string,
502 AS IF it was a GET request.
503  
504 Dies if regular expression didn't match and the route has the C<strict> flag.
505  
506 Multiple values are deliberately ignored.
507  
508 See L<CGI>.
509  
510 =cut
511  
512 94 our %query_allowed = ( GET => 1, HEAD => 1);
513 2 ▶sub url_param {
Subroutine url_param: called CC=10 SCAR=28.3
Pod documented
514 2 my ($self, $name, $regex, $default) = @_;
515  
516 2 ▶ if ($query_allowed{ $self->method }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($MVC::Neaf::Request::query_allowed{$self->method}) 1 1 2
517 1 return $self->param( $name, $regex, $default );
518 };
519  
520 # HACK here - some lazy caching + parsing string by hand
521 1 ▶ $self->{url_param_hash} ||= do {
Condition33%1/3
$self->{"url_param_hash"} ||= do { my %hash; foreach $_ (split(/[&;]/, $self->{"query_string"} || "", 0)) { /^(.*?)(?:=(.*))?$/ or next; $hash{$1} = $2; } ; +{map({&decode_utf8(scalar uri_unescape($_));} %hash)} }
l!l&&r!l&&!r
010
MC/DC0%0/2
$self->{"url_param_hash"} ||= do { my %hash; foreach $_ (split(/[&;]/, $self->{"query_string"} || "", 0)) { /^(.*?)(?:=(.*))?$/ or next; $hash{$1} = $2; } ; +{map({&decode_utf8(scalar uri_unescape($_));} %hash)} }
$self->{"url_param_hash"} do { my %hash; foreach $_ (split(/[&;]/, $self->{"query_string"} || "", 0)) { /^(.*?)(?:=(.*))?$/ or next; $hash{$1} = $2; } ; +{map({&decode_utf8(scalar uri_unescape($_));} %hash)} }
Truth table33%1/3
A ||= B
A= $self->{"url_param_hash"}B= do { my %hash; foreach $_ (split(/[&;]/, $self->{"query_string"} || "", 0)) { /^(.*?)(?:=(.*))?$/ or next; $hash{$1} = $2; } ; +{map({&decode_utf8(scalar uri_unescape($_));} %hash)} }
ABresult
1X1
011
000
522 1 my %hash;
523  
524 1 ▶ foreach (split /[&;]/, $self->{query_string} || '' ) {
Condition50%1/2
$self->{'query_string'} || ''
l!l
10
MC/DC0%0/1
$self->{'query_string'} || ''
$self->{'query_string'}
Truth table50%1/2
A
A= $self->{'query_string'}
Aresult
11
00
525 1 ▶ /^(.*?)(?:=(.*))?$/ or next;
Branch: 1 branch
BranchTrueFalseTotal
/^(.*?)(?:=(.*))?$/ or next 1 0 1
526 1 $hash{$1} = $2;
527 };
528  
529 # causes error w/o + (context issues?)
530 # do decoding AFTER uniq'ing params (plus it was simpler to write)
531 1 +{ map { decode_utf8(uri_unescape($_)) } %hash };
532 };
533 1 my $value = $self->{url_param_hash}{$name};
534  
535 # this is copypaste from param(), do something (or don't)
536 1 ▶ return $default if !defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 1 1
537 1 ▶ return $value if $value =~ /^(?:$regex)$/s;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /^(?:$regex)$/s 1 0 1
538  
539 0 ▶ if (length $value && $self->route->strict) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $value and $self->route->strict) 0 0 0
Condition0%0/3
length $value and $self->route->strict
!ll&&!rl&&r
000
MC/DC0%0/2
length $value and $self->route->strict
length $value $self->route->strict
Truth table0%0/3
A and B
A= length $valueB= $self->route->strict
ABresult
0X0
100
111
540 0 die 422; # TODO 0.30 configurable die message
541 };
542 0 return $default;
543 };
544  
545 =head2 multi_param( ... )
546  
547 =over
548  
549 =item * C<$req-E<gt>multi_param( name =E<gt> qr/regex/ )>
550  
551 =back
552  
553 Get a multiple value GET/POST parameter as a C<@list>.
554 The name generally follows that of newer L<CGI> (4.08+).
555  
556 ALL values must match the regex, or an empty list is returned.
557 Dies if strict mode if enabled for route and there is a mismatch.
558  
559 B<[EXPERIMENTAL]> If C<param_regex> hash was given during route definition,
560 C<$regex> MAY be omitted for params that were listed there.
561 This feature is not stable yet, though. Use with care.
562  
563 B<[EXPERIMENTAL]> This method's behavior MAY change in the future.
564 Please be careful when upgrading.
565  
566 =cut
567  
568 # TODO 0.90 merge multi_param, param, and _all_params
569 # backend mechanism.
570  
571 9 ▶sub multi_param {
Subroutine multi_param: called CC=6 SCAR=18.1
Pod documented
572 9 my ($self, $name, $regex) = @_;
573  
574 9 ▶ $regex ||= $self->{route}{param_regex}{$name};
Condition66%2/3
$regex ||= $self->{"route"}{"param_regex"}{$name}
l!l&&r!l&&!r
540
MC/DC0%0/2
$regex ||= $self->{"route"}{"param_regex"}{$name}
$regex $self->{"route"}{"param_regex"}{$name}
Truth table66%2/3
A ||= B
A= $regexB= $self->{"route"}{"param_regex"}{$name}
ABresult
1X1
011
000
575 9 ▶ $self->_croak( "validation regex is REQUIRED" )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $regex 0 9 9
576 unless defined $regex;
577  
578 my $ret = $self->{multi_param}{$name} ||= [
579 9 ▶ map { decode_utf8($_) } $self->do_get_param_as_array( $name ),
Condition100%2/2
$self->{"multi_param"}{$name} ||= [map({&decode_utf8($_);} $self->do_get_param_as_array($name))]
l!l
27
MC/DC100%1/1
$self->{"multi_param"}{$name} ||= [map({&decode_utf8($_);} $self->do_get_param_as_array($name))]
$self->{"multi_param"}{$name}
Truth table100%2/2
A
A= $self->{"multi_param"}{$name}
Aresult
11
00
580 ];
581  
582 # ANY mismatch = no go. Replace with simple grep if want filter EVER.
583 9 ▶ if (grep { !/^(?:$regex)$/s } @$ret) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {not /^(?:$regex)$/s;} @$ret) { } 3 6 9
584 3 ▶ die 422 if $self->route->strict;
Branch: 1 branch
BranchTrueFalseTotal
if $self->route->strict 0 3 3
585 3 return ();
586 } else {
587 6 return @$ret;
588 };
589 };
590  
591 =head2 set_param( ... )
592  
593 =over
594  
595 =item * C<$req-E<gt>set_param( name =E<gt> $value )>
596  
597 =back
598  
599 Override form parameter. Returns self.
600  
601 =cut
602  
603 1 ▶sub set_param {
Subroutine set_param: called CC=1 SCAR=0.0
Pod documented
604 1 my ($self, $name, $value) = @_;
605  
606 1 $self->{cached_params}{$name} = $value;
607 1 return $self;
608 };
609  
610 =head2 form( ... )
611  
612 =over
613  
614 =item * C<$req-E<gt>form( $validator )>
615  
616 =back
617  
618 Apply validator to raw params and return whatever it returns.
619  
620 A validator MUST be an object with C<validate> method, or a coderef,
621 or a symbolic name registered earlier via C<neaf form ...>.
622  
623 Neaf's own validators, C<MVC::Neaf::X::Form> and C<MVC::Neaf::X::Form::LIVR>,
624 will return a C<MVC::Neaf::X::Form::Data> object with the following methods:
625  
626 =over
627  
628 =item * is_valid - tells whether data passed validation
629  
630 =item * error - hash of errors, can also be modified if needed:
631  
632 $result->error( myfield => "Correct, but not found in database" );
633  
634 =item * data - hash of valid, cleaned data
635  
636 =item * raw - hash of data entered initially, may be useful to display
637 input form again.
638  
639 =back
640  
641 You are encouraged to use this return format from your own validation class
642 or propose improvements.
643  
644 =cut
645  
646 7 ▶sub form {
Subroutine form: called CC=4 SCAR=14.5
Pod documented
647 7 my ($self, $validator) = @_;
648  
649 7 ▶ if (!ref $validator) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $validator) 4 3 7
650 4 ▶ $validator = $self->{route}->get_form( $validator )
Condition33%1/3
$self->{'route'}->get_form($validator) || $self->_croak("Unknown form name $validator")
l!l&&r!l&&!r
300
MC/DC0%0/2
$self->{'route'}->get_form($validator) || $self->_croak("Unknown form name $validator")
$self->{'route'}->get_form($validator) $self->_croak("Unknown form name $validator")
Truth table33%1/3
A || B
A= $self->{'route'}->get_form($validator)B= $self->_croak("Unknown form name $validator")
ABresult
1X1
011
000
651 || $self->_croak("Unknown form name $validator");
652 };
653  
654 6 ▶ my $result = (ref $validator eq 'CODE')
Branch: 1 branch
BranchTrueFalseTotal
ref $validator eq 'CODE' ? : 0 6 6
655 ? $validator->( $self->_all_params )
656 : $validator->validate( $self->_all_params );
657  
658 6 return $result;
659 };
660  
661 =head2 get_form_as_list( ... )
662  
663 =over
664  
665 =item * C<$req-E<gt>get_form_as_list( qr/.../, qw(name1 name2 ...) )>
666  
667 =back
668  
669 =head2 get_form_as_list( ... )
670  
671 =over
672  
673 =item * C<$req-E<gt>get_form_as_list( [ qr/.../, "default" ], qw(name1 name2 ...) )>
674  
675 =back
676  
677 Return a group of uniform parameters as a list, in that order.
678 Values that fail validation are returned as C<undef>, unless default given.
679  
680 B<[EXPERIMENTAL]> The name MAY be changed in the future.
681  
682 =cut
683  
684 2 ▶sub get_form_as_list {
Subroutine get_form_as_list: called CC=3 SCAR=11.0
Pod documented
685 2 my ($self, $spec, @list) = @_;
686  
687 2 ▶ $self->_croak( "Meaningless call in scalar context" )
Branch: 1 branch
BranchTrueFalseTotal
unless wantarray 0 2 2
688 unless wantarray;
689  
690 2 ▶ $spec = [ $spec, undef ]
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "ARRAY" 1 1 2
691 unless ref $spec eq 'ARRAY';
692  
693 # Call the same validation over for each parameter
694 2 return map { $self->param( $_, @$spec ); } @list;
695 };
696  
697 51 ▶sub _all_params {
Subroutine _all_params: called CC=3 SCAR=11.0
698 51 my $self = shift;
699  
700 51 ▶ return $self->{cached_params} ||= do {
Condition66%2/3
$self->{"cached_params"} ||= do { my $raw = $self->do_get_params; $_ = &decode_utf8($_) foreach (values %$raw); $raw }
l!l&&r!l&&!r
15360
MC/DC0%0/2
$self->{"cached_params"} ||= do { my $raw = $self->do_get_params; $_ = &decode_utf8($_) foreach (values %$raw); $raw }
$self->{"cached_params"} do { my $raw = $self->do_get_params; $_ = &decode_utf8($_) foreach (values %$raw); $raw }
Truth table66%2/3
A ||= B
A= $self->{"cached_params"}B= do { my $raw = $self->do_get_params; $_ = &decode_utf8($_) foreach (values %$raw); $raw }
ABresult
1X1
011
000
701 36 my $raw = $self->do_get_params;
702  
703 $_ = decode_utf8($_)
704 36 for (values %$raw);
705  
706 36 $raw;
707 };
708 };
709  
710 =head2 body()
711  
712 See L</body_raw> below.
713  
714 =head2 body_text()
715  
716 Returns request body for PUT/POST requests as unicode text.
717  
718 B<WARNING> Encodings other than UTF-8 are not supported as of yet.
719  
720 =head2 body_json()
721  
722 Get decoded request body in JSON format.
723 In case of errors, error 422 is thrown.
724  
725 =head2 body_raw()
726  
727 Returns request body for PUT/POST requests as binary data.
728 Decoding and validation is left up to the user.
729  
730 =cut
731  
732 6 ▶sub body_raw {
Subroutine body_raw: called CC=3 SCAR=11.4
Pod documented
733 6 my $self = shift;
734  
735 carp ("MVC::Neaf: using body() is discouraged for method ".$self->method)
736 6 ▶ if ($query_allowed{$self->method});
Branch: 1 branch
BranchTrueFalseTotal
if $MVC::Neaf::Request::query_allowed{$self->method} 0 6 6
737  
738 $self->{body} = $self->do_get_body
739 6 ▶ unless exists $self->{body};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"body"} 6 0 6
740  
741 6 return $self->{body};
742 };
743  
744 94 *body = *body = \&body_raw;
745  
746 0 ▶_helper_fallback( body_text => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
747 0 my $self = shift;
748  
749 # TODO adhere to charset= in content_type
750 0 return decode_utf8( $self->body_raw );
751 94 });
752  
753 94 my $codec = JSON->new->utf8->allow_nonref;
754 5 ▶_helper_fallback( body_json => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
755 5 my ($self, $validator) = @_;
756  
757 # TODO add validator support - if fails, also 422
758 # TODO but note validator is likely to be path-specific, not call-specific
759 5 my $data;
760 eval {
761 # Content-Type must be application/json or empty
762 5 ▶ $self->content_type =~ /^(application\/json\b|$)/
Branch: 1 branch
BranchTrueFalseTotal
$self->content_type =~ m[^(application/json\b|$)] or die 'Unexpected content type for body_json: ' . $self->content_type 4 1 5
763 or die "Unexpected content type for body_json: ".$self->content_type;
764 4 $data = $codec->decode( $self->body );
765 3 1;
766 5 ▶ } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->content_type =~ m[^(application/json\b|$)] or die 'Unexpected content type for body_json: ' . $self->content_type; $data = $codec->decode($self->body); 1 } } or do { $@ =~ s/at \S+ line \d+\.?\n?$//; $self->log_message("warning", 'Failed to read JSON from request via body_json(): ' . $@); die 422 } 3 2 5
767 # TODO do we need to log error here?
768 2 $@ =~ s/at \S+ line \d+\.?\n?$//;
769 2 $self->log_message( warning => "Failed to read JSON from request via body_json(): ".$@);
770 2 die 422;
771 };
772  
773 3 return $data;
774 94 } );
775  
776 =head2 upload_utf8( ... )
777  
778 =head2 upload_raw( ... )
779  
780 =over
781  
782 =item * C<$req-E<gt>upload_utf8( "name" )>
783  
784 Returns an L<MVC::Neaf::Upload> object corresponding to an uploaded file,
785 if such uploaded file is present.
786  
787 All data read from such upload will be converted to unicode,
788 raising an exception if decoding ever fails.
789  
790 An upload object has at least C<handle> and C<content> methods to work with
791 data:
792  
793 my $upload = $req->upload("user_file");
794 if ($upload) {
795 my $untrusted_filename = $upload->filename;
796 my $fd = $upload->handle;
797 while (<$fd>) {
798 ...
799 };
800 }
801  
802 or just
803  
804 if ($upload) {
805 while ($upload->content =~ /(...)/g) {
806 do_something($1);
807 };
808 };
809  
810 =item * C<$req-E<gt>upload_raw( "name" )>
811  
812 Like above, but no decoding whatsoever is performed.
813  
814 =back
815  
816 =cut
817  
818 0 ▶sub upload_utf8 {
Subroutine upload_utf8: not called CC=1 SCAR=6.9
Pod documented
819 0 my ($self, $name) = @_;
820 0 return $self->_upload( id => $name, utf8 => 1 );
821 };
822  
823 1 ▶sub upload_raw {
Subroutine upload_raw: called CC=1 SCAR=0.0
Pod documented
824 1 my ($self, $name) = @_;
825 1 return $self->_upload( id => $name, utf8 => 0 );
826 };
827  
828 # TODO 0.30 do something about upload's content type
829 # TODO 0.30 and btw, restrict content types!
830 1 ▶sub _upload {
Subroutine _upload: called CC=4 SCAR=14.5
831 1 my ($self, %args) = @_;
832  
833 my $id = $args{id}
834 1 ▶ or $self->_croak( "upload name is required for upload" );
Branch: 1 branch
BranchTrueFalseTotal
my $id = $args{"id"} or $self->_croak("upload name is required for upload") 1 0 1
835 # caching undef as well, so exists()
836 1 ▶ if (!exists $self->{uploads}{$id}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"uploads"}{$id}) 1 0 1
837 1 my $raw = $self->do_get_upload( $id );
838 1 ▶ $self->{uploads}{$id} = (ref $raw eq 'HASH')
Branch: 1 branch
BranchTrueFalseTotal
ref $raw eq 'HASH' ? : 0 1 1
839 ? MVC::Neaf::Upload->new( %$raw, %args )
840 : undef;
841 };
842  
843 1 return $self->{uploads}{$id};
844 };
845  
846 =head2 get_cookie( ... )
847  
848 =over
849  
850 =item * C<$req-E<gt>get_cookie( "name" =E<gt> qr/regex/ [, "default" ] )>
851  
852 =back
853  
854 Fetch client cookie.
855 The cookie MUST be sanitized by regular expression.
856  
857 The regular expression is applied to the WHOLE string,
858 from beginning to end, not just the middle.
859 Use '.*' if you really need none.
860  
861 Dies if regular expression didn't match and the route has the C<strict> flag.
862  
863 =cut
864  
865 31 ▶sub get_cookie {
Subroutine get_cookie: called CC=10 SCAR=23.6
Pod documented
866 31 my ($self, $name, $regex, $default) = @_;
867  
868 31 ▶ $default = '' unless defined $default;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $default 30 1 31
869 31 ▶ $self->_croak( "validation regex is REQUIRED")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $regex 0 31 31
870 unless defined $regex;
871  
872 31 ▶ $self->{neaf_cookie_in} ||= do {
Condition66%2/3
$self->{"neaf_cookie_in"} ||= do { my %hash; foreach $_ ($self->header_in("cookie", qr/.*/)) { while (/(\S+?)=([^\s;]*);?/g) { $hash{$1} = &decode_utf8(scalar uri_unescape($2)); } ; } ; \%hash }
l!l&&r!l&&!r
8230
MC/DC0%0/2
$self->{"neaf_cookie_in"} ||= do { my %hash; foreach $_ ($self->header_in("cookie", qr/.*/)) { while (/(\S+?)=([^\s;]*);?/g) { $hash{$1} = &decode_utf8(scalar uri_unescape($2)); } ; } ; \%hash }
$self->{"neaf_cookie_in"} do { my %hash; foreach $_ ($self->header_in("cookie", qr/.*/)) { while (/(\S+?)=([^\s;]*);?/g) { $hash{$1} = &decode_utf8(scalar uri_unescape($2)); } ; } ; \%hash }
Truth table66%2/3
A ||= B
A= $self->{"neaf_cookie_in"}B= do { my %hash; foreach $_ ($self->header_in("cookie", qr/.*/)) { while (/(\S+?)=([^\s;]*);?/g) { $hash{$1} = &decode_utf8(scalar uri_unescape($2)); } ; } ; \%hash }
ABresult
1X1
011
000
873 23 my %hash;
874 23 foreach ($self->header_in('cookie', qr/.*/)) {
875 15 ▶ while (/(\S+?)=([^\s;]*);?/g) {
Branch: 1 branch
BranchTrueFalseTotal
if (/(\S+?)=([^\s;]*);?/g) 21 15 36
876 21 $hash{$1} = decode_utf8(uri_unescape($2));
877 };
878 };
879 23 \%hash;
880 };
881 31 my $value = $self->{neaf_cookie_in}{ $name };
882 31 ▶ return $default unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 10 21 31
883  
884 21 ▶ return $value if $value =~ /^$regex$/;
Branch: 1 branch
BranchTrueFalseTotal
if $value =~ /^$regex$/ 17 4 21
885  
886 4 ▶ if (length $value && $self->route->strict) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $value and $self->route->strict) 4 0 4
Condition33%1/3
length $value and $self->route->strict
!ll&&!rl&&r
004
MC/DC0%0/2
length $value and $self->route->strict
length $value $self->route->strict
Truth table33%1/3
A and B
A= length $valueB= $self->route->strict
ABresult
0X0
100
111
887 4 die 422; # TODO 0.30 configurable die message
888 };
889 0 return $default;
890 };
891  
892 =head2 set_cookie( ... )
893  
894 =over
895  
896 =item * C<$req-E<gt>set_cookie( name =E<gt> "value", %options )>
897  
898 =back
899  
900 Set HTTP cookie. C<%options> may include:
901  
902 =over
903  
904 =item * C<regex> - regular expression to check outgoing value
905  
906 =item * C<ttl> - time to live in seconds.
907 0 means no C<ttl>.
908 Use negative C<ttl> and empty value to delete cookie.
909  
910 =item * C<expire> - UNIX time stamp when the cookie expires
911 (overridden by C<ttl>).
912  
913 =item * C<expires> - B<[DEPRECATED]> - use 'expire' instead (without trailing "s")
914  
915 =item * C<domain>
916  
917 =item * C<path>
918  
919 =item * C<httponly> - flag
920  
921 =item * C<secure> - flag
922  
923 =back
924  
925 Returns self.
926  
927 =cut
928  
929 9 ▶sub set_cookie {
Subroutine set_cookie: called CC=5 SCAR=17.8
Pod documented
930 9 my ($self, $name, $cook, %opt) = @_;
931  
932 9 ▶ defined $opt{regex} and $cook !~ /^$opt{regex}$/
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{"regex"} and not $cook =~ /^$opt{"regex"}$/ and $self->_croak("output value doesn't match regex") 0 9 9
Condition33%1/3
defined $opt{"regex"} and not $cook =~ /^$opt{"regex"}$/
!ll&&!rl&&r
900
MC/DC0%0/2
defined $opt{"regex"} and not $cook =~ /^$opt{"regex"}$/
defined $opt{"regex"} not $cook =~ /^$opt{"regex"}$/
Truth table33%1/3
A and not(B)
A= defined $opt{"regex"}B= not $cook =~ /^$opt{"regex"}$/
ABresult
0X0
100
111
933 and $self->_croak( "output value doesn't match regex" );
934 9 ▶ if (exists $opt{expires}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opt{"expires"}) 0 9 9
935 # TODO 0.30 kill it and croak
936 0 carp( "NEAF set_cookie(): 'expires' parameter DEPRECATED, use 'expire' instead" );
937 0 $opt{expire} = delete $opt{expires};
938 };
939  
940 # Zero ttl is ok and means "no ttl at all".
941 9 ▶ if ($opt{ttl}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"ttl"}) 1 8 9
942 1 $opt{expire} = time + $opt{ttl};
943 };
944  
945 $self->{response}{cookie}{ $name } = [
946 $cook, $opt{regex},
947 $opt{domain}, $opt{path}, $opt{expire}, $opt{secure}, $opt{httponly}
948 9 ];
949  
950 # TODO 0.90 also set cookie_in for great consistency, but don't
951 # break reading cookies from backend by cache vivification!!!
952 9 return $self;
953 };
954  
955 =head2 delete_cookie( ... )
956  
957 =over
958  
959 =item * C<$req-E<gt>delete_cookie( "name" )>
960  
961 =back
962  
963 Remove cookie by setting value to an empty string,
964 and expiration in the past.
965 B<[NOTE]> It is up to the user agent to actually remove cookie.
966  
967 Returns self.
968  
969 =cut
970  
971 1 ▶sub delete_cookie {
Subroutine delete_cookie: called CC=1 SCAR=0.0
Pod documented
972 1 my ($self, $name) = @_;
973 1 return $self->set_cookie( $name => '', ttl => -100000 );
974 };
975  
976 # Set-Cookie: SSID=Ap4P….GTEq; Domain=foo.com; Path=/;
977 # Expires=Wed, 13 Jan 2021 22:23:01 GMT; Secure; HttpOnly
978  
979 =head2 format_cookies
980  
981 Converts stored cookies into an arrayref of scalars
982 ready to be put into Set-Cookie header.
983  
984 =cut
985  
986 160 ▶sub format_cookies {
Subroutine format_cookies: called CC=10 SCAR=23.6
Pod documented
987 160 my $self = shift;
988  
989 160 ▶ my $cookies = $self->{response}{cookie} || {};
Condition100%2/2
$self->{'response'}{'cookie'} || {}
l!l
9151
MC/DC100%1/1
$self->{'response'}{'cookie'} || {}
$self->{'response'}{'cookie'}
Truth table100%2/2
A
A= $self->{'response'}{'cookie'}
Aresult
11
00
990  
991 160 my @out;
992 160 foreach my $name (keys %$cookies) {
993 my ($cook, $regex, $domain, $path, $expire, $secure, $httponly)
994 9 = @{ $cookies->{$name} };
995 9 ▶ next unless defined $cook; # TODO 0.90 erase cookie if undef?
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cook 0 9 9
996  
997 9 ▶ $path = "/" unless defined $path;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path 9 0 9
998 9 ▶ defined $expire and $expire = http_date( $expire );
Branch: 1 branch
BranchTrueFalseTotal
defined $expire and $expire = http_date($expire) 7 2 9
999 9 ▶ my $bake = join "; ", ("$name=".uri_escape_utf8($cook))
Branch: 4 branches
BranchTrueFalseTotal
defined $domain ? : 0 9 9
defined $expire ? : 7 2 9
$secure ? : 0 9 9
$httponly ? : 0 9 9
1000 , defined $domain ? "Domain=$domain" : ()
1001 , "Path=$path"
1002 , defined $expire ? "Expires=$expire" : ()
1003 , $secure ? "Secure" : ()
1004 , $httponly ? "HttpOnly" : ();
1005 9 push @out, $bake;
1006 };
1007 160 return \@out;
1008 };
1009  
1010 =head2 error( ... )
1011  
1012 =over
1013  
1014 =item * C<$req-E<gt>error( status )>
1015  
1016 =back
1017  
1018 Report error to the CORE.
1019  
1020 This throws an C<MVC::Neaf::Exception> object.
1021  
1022 If you're planning calling C<$req-E<gt>error> within C<eval> block,
1023 consider using C<neaf_err> function to let it propagate:
1024  
1025 use MVC::Neaf::Exception qw(neaf_err);
1026  
1027 eval {
1028 $req->error(422)
1029 if ($foo);
1030 $req->redirect( "http://google.com" )
1031 if ($bar);
1032 };
1033 if ($@) {
1034 neaf_err($@);
1035 # The rest of the catch block
1036 };
1037  
1038 =cut
1039  
1040 1 ▶sub error {
Subroutine error: called CC=1 SCAR=0.0
Pod documented
1041 1 my $self = shift;
1042 1 die MVC::Neaf::Exception->new(@_);
1043 };
1044  
1045 =head2 redirect( ... )
1046  
1047 =over
1048  
1049 =item * C<$req-E<gt>redirect( $location )>
1050  
1051 =back
1052  
1053 Redirect to a new location.
1054  
1055 This throws an MVC::Neaf::Exception object.
1056 See C<error()> discussion above.
1057  
1058 =cut
1059  
1060 2 ▶sub redirect {
Subroutine redirect: called CC=1 SCAR=0.0
Pod documented
1061 2 my ($self, $location) = @_;
1062  
1063 2 die MVC::Neaf::Exception->new(
1064 -status => 302,
1065 -location => $location,
1066 -content => 'See '.$location,
1067 -type => 'text/plain',
1068 );
1069 };
1070  
1071 =head2 header_in( ... )
1072  
1073 =over
1074  
1075 =item * C<header_in()> - return headers as-is
1076  
1077 =item * C<$req-E<gt>header_in( "header_name", qr/.../ )>
1078  
1079 =back
1080  
1081 Fetch HTTP header sent by client.
1082 Header names are canonized,
1083 so C<Http-Header>, C<HTTP_HEADER> and C<http_header> are all the same.
1084  
1085 Without argument, returns a L<HTTP::Headers::Fast> object.
1086  
1087 With a name, returns all values for that header in list context,
1088 or ", " - joined value as one scalar in scalar context.
1089 An empty string is returned if no such header is present.
1090  
1091 If regex fails to match I<any> of the header values, error 422 is thrown.
1092  
1093 This call still works without regex, but such behavior is deprecated.
1094  
1095 =cut
1096  
1097 43 ▶sub header_in {
Subroutine header_in: called CC=9 SCAR=22.0
Pod documented
1098 43 my ($self, $name, $regex) = @_;
1099  
1100 43 ▶ $self->{header_in} ||= $self->do_get_header_in;
Condition66%2/3
$self->{"header_in"} ||= $self->do_get_header_in
l!l&&r!l&&!r
14290
MC/DC0%0/2
$self->{"header_in"} ||= $self->do_get_header_in
$self->{"header_in"} $self->do_get_header_in
Truth table66%2/3
A ||= B
A= $self->{"header_in"}B= $self->do_get_header_in
ABresult
1X1
011
000
1101 43 ▶ return $self->{header_in} unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 3 40 43
1102  
1103 40 $name = lc $name;
1104 40 $name =~ s/-/_/g;
1105 40 my @list = $self->{header_in}->header( $name );
1106  
1107 # TODO 0.30 deprecate w/o regex
1108 40 ▶ if ($regex) {
Branch: 1 branch
BranchTrueFalseTotal
if ($regex) 37 3 40
1109 37 ▶ $regex = qr/^$regex$/
Branch: 1 branch
BranchTrueFalseTotal
unless ref $regex and ref $regex eq "Regexp" 3 34 37
Condition66%2/3
ref $regex and ref $regex eq "Regexp"
!ll&&!rl&&r
3034
MC/DC50%1/2
ref $regex and ref $regex eq "Regexp"
ref $regex ref $regex eq "Regexp"
Truth table66%2/3
A and B
A= ref $regexB= ref $regex eq "Regexp"
ABresult
0X0
100
111
1110 unless ref $regex and ref $regex eq 'Regexp';
1111 $_ =~ $regex or die 422 # TODO 0.30 configurable
1112 37 ▶ for @list;
Branch: 1 branch
BranchTrueFalseTotal
$_ =~ /$regex/ or die 422 26 2 28
1113 };
1114  
1115 38 ▶ return wantarray ? @list : join ', ', @list;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 26 12 38
1116 };
1117  
1118 =head2 referer
1119  
1120 Get/set HTTP referrer - i.e. where the request pretends to come from.
1121  
1122 B<[NOTE]> Avoid using this for anything serious/secure - too easy to forge.
1123  
1124 =cut
1125  
1126 2 ▶sub referer {
Subroutine referer: called CC=3 SCAR=12.0
Pod documented
1127 2 my $self = shift;
1128 2 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 0 2 2
1129 $self->{referer} = shift
1130 0 } else {
1131 2 ▶ return $self->{referer} ||= $self->header_in( 'referer', qr/.*/ );
Condition66%2/3
$self->{"referer"} ||= $self->header_in("referer", qr/.*/)
l!l&&r!l&&!r
110
MC/DC0%0/2
$self->{"referer"} ||= $self->header_in("referer", qr/.*/)
$self->{"referer"} $self->header_in("referer", qr/.*/)
Truth table66%2/3
A ||= B
A= $self->{"referer"}B= $self->header_in("referer", qr/.*/)
ABresult
1X1
011
000
1132 };
1133 };
1134  
1135 =head2 user_agent
1136  
1137 Get/set user_agent.
1138  
1139 B<[NOTE]> Avoid using user_agent for anything serious - too easy to forge.
1140  
1141 =cut
1142  
1143 3 ▶sub user_agent {
Subroutine user_agent: called CC=3 SCAR=11.3
Pod documented
1144 3 my $self = shift;
1145 3 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) { } 0 3 3
1146 $self->{user_agent} = shift
1147 0 } else {
1148 $self->{user_agent} = $self->header_in( 'user_agent', qr/.*/ )
1149 3 ▶ unless exists $self->{user_agent};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"user_agent"} 2 1 3
1150 3 return $self->{user_agent};
1151 };
1152 };
1153  
1154 =head2 content_type
1155  
1156 Returns C<Content-Type> request header, if present, or an empty string.
1157  
1158 The usage of Content-Type in GET/HEAD requests is discouraged.
1159 See also L<body>.
1160  
1161 =cut
1162  
1163 6 ▶sub content_type {
Subroutine content_type: called CC=4 SCAR=14.6
Pod documented
1164 6 my ($self, $regex) = @_;
1165  
1166 carp ("MVC::Neaf: using content_type is discouraged for method ".$self->method)
1167 6 ▶ if ($query_allowed{$self->method});
Branch: 1 branch
BranchTrueFalseTotal
if $MVC::Neaf::Request::query_allowed{$self->method} 0 6 6
1168  
1169 6 ▶ my $ctype = $self->header_in('content_type', $regex || qr/.*/);
Condition50%1/2
$regex || qr/.*/
l!l
06
MC/DC0%0/1
$regex || qr/.*/
$regex
Truth table50%1/2
A
A= $regex
Aresult
11
00
1170 6 ▶ $ctype = '' unless defined $ctype;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ctype 0 6 6
1171  
1172 6 return $ctype;
1173 };
1174  
1175 =head2 dump ()
1176  
1177 Dump whatever came in the request. Useful for debugging.
1178  
1179 =cut
1180  
1181 1 ▶sub dump {
Subroutine dump: called CC=3 SCAR=11.0
Pod documented
1182 1 my $self = shift;
1183  
1184 1 my %raw;
1185 1 foreach my $method (qw( http_version scheme secure method hostname port
1186 path script_name
1187 referer user_agent )) {
1188 10 $raw{$method} = eval { $self->$method }; # deliberately skip errors
1189 };
1190 1 $raw{param} = $self->_all_params;
1191 1 $raw{header_in} = $self->header_in->as_string;
1192 1 $self->get_cookie( noexist => '' ); # warm up cookie cache
1193 1 $raw{cookie_in} = $self->{neaf_cookie_in};
1194 $raw{path_info} = $self->{postfix}
1195 1 ▶ if defined $self->{postfix};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"postfix"} 1 0 1
1196  
1197 1 return \%raw;
1198 };
1199  
1200 =head1 SESSION MANAGEMENT
1201  
1202 =head2 session()
1203  
1204 Get reference to session data.
1205 This reference is guaranteed to be the same throughout the request lifetime.
1206  
1207 If MVC::Neaf->set_session_handler() was called during application setup,
1208 this data will be initialized by that handler;
1209 otherwise initializes with an empty hash (or whatever session engine generates).
1210  
1211 If session engine was not provided, dies instead.
1212  
1213 See L<MVC::Neaf::X::Session> for details about session engine internal API.
1214  
1215 =cut
1216  
1217 21 ▶sub session {
Subroutine session: called CC=2 SCAR=6.9
Pod documented
1218 21 my $self = shift;
1219  
1220 21 ▶ if (my $sess = $self->load_session) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sess = $self->load_session) 16 4 20
1221 16 return $sess;
1222 };
1223  
1224 4 return $self->{session} = $self->_session_setup->{engine}->create_session;
1225 };
1226  
1227 =head2 load_session
1228  
1229 Like above, but don't create session - just fetch from cookies & storage.
1230  
1231 Never tries to load anything if session already loaded or created.
1232  
1233 =cut
1234  
1235 23 ▶sub load_session {
Subroutine load_session: called CC=9 SCAR=22.2
Pod documented
1236 23 my $self = shift;
1237  
1238 # aggressive caching FTW
1239 23 ▶ return $self->{session} if exists $self->{session};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"session"} 11 12 23
1240  
1241 12 my $setup = $self->_session_setup;
1242 12 ▶ $self->_croak("No session engine found, use Request->stash() for per-request data")
Branch: 1 branch
BranchTrueFalseTotal
unless $setup 0 12 12
1243 unless $setup;
1244  
1245 # Try loading session...
1246 12 my $id = $self->get_cookie( $setup->{cookie}, $setup->{regex} );
1247 12 ▶ my $hash = ($id && $setup->{engine}->load_session( $id ));
Condition66%2/3
$id && $setup->{'engine'}->load_session($id)
!ll&&!rl&&r
309
MC/DC50%1/2
$id && $setup->{'engine'}->load_session($id)
$id $setup->{'engine'}->load_session($id)
Truth table66%2/3
A && B
A= $idB= $setup->{'engine'}->load_session($id)
ABresult
0X0
100
111
1248  
1249 12 ▶ if (!$hash) {
Branch: 3 branches
BranchTrueFalseTotal
if (not $hash) { } 3 9 12
elsif (ref $hash ne 'HASH') { } 1 8 9
elsif ($hash->{'data'}) { } 7 1 8
1250 3 return;
1251 } elsif ( ref $hash ne 'HASH' ) {
1252 $self->_croak( (ref $setup->{engine})
1253 1 ."->load_session must return a HASH and not ".(ref $hash) );
1254 } elsif ($hash->{data} ) {
1255 # Loaded, cache it & refresh if needed
1256 7 $self->{session} = $hash->{data};
1257  
1258 $self->set_cookie(
1259 $setup->{cookie} => $hash->{id},
1260 expire => $hash->{expire} || $setup->{expire},
1261 )
1262 7 ▶ if $hash->{id};
Branch: 1 branch
BranchTrueFalseTotal
if $hash->{"id"} 1 6 7
Condition33%1/3
$hash->{'expire'} || $setup->{'expire'}
l!l&&r!l&&!r
001
MC/DC0%0/2
$hash->{'expire'} || $setup->{'expire'}
$hash->{'expire'} $setup->{'expire'}
Truth table33%1/3
A || B
A= $hash->{'expire'}B= $setup->{'expire'}
ABresult
1X1
011
000
1263 } else {
1264 carp(
1265 (ref $setup->{engine})
1266 1 ."->load_session must return keys(data,[id,expire]) and not "
1267 .join ",", keys %$hash
1268 );
1269 };
1270  
1271 8 return $self->{session};
1272 };
1273  
1274 =head2 save_session( ... )
1275  
1276 =over
1277  
1278 =item * C<$req-E<gt>save_session( [$replace] )>
1279  
1280 =back
1281  
1282 Save whatever is in session data reference.
1283  
1284 If argument is given, replace session (if any) altogether with that one
1285 before saving.
1286  
1287 =cut
1288  
1289 6 ▶sub save_session {
Subroutine save_session: called CC=7 SCAR=20.6
Pod documented
1290 6 my $self = shift;
1291  
1292 6 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 5 1 6
1293 5 $self->{session} = shift;
1294 };
1295  
1296 6 my $setup = $self->_session_setup;
1297 6 ▶ return $self unless $setup;
Branch: 1 branch
BranchTrueFalseTotal
unless $setup 0 6 6
1298  
1299 # TODO 0.90 set "save session" flag, save later
1300 6 my $id = $self->get_cookie( $setup->{cookie}, $setup->{regex} );
1301 6 ▶ $id ||= $setup->{engine}->get_session_id();
Condition66%2/3
$id ||= $setup->{"engine"}->get_session_id
l!l&&r!l&&!r
150
MC/DC0%0/2
$id ||= $setup->{"engine"}->get_session_id
$id $setup->{"engine"}->get_session_id
Truth table66%2/3
A ||= B
A= $idB= $setup->{"engine"}->get_session_id
ABresult
1X1
011
000
1302  
1303 6 my $hash = $setup->{engine}->save_session( $id, $self->session );
1304  
1305 6 ▶ if ( $hash && ref $hash eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hash and ref $hash eq "HASH") 6 0 6
Condition33%1/3
$hash and ref $hash eq "HASH"
!ll&&!rl&&r
006
MC/DC0%0/2
$hash and ref $hash eq "HASH"
$hash ref $hash eq "HASH"
Truth table33%1/3
A and B
A= $hashB= ref $hash eq "HASH"
ABresult
0X0
100
111
1306 # save successful - send cookie to user
1307 6 my $expire = $hash->{expire};
1308  
1309 $self->set_cookie(
1310 $setup->{cookie} => $hash->{id} || $id,
1311 expire => $hash->{expire},
1312 6 ▶ );
Condition33%1/3
$hash->{'id'} || $id
l!l&&r!l&&!r
600
MC/DC0%0/2
$hash->{'id'} || $id
$hash->{'id'} $id
Truth table33%1/3
A || B
A= $hash->{'id'}B= $id
ABresult
1X1
011
000
1313 };
1314  
1315 6 return $self;
1316 };
1317  
1318 =head2 delete_session()
1319  
1320 Remove session.
1321  
1322 =cut
1323  
1324 1 ▶sub delete_session {
Subroutine delete_session: called CC=3 SCAR=11.2
Pod documented
1325 1 my $self = shift;
1326  
1327 1 my $setup = $self->_session_setup;
1328 1 ▶ return unless $setup->{engine};
Branch: 1 branch
BranchTrueFalseTotal
unless $setup->{"engine"} 0 1 1
1329  
1330 1 my $id = $self->get_cookie( $setup->{cookie}, $setup->{regex} );
1331 1 ▶ $setup->{engine}->delete_session( $id )
Branch: 1 branch
BranchTrueFalseTotal
if $id 1 0 1
1332 if $id;
1333 1 $self->delete_cookie( $setup->{cookie} );
1334 1 return $self;
1335 };
1336  
1337 0 ▶_helper_fallback( _session_setup => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1338 0 my $self = shift;
1339 0 $self->_croak("No session engine found, use `neaf session => ...` to set up one");
1340 94 } );
1341  
1342 =head1 REPLY METHODS
1343  
1344 Typically, a Neaf user only needs to return a hashref with the whole reply
1345 to client.
1346  
1347 However, sometimes more fine-grained control is required.
1348  
1349 In this case, a number of methods help stashing your data
1350 (headers, cookies etc) in the request object until the response is sent.
1351  
1352 Also some lengthly actions (e.g. writing request statistics or
1353 sending confirmation e-mail) may be postponed until the request is served.
1354  
1355 =head2 header_out( ... )
1356  
1357 =over
1358  
1359 =item * C<$req-E<gt>header_out( [$header_name] )>
1360  
1361 =back
1362  
1363 Without parameters returns a L<HTTP::Headers::Fast>-compatible object
1364 containing all headers to be returned to client.
1365  
1366 With one parameter returns this header.
1367  
1368 Returned values are just proxied L<HTTP::Headers::Fast> returns.
1369 It is generally advised to use them in list context as multiple
1370 headers may return trash in scalar context.
1371  
1372 E.g.
1373  
1374 my @old_value = $req->header_out( foobar => set => [ "XX", "XY" ] );
1375  
1376 or
1377  
1378 my $old_value = [ $req->header_out( foobar => delete => 1 ) ];
1379  
1380 B<[NOTE]> This format may change in the future.
1381  
1382 =cut
1383  
1384 374 ▶sub header_out {
Subroutine header_out: called CC=3 SCAR=11.0
Pod documented
1385 374 my $self = shift;
1386  
1387 374 ▶ my $head = $self->{response}{header} ||= HTTP::Headers::Fast->new;
Condition66%2/3
$self->{"response"}{"header"} ||= "HTTP::Headers::Fast"->new
l!l&&r!l&&!r
2141600
MC/DC0%0/2
$self->{"response"}{"header"} ||= "HTTP::Headers::Fast"->new
$self->{"response"}{"header"} "HTTP::Headers::Fast"->new
Truth table66%2/3
A ||= B
A= $self->{"response"}{"header"}B= "HTTP::Headers::Fast"->new
ABresult
1X1
011
000
1388 374 ▶ return $head unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 372 2 374
1389  
1390 2 my $name = shift;
1391 2 return $head->header( $name );
1392 };
1393  
1394 =head2 set_header( ... )
1395  
1396 =head2 push_header( ... )
1397  
1398 =head2 remove_header( ... )
1399  
1400 =over
1401  
1402 =item * C<$req-E<gt>set_header( $name, $value || [] )>
1403  
1404 =item * C<$req-E<gt>push_header( $name, $value || [] )>
1405  
1406 =item * C<$req-E<gt>remove_header( $name )>
1407  
1408 =back
1409  
1410 Set, append, and delete values in the header_out object.
1411 See L<HTTP::Headers::Fast>.
1412  
1413 Arrayrefs are fine and will set multiple values for a given header.
1414  
1415 =cut
1416  
1417 2 ▶sub set_header {
Subroutine set_header: called CC=1 SCAR=0.0
Pod documented
1418 2 my ($self, $name, $value) = @_;
1419 2 return $self->header_out->header( $name, $value );
1420 };
1421  
1422 2 ▶sub push_header {
Subroutine push_header: called CC=1 SCAR=0.0
Pod documented
1423 2 my ($self, $name, $value) = @_;
1424 2 return $self->header_out->push_header( $name, $value );
1425 };
1426  
1427 1 ▶sub remove_header {
Subroutine remove_header: called CC=1 SCAR=0.0
Pod documented
1428 1 my ($self, $name) = @_;
1429 1 return $self->header_out->remove_header( $name );
1430 };
1431  
1432 =head2 reply
1433  
1434 Returns reply hashref that was returned by controller, if any.
1435 Returns C<undef> unless the controller was actually called.
1436 This may be useful in postponed actions or hooks.
1437  
1438 This is killed by a C<clear()> call.
1439  
1440 =cut
1441  
1442 378 ▶sub reply {
Subroutine reply: called CC=1 SCAR=0.0
Pod documented
1443 378 my $self = shift;
1444  
1445 378 return $self->{response}{ret};
1446 }
1447  
1448 162 ▶sub _set_reply {
Subroutine _set_reply: called CC=8 SCAR=22.6
1449 162 my ($self, $data) = @_;
1450  
1451 # Cannot croak because it may point at wrong location
1452 # TODO 0.30 More suitable error message, force logging error
1453 162 ▶ die "NEAF: FATAL: Controller must return hash at ".$self->endpoint_origin."\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data and UNIVERSAL::isa($data, "HASH") 1 161 162
Condition66%2/3
ref $data and UNIVERSAL::isa($data, "HASH")
!ll&&!rl&&r
10161
MC/DC50%1/2
ref $data and UNIVERSAL::isa($data, "HASH")
ref $data UNIVERSAL::isa($data, "HASH")
Truth table66%2/3
A and B
A= ref $dataB= UNIVERSAL::isa($data, "HASH")
ABresult
0X0
100
111
1454 unless ref $data and UNIVERSAL::isa($data, 'HASH');
1455 # TODO 0.30 Also accept (&convert) hash headers
1456 die "NEAF: FATAL: '-headers' must be an even-sized array at ".$self->endpoint_origin."\n"
1457 if defined $data->{-headers}
1458 161 ▶ and (ref $data->{-headers} ne 'ARRAY' or @{ $data->{-headers} } % 2);
Branch: 1 branch
BranchTrueFalseTotal
if defined $data->{"-headers"} and ref $data->{"-headers"} ne "ARRAY" || @{$data->{"-headers"};} % 2 0 161 161
Condition50%3/6
defined $data->{"-headers"} and ref $data->{"-headers"} ne "ARRAY" || @{$data->{"-headers"};} % 2
!ll&&!rl&&r
113480
ref $data->{"-headers"} ne "ARRAY" or @{$data->{"-headers"};} % 2
l!l&&r!l&&!r
0048
MC/DC0%0/3
defined $data->{"-headers"} and ref $data->{"-headers"} ne "ARRAY" || @{$data->{"-headers"};} % 2
defined $data->{"-headers"} ref $data->{"-headers"} ne "ARRAY" @{$data->{"-headers"};} % 2
Truth table50%2/4
A and B or C
A= defined $data->{"-headers"}B= ref $data->{"-headers"} ne "ARRAY"C= @{$data->{"-headers"};} % 2
ABCresult
0XX0
1000
11X1
1011
1459 Carp::cluck "NEAF: WARN: Request->_set_reply called twice, please file a bug in Neaf"
1460 161 ▶ if $self->{response}{ret};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"response"}{"ret"} 0 161 161
1461  
1462 161 ▶ my $def = $self->route->default || {};
Condition50%1/2
$self->route->default || {}
l!l
1610
MC/DC0%0/1
$self->route->default || {}
$self->route->default
Truth table50%1/2
A
A= $self->route->default
Aresult
11
00
1463  
1464 # Return the resulting hash
1465 161 $self->{response}{ret} = { %$def, %$data };
1466 }
1467  
1468 # TODO 0.4 should we delete {response} altogether?
1469 48 ▶sub _unset_reply {
Subroutine _unset_reply: called CC=1 SCAR=0.0
1470 48 my $self = shift;
1471 48 delete $self->{response}{ret};
1472 };
1473  
1474 =head2 stash( ... )
1475  
1476 Stash (ah, the naming...) is a temporary set of data that only lives
1477 throughtout request's lifetime and never gets to the client.
1478  
1479 This may be useful to maintain shared data across hooks and callbacks.
1480 Usage is as follows:
1481  
1482 =over
1483  
1484 =item * C<$req-E<gt>stash()> - get the whole stash as hash.
1485  
1486 =item * C<$req-E<gt>stash( "name" )> - get a single value
1487  
1488 =item * C<$req-E<gt>stash( %save_data )> - set multiple values, old data
1489 is overridden rather than replaced.
1490  
1491 =back
1492  
1493 As a rule of thumb,
1494  
1495 =over
1496  
1497 =item * use C<session> if you intend to share data between requests;
1498  
1499 =item * use C<reply> if you intend to render the data for the user;
1500  
1501 =item * use C<stash> as a last resort for temporary, private data.
1502  
1503 =back
1504  
1505 Stash is not killed by C<clear()> function so that cleanup hooks aren't
1506 botched accidentally.
1507  
1508 =cut
1509  
1510 3 ▶sub stash {
Subroutine stash: called CC=6 SCAR=18.0
Pod documented
1511 3 my $self = shift;
1512 3 ▶ my $st = $self->{stash} ||= {};
Condition100%2/2
$self->{"stash"} ||= {}
l!l
21
MC/DC100%1/1
$self->{"stash"} ||= {}
$self->{"stash"}
Truth table100%2/2
A
A= $self->{"stash"}
Aresult
11
00
1513 3 ▶ return $st unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 1 2 3
1514  
1515 2 ▶ return $st->{ $_[0] } unless @_>1;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ > 1 0 2 2
1516  
1517 2 ▶ $self->_croak("Odd number of elements in hash assignment") if @_ % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 0 2 2
1518 2 my %new = @_;
1519 2 $st->{$_} = $new{$_} for keys %new;
1520 2 return $self;
1521 };
1522  
1523 =head2 postpone( ... )
1524  
1525 =over
1526  
1527 =item * C<$req-E<gt>postpone( CODEREF-E<gt>($request) )>
1528  
1529 =item * C<$req-E<gt>postpone( [ CODEREF-E<gt>($request), ... ] )>
1530  
1531 =back
1532  
1533 Execute a function (or several) right after the request is served.
1534  
1535 Can be called multiple times.
1536  
1537 B<[CAVEAT]> If CODEREF contains reference to the request,
1538 the request will never be destroyed due to circular reference.
1539 Thus CODEREF may not be executed.
1540  
1541 Don't pass request to CODEREF, use C<my $req = shift> instead.
1542  
1543 Returns self.
1544  
1545 =cut
1546  
1547 8 ▶sub postpone {
Subroutine postpone: called CC=4 SCAR=13.9
Pod documented
1548 8 my ($self, $code, $prepend_flag) = @_;
1549  
1550 8 ▶ $code = [ $code ]
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "ARRAY" 5 3 8
1551 unless ref $code eq 'ARRAY';
1552 8 ▶ grep { ref $_ ne 'CODE' } @$code
Branch: 1 branch
BranchTrueFalseTotal
grep {ref $_ ne "CODE";} @$code and $self->_croak("argument must be a function or a list of functions") 0 8 8
1553 and $self->_croak( "argument must be a function or a list of functions" );
1554  
1555 $prepend_flag
1556 4 ? unshift @{ $self->{response}{postponed} }, reverse @$code
1557 8 ▶ : push @{ $self->{response}{postponed} }, @$code;
Branch: 1 branch
BranchTrueFalseTotal
$prepend_flag ? : 4 4 8
1558  
1559 8 return $self;
1560 };
1561  
1562 =head2 write( ... )
1563  
1564 =over
1565  
1566 =item * C<$req-E<gt>write( $data )>
1567  
1568 =back
1569  
1570 Write data to client inside C<-continue> callback, unless C<close> was called.
1571  
1572 Returns self.
1573  
1574 =cut
1575  
1576 46 ▶sub write {
Subroutine write: called CC=3 SCAR=11.4
Pod documented
1577 46 my ($self, $data) = @_;
1578  
1579 $self->{continue}
1580 46 ▶ or $self->_croak( "called outside -continue callback scope" );
Branch: 1 branch
BranchTrueFalseTotal
$self->{"continue"} or $self->_croak("called outside -continue callback scope") 46 0 46
1581  
1582 46 ▶ $self->do_write( $data )
Branch: 1 branch
BranchTrueFalseTotal
if defined $data 46 0 46
1583 if defined $data;
1584 46 return $self;
1585 };
1586  
1587 =head2 close()
1588  
1589 Stop writing to client in C<-continue> callback.
1590  
1591 By default, does nothing, as the socket will probably
1592 be closed anyway when the request finishes.
1593  
1594 =cut
1595  
1596 3 ▶sub close {
Subroutine close: called CC=2 SCAR=7.1
Pod documented
1597 3 my ($self) = @_;
1598  
1599 $self->{continue}
1600 3 ▶ or $self->_croak( "called outside -continue callback scope" );
Branch: 1 branch
BranchTrueFalseTotal
$self->{"continue"} or $self->_croak("called outside -continue callback scope") 3 0 3
1601  
1602 3 return $self->do_close();
1603 }
1604  
1605 =head2 clear()
1606  
1607 Remove all data that belongs to reply.
1608 This is called when a handler bails out to avoid e.g. setting cookies
1609 in a failed request.
1610  
1611 =cut
1612  
1613 1 ▶sub clear {
Subroutine clear: called CC=2 SCAR=7.0
Pod documented
1614 1 my $self = shift;
1615  
1616 $self->_croak( "called after responding" )
1617 1 ▶ if $self->{continue};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"continue"} 0 1 1
1618  
1619 1 delete $self->{response};
1620 1 return $self;
1621 }
1622  
1623 =head1 DEVELOPER METHODS
1624  
1625 =head2 id()
1626  
1627 Fetch unique request id. If none has been set yet (see L</set_id>),
1628 use L</make_id> method to create one.
1629  
1630 The request id is present in both log messages from Neaf
1631 and default error pages, making it easier to establish link
1632 between the two.
1633  
1634 Custom ids can be provided, see L</make_id> below.
1635  
1636 =cut
1637  
1638 71 ▶sub id {
Subroutine id: called CC=2 SCAR=7.1
Pod documented
1639 71 my $self = shift;
1640  
1641 # We don't really need to protect anything here
1642 # Just avoid accidental matches for which md5 seems good enough
1643 71 ▶ return $self->{id} ||= $self->make_id;
Condition66%2/3
$self->{"id"} ||= $self->make_id
l!l&&r!l&&!r
26450
MC/DC0%0/2
$self->{"id"} ||= $self->make_id
$self->{"id"} $self->make_id
Truth table66%2/3
A ||= B
A= $self->{"id"}B= $self->make_id
ABresult
1X1
011
000
1644 };
1645  
1646 =head2 set_id( ... )
1647  
1648 =over
1649  
1650 =item * C<$req-E<gt>set_id( $new_value )>
1651  
1652 =back
1653  
1654 Set the id above to a user-supplied value.
1655  
1656 If a false value given, just generate a new one next time id is requested.
1657  
1658 Symbols outside C<ascii>, as well as whitespace and C<"> and C"\",
1659 are prohibited.
1660  
1661 Returns the request object.
1662  
1663 =cut
1664  
1665 1 ▶sub set_id {
Subroutine set_id: called CC=4 SCAR=16.4
Pod documented
1666 1 my ($self, $id) = @_;
1667  
1668 1 ▶ !$id or $id =~ /^[\x21-\x7E]+$/ && $id !~ /[\s\"\\]/
Branch: 1 branch
BranchTrueFalseTotal
not $id or $id =~ /^[\x21-\x7E]+$/ and not $id =~ /[\s\"\\]/ or $self->_croak("Bad id format, should only contain printable") 1 0 1
Condition33%2/6
not $id or $id =~ /^[\x21-\x7E]+$/ and not $id =~ /[\s\"\\]/
l!l&&r!l&&!r
010
$id =~ /^[\x21-\x7E]+$/ and not $id =~ /[\s\"\\]/
!ll&&!rl&&r
001
MC/DC0%0/3
not $id or $id =~ /^[\x21-\x7E]+$/ and not $id =~ /[\s\"\\]/
not $id $id =~ /^[\x21-\x7E]+$/ not $id =~ /[\s\"\\]/
Truth table25%1/4
not(A) or B and not(C)
A= not $idB= $id =~ /^[\x21-\x7E]+$/C= not $id =~ /[\s\"\\]/
ABCresult
1XX1
0111
00X0
0100
1669 or $self->_croak( "Bad id format, should only contain printable" );
1670  
1671 1 $self->{id} = $id;
1672 1 return $self;
1673 };
1674  
1675 =head2 log_error( ... )
1676  
1677 =over
1678  
1679 =item * C<$req-E<gt>log_error( $message )>
1680  
1681 =back
1682  
1683 Log an error message, annotated with request id and the route being processed.
1684  
1685 Currently works via warn, but this may change in the future.
1686  
1687 B<[EXPERIMENTAL]> This feature is still under development.
1688  
1689 One can count on C<log_error> to be available in the future and do
1690 some king of logging.
1691  
1692 =cut
1693  
1694 20 ▶sub log_error {
Subroutine log_error: called CC=1 SCAR=0.0
Pod documented
1695 20 my ($self, $msg) = @_;
1696 20 $self->log_message( error => $msg );
1697 };
1698  
1699 =head2 execute_postponed()
1700  
1701 NOT TO BE CALLED BY USER.
1702  
1703 Execute postponed functions. This is called in DESTROY by default,
1704 but request driver may decide it knows better.
1705  
1706 Flushes postponed queue. Ignores exceptions in functions being executed.
1707  
1708 Returns self.
1709  
1710 =cut
1711  
1712 6 ▶sub execute_postponed {
Subroutine execute_postponed: called CC=1 SCAR=0.1
Pod documented
1713 6 my $self = shift;
1714  
1715 6 $self->{continue}++;
1716 0 ▶ run_all_nodie( delete $self->{response}{postponed}, sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1717 # TODO 0.30 prettier error handling
1718 0 carp "NEAF WARN ".(ref $self).": postponed action failed: $@";
1719 6 }, $self );
1720  
1721 6 return $self;
1722 };
1723  
1724  
1725 157 ▶sub _mangle_headers {
Subroutine _mangle_headers: called CC=15 SCAR=27.1
1726 157 my $self = shift;
1727  
1728 157 my $data = $self->reply;
1729 157 my $content = \$data->{-content};
1730  
1731 157 ▶ confess "NEAF: No content after request processing. File a bug in MVC::Neaf"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$content 0 157 157
1732 unless defined $$content;
1733  
1734 # Process user-supplied headers
1735 157 ▶ if (my $append = $data->{-headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $append = $data->{"-headers"}) 48 109 157
1736 48 my $head = $self->header_out;
1737 48 ▶ for (my $i = 0; $i < @$append; $i+=2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$append) 11 48 59
1738 11 $head->push_header($append->[$i], $append->[$i+1]);
1739 };
1740 };
1741  
1742 # TODO 0.30 do something with this regex mess - its complicated & dog slow
1743 # Encode unicode content NOW so that we don't lie about its length
1744 # Then detect ascii/binary
1745 157 ▶ if (Encode::is_utf8( $$content )) {
Branch: 3 branches
BranchTrueFalseTotal
if (&Encode::is_utf8($$content)) { } 48 109 157
elsif (not $data->{'-type'}) { } 50 59 109
elsif ($data->{'-type'} =~ m[^text/]) { } 54 5 59
1746 # UTF8 means text, period
1747 48 $$content = encode_utf8( $$content );
1748 48 ▶ $data->{-type} ||= 'text/plain';
Condition100%2/2
$data->{"-type"} ||= "text/plain"
l!l
426
MC/DC100%1/1
$data->{"-type"} ||= "text/plain"
$data->{"-type"}
Truth table100%2/2
A
A= $data->{"-type"}
Aresult
11
00
1749 $data->{-type} .= "; charset=utf-8"
1750 48 ▶ unless $data->{-type} =~ /; charset=/;
Branch: 1 branch
BranchTrueFalseTotal
unless $data->{"-type"} =~ /; charset=/ 10 38 48
1751 } elsif (!$data->{-type}) {
1752 # Autodetect binary. Plain text is believed to be in utf8 still
1753 50 ▶ $data->{-type} = $$content =~ /^.{0,512}?[^\s\x20-\x7F]/s
Branch: 1 branch
BranchTrueFalseTotal
$$content =~ /^.{0,512}?[^\s\x20-\x7F]/s ? : 1 49 50
1754 ? 'application/octet-stream'
1755 : 'text/plain; charset=utf-8';
1756 } elsif ($data->{-type} =~ m#^text/#) {
1757 # Some other text, mark as utf-8 just in case
1758 $data->{-type} .= "; charset=utf-8"
1759 54 ▶ unless $data->{-type} =~ /; charset=/;
Branch: 1 branch
BranchTrueFalseTotal
unless $data->{"-type"} =~ /; charset=/ 14 40 54
1760 };
1761  
1762 # MANGLE HEADERS
1763 157 my $head = $self->header_out;
1764  
1765 # The most standard ones...
1766 157 $head->init_header( content_type => $data->{-type} );
1767 $head->init_header( location => $data->{-location} )
1768 157 ▶ if $data->{-location};
Branch: 1 branch
BranchTrueFalseTotal
if $data->{"-location"} 0 157 157
1769 157 $head->push_header( set_cookie => $self->format_cookies );
1770 $head->init_header( content_length => length $$content )
1771 157 ▶ unless $data->{-continue};
Branch: 1 branch
BranchTrueFalseTotal
unless $data->{"-continue"} 155 2 157
1772  
1773 # TODO 0.30 must be hook
1774 157 ▶ if ($data->{-status} == 200 and my $ttl = $self->route->cache_ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{"-status"} == 200 and my $ttl = $self->route->cache_ttl) 3 154 157
Condition100%3/3
$data->{"-status"} == 200 and my $ttl = $self->route->cache_ttl
!ll&&!rl&&r
481063
MC/DC100%2/2
$data->{"-status"} == 200 and my $ttl = $self->route->cache_ttl
$data->{"-status"} == 200 my $ttl = $self->route->cache_ttl
Truth table100%3/3
A and B
A= $data->{"-status"} == 200B= my $ttl = $self->route->cache_ttl
ABresult
0X0
100
111
1775 3 $head->init_header( expires => http_date( time + $ttl ) );
1776 };
1777  
1778 # END MANGLE HEADERS
1779 };
1780  
1781 # Apply route's pre_reply & pre_cleanup hooks to self, if any
1782 157 ▶sub _apply_late_hooks {
Subroutine _apply_late_hooks: called CC=3 SCAR=11.0
1783 157 my $self = shift;
1784  
1785 157 my $route = $self->route;
1786 157 ▶ if (my $hooks = $route->hooks->{pre_cleanup}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hooks = $route->hooks->{"pre_cleanup"}) 3 154 157
1787 3 $self->postpone( $hooks );
1788 };
1789 157 ▶ if (my $hooks = $route->hooks->{pre_reply}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hooks = $route->hooks->{"pre_reply"}) 5 152 157
1790 1 ▶ run_all_nodie( $hooks, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1791 1 $self->log_error( "NEAF: pre_reply hook failed: $@" )
1792 5 }, $self );
1793 };
1794 };
1795  
1796 # Dispatch headers & content
1797 # This is called at the end of handle_request
1798 157 ▶sub _respond {
Subroutine _respond: called CC=3 SCAR=11.0
1799 157 my $self = shift;
1800  
1801 # TODO 0.30 kill do_reply, simplify this
1802 157 my $data = $self->reply;
1803  
1804 157 ▶ if( $self->method eq 'HEAD' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->method eq 'HEAD') { } 1 156 157
elsif ($data->{'-continue'}) { } 2 154 156
1805 1 return $self->do_reply( $data->{-status}, '' );
1806 } elsif ( $data->{-continue} ) {
1807 2 $self->postpone( $data->{-continue}, 1 );
1808 2 ▶ $self->postpone( sub { $_[0]->write( $data->{-content} ); }, 1 );
Subroutine __ANON__: called CC=1 SCAR=0.0
1809 2 return $self->do_reply( $data->{-status} );
1810 } else {
1811 154 return $self->do_reply( $data->{-status}, $data->{-content} );
1812 };
1813 };
1814  
1815 167 ▶sub DESTROY {
Subroutine DESTROY: called CC=2 SCAR=6.9
1816 167 my $self = shift;
1817  
1818 # TODO 0.90 Check that request isn't destroyed because of an exception
1819 # during sending headers
1820 # In this case we're gonna fail silently with cryptic warnings. :(
1821 $self->execute_postponed
1822 167 ▶ if (exists $self->{response}{postponed});
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->{"response"}{"postponed"} 1 166 167
1823 };
1824  
1825 =head1 METHODS THAT CAN BE OVERRIDDEN
1826  
1827 Generally Neaf allows to define custom Request methods restricted to certain
1828 path & method combinations.
1829  
1830 The following methods are available by default, but can be overridden
1831 via the helper mechanism.
1832  
1833 For instance,
1834  
1835 use MVC::Neaf;
1836  
1837 my $id;
1838 neaf helper => make_id => sub { $$ . "_" . ++$id };
1839 neaf helper => make_id => \&unique_secure_base64, path => '/admin';
1840  
1841 =cut
1842  
1843 470 ▶sub _helper_fallback {
Subroutine _helper_fallback: called CC=1 SCAR=0.0
1844 470 my ($name, $impl) = @_;
1845  
1846 95 ▶ my $code = sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
1847 95 my $self = shift;
1848 95 ▶ my $todo = $self->route && $self->route->helpers->{$name} || $impl;
Condition66%4/6
$self->route && $self->route->helpers->{$name} || $impl
l!l&&r!l&&!r
26690
$self->route and $self->route->helpers->{$name}
!ll&&!rl&&r
06926
MC/DC0%0/3
$self->route && $self->route->helpers->{$name} || $impl
$self->route $self->route->helpers->{$name} $impl
Truth table40%2/5
A and B || C
A= $self->routeB= $self->route->helpers->{$name}C= $impl
ABCresult
11X1
0X11
1011
0X00
1000
1849 95 $todo->( $self, @_ );
1850 470 };
1851  
1852 470 $allow_helper{$name}++;
1853  
1854 94 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
1855 94 ▶ use warnings FATAL => qw(all);
Subroutine BEGIN: called CC=1 SCAR=0.0
1856 470 *$name = $code;
1857 };
1858  
1859 =head2 make_id
1860  
1861 Create unique request id, e.g. for logging context.
1862 This is called by L</id> if the id has not yet been set.
1863  
1864 By default, generates MD5 checksum based on time, hostname, process id, and a
1865 sequential number and encodes as URL-friendly base64.
1866  
1867 B<[CAUTION]> This should be unique, but may not be secure.
1868 Use L<MVC::Neaf::X::Session> if you need something to rely upon.
1869  
1870 =cut
1871  
1872 94 my $host = Sys::Hostname::hostname();
1873 94 my $lastid = 0;
1874 43 ▶_helper_fallback( make_id => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
1875 43 ▶ $lastid = 0 if $lastid > 4_000_000_000;
Branch: 1 branch
BranchTrueFalseTotal
if $lastid > 4000000000 0 43 43
1876 43 encode_b64( md5( join "#", $host, $$, Time::HiRes::time, ++$lastid ) );
1877 94 } );
1878  
1879 =head2 log_message
1880  
1881 $req->log_message( $level => $message );
1882  
1883 By default would print uppercased level, $request->id, route,
1884 and the message itself.
1885  
1886 Levels are not restricted whatsoever.
1887 Suggested values are "fatal", "error", "warn", "debug".
1888  
1889 =cut
1890  
1891 21 ▶_helper_fallback( log_message => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1892 21 my ($req, $level, $mess) = @_;
1893  
1894 21 ▶ $mess = Carp::shortmess("(undef)")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $mess 2 19 21
1895 unless defined $mess;
1896 21 $mess =~ s/\n+$//s;
1897  
1898 21 warn sprintf "%s req_id=%s [%s]: %s\n"
1899 , uc $level, $req->id, $req->route->path, $mess;
1900 94 });
1901  
1902 =head1 DRIVER METHODS
1903  
1904 The following methods MUST be implemented in every Request subclass
1905 to create a working Neaf backend.
1906  
1907 They SHOULD NOT be called directly inside the application.
1908  
1909 =over
1910  
1911 =item * do_get_client_ip()
1912  
1913 =item * do_get_http_version()
1914  
1915 =item * do_get_method()
1916  
1917 =item * do_get_scheme()
1918  
1919 =item * do_get_hostname()
1920  
1921 =item * do_get_port()
1922  
1923 =item * do_get_path()
1924  
1925 =item * do_get_params()
1926  
1927 =item * do_get_param_as_array() - get single GET/POST parameter in list context
1928  
1929 =item * do_get_upload()
1930  
1931 =item * do_get_body()
1932  
1933 =item * do_get_header_in() - returns a L<HTTP::Headers>-compatible object.
1934  
1935 =item * do_reply( $status, $content ) - write reply to client
1936  
1937 =item * do_reply( $status ) - only send headers to client
1938  
1939 =item * do_write( $data )
1940  
1941 =item * do_close()
1942  
1943 =back
1944  
1945 =cut
1946  
1947 94 foreach (qw(
1948 do_get_method do_get_scheme do_get_hostname do_get_port do_get_path
1949 do_get_client_ip do_get_http_version
1950 do_get_params do_get_param_as_array do_get_upload do_get_header_in
1951 do_get_body
1952 do_reply do_write)) {
1953 1316 my $method = $_;
1954 6 ▶ my $code = sub {
Subroutine __ANON__: called CC=2 SCAR=8.1
1955 6 my $self = shift;
1956 6 ▶ croak ((ref $self || $self)."->$method() unimplemented!");
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
600
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
1957 1316 };
1958 94 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
1959 1316 *$method = $code;
1960 };
1961  
1962 # by default, just skip - the handle will auto-close anyway at some point
1963 1 ▶sub do_close { return 1 };
Subroutine do_close: called CC=1 SCAR=0.0
Pod documented
1964  
1965 6 ▶sub _croak {
Subroutine _croak: called CC=2 SCAR=7.4
1966 6 my ($self, $msg) = @_;
1967  
1968 6 my $where = [caller(1)]->[3];
1969 6 $where =~ s/.*:://;
1970 6 ▶ croak( (ref $self || $self)."->$where: $msg" );
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
600
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
1971 };
1972  
1973 =head1 DEPRECATED METHODS
1974  
1975 Some methods become obsolete during Neaf development.
1976 Anything that is considered deprecated will continue to be supported
1977 I<for at least three minor versions> after official deprecation
1978 and a corresponding warning being added.
1979  
1980 Please keep an eye on C<Changes> though.
1981  
1982 Here are these methods, for the sake of completeness.
1983  
1984 =cut
1985  
1986 =head2 script_name
1987  
1988 See L</prefix>
1989  
1990 =head2 path_info
1991  
1992 See L</postfix>.
1993  
1994 =head2 path_info_split
1995  
1996 See L</prefix>
1997  
1998 These three will start warning in 0.30 and will be removed in 0.40
1999  
2000 =cut
2001  
2002 # TODO 0.30 start warning "deprecated"
2003 {
2004 94 ▶ no warnings 'once'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
2005 94 ▶ use warnings FATAL => 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
2006 94 *script_name = \&prefix;
2007 94 *path_info = \&postfix;
2008 94 *path_info_split = \&splat;
2009 }
2010  
2011 =head2 header_in_keys ()
2012  
2013 Return all keys in header_in object as a list.
2014  
2015 B<[DEPRECATED]> Use C<$req-E<gt>header_in-E<gt>header_field_names> instead.
2016  
2017 =cut
2018  
2019 1 ▶sub header_in_keys {
Subroutine header_in_keys: called CC=1 SCAR=0.0
Pod documented
2020 1 my $self = shift;
2021  
2022 1 carp( (ref $self)."->header_in_keys: DEPRECATED, use header_in()->header_field_names instead" );
2023 1 my $head = $self->header_in;
2024 1 $head->header_field_names;
2025 };
2026  
2027 =head2 endpoint_origin
2028  
2029 Returns file:line where controller was defined.
2030  
2031 B<[DEPRECATED]> This function was added prematurely and shall not be used.
2032  
2033 =cut
2034  
2035 4 ▶sub endpoint_origin {
Subroutine endpoint_origin: called CC=2 SCAR=7.0
Pod documented
2036 4 my $self = shift;
2037  
2038 4 ▶ return '(unspecified file):0' unless $self->{route}{caller};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"route"}{"caller"} 0 4 4
2039 4 return join " line ", @{ $self->{route}{caller} }[1,2];
2040 };
2041  
2042 =head2 get_form_as_hash( ... )
2043  
2044 =over
2045  
2046 =item * C<$req-E<gt>get_form_as_hash( name =E<gt> qr/.../, name2 =E<gt> qr/..../, ... )>
2047  
2048 =back
2049  
2050 B<[DEPRECATED]> and dies. Use L<MVC::Neaf::X::Form> instead.
2051  
2052 =cut
2053  
2054 1 ▶sub get_form_as_hash {
Subroutine get_form_as_hash: called CC=1 SCAR=0.0
Pod documented
2055 1 my ($self, %spec) = @_;
2056  
2057 1 $self->_croak( "DEPRECATED. use neaf->add_form( name, ...) + \$req->form( name )" );
2058 };
2059  
2060 =head2 set_default( ... )
2061  
2062 =over
2063  
2064 =item * C<$req-E<gt>set_default( key =E<gt> $value, ... )>
2065  
2066 =back
2067  
2068 As of v.0.20 this dies.
2069  
2070 Use path-based defaults, or stash().
2071  
2072 =cut
2073  
2074 1 ▶sub set_default {
Subroutine set_default: called CC=1 SCAR=0.0
Pod documented
2075 1 my ($self, %args) = @_;
2076  
2077 # TODO 0.30 remove completely
2078 1 $self->_croak( "DEPRECATED. Use path-based defaults or stash()" );
2079 };
2080  
2081 =head2 get_default()
2082  
2083 As of v.0.20 this dies.
2084  
2085 Use path-based defaults, or stash().
2086  
2087 =cut
2088  
2089 1 ▶sub get_default {
Subroutine get_default: called CC=1 SCAR=0.0
Pod documented
2090 1 my $self = shift;
2091  
2092 # TODO 0.30 remove completely
2093 1 $self->_croak( "DEPRECATED. Use path-based defaults or stash()" );
2094 };
2095  
2096 =head1 LICENSE AND COPYRIGHT
2097  
2098 This module is part of L<MVC::Neaf> suite.
2099  
2100 Copyright 2016-2023 Konstantin S. Uvarin C<khedin@cpan.org>.
2101  
2102 This program is free software; you can redistribute it and/or modify it
2103 under the terms of either: the GNU General Public License as published
2104 by the Free Software Foundation; or the Artistic License.
2105  
2106 See L<http://dev.perl.org/licenses/> for more information.
2107  
2108 =cut
2109  
2110 94 1;
« Neaf.pm ↑ Summary Neaf/Upload.pm »