blib/lib/Web/Simple/Application.pm

filter: Statementstmt 71.7% 66 / 92 Branchbran 63.3% 19 / 30 Conditioncond 58.3% 14 / 24 MC/DCmcdc 33.3% 4 / 12 Subroutinesub 75.0% 15 / 20 Podpod 100% 5 / 5 totaltotal 67.2% 123 / 183 CC 24 SCAR 21.5
CC
24
Cov
68%
_run_cli_test_request
20.0
run
16.7
_test_request_spec_to_http_request
9.0
CRAP 8.6
« blib/lib/Web/Dispatch/Parser.pm ↑ Summary blib/lib/Web/Dispatch/ParamParser.pm »
1 package Web::Simple::Application;
2  
3 16 ▶use Scalar::Util 'weaken';
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 16 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 has 'config' => (
8 is => 'ro',
9 16 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
10 16 my ($self) = @_;
11 16 +{ $self->default_config }
12 },
13 0 ▶ trigger => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
14 0 my ($self, $value) = @_;
15 0 my %default = $self->default_config;
16 0 my @not = grep !exists $value->{$_}, keys %default;
17 0 @{$value}{@not} = @default{@not};
18 }
19 16 );
20  
21 15 ▶sub default_config { () }
Subroutine default_config: called CC=1 SCAR=0.0
Pod documented
22  
23 16 has '_dispatcher' => (is => 'lazy');
24  
25 15 ▶sub _build__dispatcher {
Subroutine _build__dispatcher: called CC=1 SCAR=0.0
26 15 my $self = shift;
27 15 require Web::Dispatch;
28 15 my $final = $self->_build_final_dispatcher;
29  
30 # We need to weaken both the copy of $self that the
31 # app parameter will close over and the copy that'll
32 # be passed through as a node argument.
33 #
34 # To ensure that this doesn't then result in us being
35 # DESTROYed unexpectedly early, our to_psgi_app method
36 # closes back over $self
37  
38 15 weaken($self);
39 my %dispatch_args = (
40 65 ▶ dispatch_app => sub { $self->dispatch_request(@_), $final },
Subroutine __ANON__: called CC=1 SCAR=0.0
41 15 dispatch_object => $self
42 );
43 15 weaken($dispatch_args{dispatch_object});
44 15 Web::Dispatch->new(%dispatch_args);
45 }
46  
47 15 ▶sub _build_final_dispatcher {
Subroutine _build_final_dispatcher: called CC=1 SCAR=0.0
48 15 [ 404, [ 'Content-type', 'text/plain' ], [ 'Not found' ] ]
49 }
50  
51 1 ▶sub run_if_script {
Subroutine run_if_script: called CC=3 SCAR=18.4
Pod documented
52 # ->to_psgi_app is true for require() but also works for plackup
53 1 ▶ return $_[0]->to_psgi_app if caller(1);
Branch: 1 branch
BranchTrueFalseTotal
if caller 1 1 0 1
54 0 ▶ my $self = ref($_[0]) ? $_[0] : $_[0]->new;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 0 0
55 0 $self->run(@_);
56 }
57  
58 2 ▶sub _run_cgi {
Subroutine _run_cgi: called CC=1 SCAR=0.0
59 2 my $self = shift;
60 2 require Plack::Handler::CGI;
61 2 Plack::Handler::CGI->new->run($self->to_psgi_app);
62 }
63  
64 0 ▶sub _run_fcgi {
Subroutine _run_fcgi: not called CC=1 SCAR=6.9
65 0 my $self = shift;
66 0 require Plack::Handler::FCGI;
67 0 Plack::Handler::FCGI->new->run($self->to_psgi_app);
68 }
69  
70 66 ▶sub to_psgi_app {
Subroutine to_psgi_app: called CC=2 SCAR=6.9
Pod documented
71 66 ▶ my $self = ref($_[0]) ? $_[0] : $_[0]->new;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 65 1 66
72 66 my $app = $self->_dispatcher->to_app;
73  
74 # Close over $self to keep $self alive even though
75 # we weakened the copies the dispatcher has; the
76 # if 0 causes the ops to be optimised away to
77 # minimise the performance impact and avoid void
78 # context warnings while still doing the closing
79 # over part. As Mithaldu said: "Gnarly." ...
80  
81 66 ▶ return sub { $self if 0; goto &$app; };
Subroutine __ANON__: called CC=1 SCAR=0.0
82 }
83  
84 5 ▶sub run {
Subroutine run: called CC=10 SCAR=28.2
Pod documented
85 5 my $self = shift;
86 5 ▶ if (
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'PHP_FCGI_CHILDREN'} or $ENV{'FCGI_ROLE'} or $ENV{'FCGI_SOCKET_PATH'} or -S STDIN and not $ENV{'GATEWAY_INTERFACE'}) { } 1 4 5
elsif ($ENV{'GATEWAY_INTERFACE'}) { } 3 1 4
Condition58%7/12
$ENV{"PHP_FCGI_CHILDREN"} or $ENV{"FCGI_ROLE"} or $ENV{"FCGI_SOCKET_PATH"} or -S STDIN and not $ENV{"GATEWAY_INTERFACE"}
l!l&&r!l&&!r
014
$ENV{"PHP_FCGI_CHILDREN"} or $ENV{"FCGI_ROLE"} or $ENV{"FCGI_SOCKET_PATH"}
l!l&&r!l&&!r
005
$ENV{"PHP_FCGI_CHILDREN"} or $ENV{"FCGI_ROLE"}
l!l&&r!l&&!r
005
-S STDIN and not $ENV{"GATEWAY_INTERFACE"}
!ll&&!rl&&r
311
MC/DC40%2/5
$ENV{"PHP_FCGI_CHILDREN"} or $ENV{"FCGI_ROLE"} or $ENV{"FCGI_SOCKET_PATH"} or -S STDIN and not $ENV{"GATEWAY_INTERFACE"}
$ENV{"PHP_FCGI_CHILDREN"} $ENV{"FCGI_ROLE"} $ENV{"FCGI_SOCKET_PATH"} -S STDIN not $ENV{"GATEWAY_INTERFACE"}
Truth table50%3/6
A or B or C or D and not(E)
A= $ENV{"PHP_FCGI_CHILDREN"}B= $ENV{"FCGI_ROLE"}C= $ENV{"FCGI_SOCKET_PATH"}D= -S STDINE= not $ENV{"GATEWAY_INTERFACE"}
ABCDEresult
1XXXX1
01XXX1
001XX1
000111
0000X0
000100
87 $ENV{PHP_FCGI_CHILDREN} || $ENV{FCGI_ROLE} || $ENV{FCGI_SOCKET_PATH}
88 || ( -S STDIN && !$ENV{GATEWAY_INTERFACE} )
89 # If STDIN is a socket, almost certainly FastCGI, except for mod_cgid
90 ) {
91 1 return $self->_run_fcgi;
92 } elsif ($ENV{GATEWAY_INTERFACE}) {
93 3 return $self->_run_cgi;
94 }
95 1 ▶ unless (@ARGV && $ARGV[0] =~ m{(^[A-Z/])|\@}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@ARGV and $ARGV[0] =~ m[(^[A-Z/])|\@]) 1 0 1
Condition33%1/3
@ARGV and $ARGV[0] =~ m[(^[A-Z/])|\@]
!ll&&!rl&&r
100
MC/DC0%0/2
@ARGV and $ARGV[0] =~ m[(^[A-Z/])|\@]
@ARGV $ARGV[0] =~ m[(^[A-Z/])|\@]
Truth table33%1/3
A and B
A= @ARGVB= $ARGV[0] =~ m[(^[A-Z/])|\@]
ABresult
0X0
100
111
96 1 return $self->_run_cli(@ARGV);
97 }
98  
99 0 my @args = @ARGV;
100  
101 0 ▶ unshift(@args, 'GET') if $args[0] !~ /^[A-Z]/;
Branch: 1 branch
BranchTrueFalseTotal
unless $args[0] =~ /^[A-Z]/ 0 0 0
102  
103 0 $self->_run_cli_test_request(@args);
104 }
105  
106 60 ▶sub _test_request_spec_to_http_request {
Subroutine _test_request_spec_to_http_request: called CC=9 SCAR=22.0
107 60 my ($self, $method, $path, @rest) = @_;
108  
109 # if it's a reference, assume a request object
110 60 ▶ return $method if ref($method);
Branch: 1 branch
BranchTrueFalseTotal
if ref $method 13 47 60
111  
112 47 ▶ if ($path =~ s/^(.*?)\@//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ s/^(.*?)\@//) 2 45 47
113 2 my $basic = $1;
114 2 require MIME::Base64;
115 2 unshift @rest, 'Authorization:', 'Basic '.MIME::Base64::encode($basic);
116 }
117  
118 47 my $request = HTTP::Request->new($method => $path);
119  
120 47 my @params;
121  
122 47 ▶ while (my ($header, $value) = splice(@rest, 0, 2)) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@rest, 0, 2)) 4 47 51
123 4 ▶ unless ($header =~ s/:$//) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($header =~ s/:$//) 2 2 4
124 2 push @params, $header, $value;
125 }
126 4 $header =~ s/_/-/g;
127 4 ▶ if ($header eq 'Content') {
Branch: 1 branch
BranchTrueFalseTotal
if ($header eq 'Content') { } 0 4 4
128 0 $request->content($value);
129 } else {
130 4 $request->headers->push_header($header, $value);
131 }
132 }
133  
134 47 ▶ if (($method eq 'POST' or $method eq 'PUT') and @params) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "POST" || $method eq "PUT" and @params) 2 45 47
Condition100%6/6
$method eq "POST" || $method eq "PUT" and @params
!ll&&!rl&&r
4142
$method eq "POST" or $method eq "PUT"
l!l&&r!l&&!r
3341
MC/DC66%2/3
$method eq "POST" || $method eq "PUT" and @params
$method eq "POST" $method eq "PUT" @params
Truth table80%4/5
A or B and C
A= $method eq "POST"B= $method eq "PUT"C= @params
ABCresult
00X0
1X00
0100
1X11
0111
135 2 my $content = do {
136 2 require URI;
137 2 my $url = URI->new('http:');
138 2 $url->query_form(@params);
139 2 $url->query;
140 };
141 2 $request->header('Content-Type' => 'application/x-www-form-urlencoded');
142 2 $request->header('Content-Length' => length($content));
143 2 $request->content($content);
144 }
145  
146 47 return $request;
147 }
148  
149 60 ▶sub run_test_request {
Subroutine run_test_request: called CC=1 SCAR=0.0
Pod documented
150 60 my ($self, @req) = @_;
151  
152 60 require HTTP::Request;
153  
154 60 require Plack::Test;
155  
156 60 my $request = $self->_test_request_spec_to_http_request(@req);
157  
158 Plack::Test::test_psgi(
159 60 ▶ $self->to_psgi_app, sub { shift->($request) }
Subroutine __ANON__: called CC=1 SCAR=0.0
160 60 );
161 }
162  
163 0 ▶sub _run_cli_test_request {
Subroutine _run_cli_test_request: not called CC=4 SCAR=30.0
164 0 my ($self, @req) = @_;
165 0 my $response = $self->run_test_request(@req);
166  
167 0 binmode(STDOUT); binmode(STDERR); # for win32
168  
169 0 print STDERR $response->status_line."\n";
170 0 print STDERR $response->headers_as_string("\n")."\n";
171 0 my $content = $response->content;
172 0 ▶ $content .= "\n" if length($content) and $content !~ /\n\z/;
Branch: 1 branch
BranchTrueFalseTotal
if length $content and not $content =~ /\n\z/ 0 0 0
Condition0%0/3
length $content and not $content =~ /\n\z/
!ll&&!rl&&r
000
MC/DC0%0/2
length $content and not $content =~ /\n\z/
length $content not $content =~ /\n\z/
Truth table0%0/3
A and not(B)
A= length $contentB= not $content =~ /\n\z/
ABresult
0X0
100
111
173 0 ▶ print STDOUT $content if $content;
Branch: 1 branch
BranchTrueFalseTotal
if $content 0 0 0
174 }
175  
176 0 ▶sub _run_cli {
Subroutine _run_cli: not called CC=1 SCAR=6.9
177 0 my $self = shift;
178 0 die $self->_cli_usage;
179 }
180  
181 0 ▶sub _cli_usage {
Subroutine _cli_usage: not called CC=1 SCAR=6.9
182 0 "To run this script in CGI test mode, pass a URL path beginning with /:\n".
183 "\n".
184 " $0 /some/path\n".
185 " $0 /\n"
186 }
187  
188 16 1;
189  
190 =head1 NAME
191  
192 Web::Simple::Application - A base class for your Web-Simple application
193  
194 =head1 DESCRIPTION
195  
196 This is a base class for your L<Web::Simple> application. You probably don't
197 need to construct this class yourself, since L<Web::Simple> does the 'heavy
198 lifting' for you in that regards.
199  
200 =head1 METHODS
201  
202 This class exposes the following public methods.
203  
204 =head2 default_config
205  
206 Merges with the C<config> initializer to provide configuration information for
207 your application. For example:
208  
209 sub default_config {
210 (
211 title => 'Bloggery',
212 posts_dir => $FindBin::Bin.'/posts',
213 );
214 }
215  
216 Now, the C<config> attribute of C<$self> will be set to a HashRef
217 containing keys 'title' and 'posts_dir'.
218  
219 The keys from default_config are merged into any config supplied, so
220 if you construct your application like:
221  
222 MyWebSimpleApp::Web->new(
223 config => { title => 'Spoon', environment => 'dev' }
224 )
225  
226 then C<config> will contain:
227  
228 {
229 title => 'Spoon',
230 posts_dir => '/path/to/myapp/posts',
231 environment => 'dev'
232 }
233  
234 =head2 run_if_script
235  
236 The run_if_script method is designed to be used at the end of the script
237 or .pm file where your application class is defined - for example:
238  
239 ## my_web_simple_app.pl
240 #!/usr/bin/env perl
241 use Web::Simple 'HelloWorld';
242  
243 {
244 package HelloWorld;
245  
246 sub dispatch_request {
247 sub (GET) {
248 [ 200, [ 'Content-type', 'text/plain' ], [ 'Hello world!' ] ]
249 },
250 sub () {
251 [ 405, [ 'Content-type', 'text/plain' ], [ 'Method not allowed' ] ]
252 }
253 }
254 }
255  
256 HelloWorld->run_if_script;
257  
258 This returns a true value, so your file is now valid as a module - so
259  
260 require 'my_web_simple_app.pl';
261  
262 my $hw = HelloWorld->new;
263  
264 will work fine (and you can rename it to lib/HelloWorld.pm later to make it
265 a real use-able module).
266  
267 However, it detects if it's being run as a script (via testing $0) and if
268 so attempts to do the right thing.
269  
270 If run under a CGI environment, your application will execute as a CGI.
271  
272 If run under a FastCGI environment, your application will execute as a
273 FastCGI process (this works both for dynamic shared-hosting-style FastCGI
274 and for apache FastCgiServer style setups).
275  
276 If run from the commandline with a URL path, it runs a GET request against
277 that path -
278  
279 $ perl -Ilib examples/hello-world/hello-world.cgi /
280 200 OK
281 Content-Type: text/plain
282
283 Hello world!
284  
285 You can also provide a method name -
286  
287 $ perl -Ilib examples/hello-world/hello-world.cgi POST /
288 405 Method Not Allowed
289 Content-Type: text/plain
290
291 Method not allowed
292  
293 For a POST or PUT request, pairs on the command line will be treated
294 as form variables. For any request, pairs on the command line ending in :
295 are treated as headers, and 'Content:' will set the request body -
296  
297 $ ./myapp POST / Accept: text/html form_field_name form_field_value
298
299 $ ./myapp POST / Content-Type: text/json Content: '{ "json": "here" }'
300  
301 The body of the response is sent to STDOUT and the headers to STDERR, so
302  
303 $ ./myapp GET / >index.html
304  
305 will generally do the right thing.
306  
307 To send basic authentication credentials, use user:pass@ syntax -
308  
309 $ ./myapp GET bob:secret@/protected/path
310  
311 Additionally, you can treat the file as though it were a standard PSGI
312 application file (*.psgi). For example you can start up up with C<plackup>
313  
314 plackup my_web_simple_app.pl
315  
316 or C<starman>
317  
318 starman my_web_simple_app.pl
319  
320 =head2 to_psgi_app
321  
322 This method is called by L</run_if_script> to create the L<PSGI> app coderef
323 for use via L<Plack> and L<plackup>. If you want to globally add middleware,
324 you can override this method:
325  
326 use Web::Simple 'HelloWorld';
327
328 {
329 package HelloWorld;
330 use Plack::Builder;
331
332 around 'to_psgi_app', sub {
333 my ($orig, $self) = (shift, shift);
334 my $app = $self->$orig(@_);
335 builder {
336 enable ...; ## whatever middleware you want
337 $app;
338 };
339 };
340 }
341  
342 This method can also be used to mount a Web::Simple application within
343 a separate C<*.psgi> file -
344  
345 use strictures 1;
346 use Plack::Builder;
347 use WSApp;
348 use AnotherWSApp;
349  
350 builder {
351 mount '/' => WSApp->to_psgi_app;
352 mount '/another' => AnotherWSApp->to_psgi_app;
353 };
354  
355 This method can be called as a class method, in which case it implicitly
356 calls ->new, or as an object method ... in which case it doesn't.
357  
358 =head2 run
359  
360 Used for running your application under stand-alone CGI and FCGI modes.
361  
362 I should document this more extensively but run_if_script will call it when
363 you need it, so don't worry about it too much.
364  
365 =head2 run_test_request
366  
367 my $res = $app->run_test_request(GET => '/' => %headers);
368  
369 my $res = $app->run_test_request(POST => '/' => %headers_or_form);
370  
371 my $res = $app->run_test_request($http_request);
372  
373 Accepts either an L<HTTP::Request> object or ($method, $path) and runs that
374 request against the application, returning an L<HTTP::Response> object.
375  
376 If the HTTP method is POST or PUT, then a series of pairs can be passed after
377 this to create a form style message body. If you need to test an upload, then
378 create an L<HTTP::Request> object by hand or use the C<POST> subroutine
379 provided by L<HTTP::Request::Common>.
380  
381 If you prefix the URL with 'user:pass@' this will be converted into
382 an Authorization header for HTTP basic auth:
383  
384 my $res = $app->run_test_request(
385 GET => 'bob:secret@/protected/resource'
386 );
387  
388 If pairs are passed where the key ends in :, it is instead treated as a
389 headers, so:
390  
391 my $res = $app->run_test_request(
392 POST => '/',
393 'Accept:' => 'text/html',
394 some_form_key => 'value'
395 );
396  
397 will do what you expect. You can also pass a special key of Content: to
398 set the request body:
399  
400 my $res = $app->run_test_request(
401 POST => '/',
402 'Content-Type:' => 'text/json',
403 'Content:' => '{ "json": "here" }',
404 );
405  
406 =head1 AUTHORS
407  
408 See L<Web::Simple> for authors.
409  
410 =head1 COPYRIGHT AND LICENSE
411  
412 See L<Web::Simple> for the copyright and license.
413  
414 =cut
« blib/lib/Web/Dispatch/Parser.pm ↑ Summary blib/lib/Web/Dispatch/ParamParser.pm »