File Coverage

blib/lib/Plack/App/Cascade.pm
Criterion Covered Total %
statement 45 45 100.0
branch 16 16 100.0
condition n/a
subroutine 8 8 100.0
pod 3 3 100.0
total 72 72 100.0


line stmt bran cond sub pod time code
1             package Plack::App::Cascade;
2 2     2   171206 use strict;
  2         4  
  2         67  
3 2     2   7 use parent qw(Plack::Component);
  2         2  
  2         11  
4              
5 2     2   94 use Plack::Util;
  2         3  
  2         72  
6 2     2   802 use Plack::Util::Accessor qw(apps catch codes);
  2         5  
  2         15  
7              
8             sub add {
9 6     6 1 34 my $self = shift;
10 6 100       16 $self->apps([]) unless $self->apps;
11 6         11 push @{$self->apps}, @_;
  6         11  
12             }
13              
14             sub prepare_app {
15 6     6 1 9 my $self = shift;
16 6 100       32 my %codes = map { $_ => 1 } @{ $self->catch || [ 404 ] };
  8         32  
  6         19  
17 6         26 $self->codes(\%codes);
18             }
19              
20             sub call {
21 6     6 1 21 my($self, $env) = @_;
22              
23             return sub {
24 6     6   10 my $respond = shift;
25              
26 6         7 my $done;
27             my $respond_wrapper = sub {
28 9         22 my $res = shift;
29 9 100       22 if ($self->codes->{$res->[0]}) {
30             # suppress output by giving the app an
31             # output spool which drops everything on the floor
32             return Plack::Util::inline_object
33 7         43 write => sub { }, close => sub { };
34             } else {
35 2         2 $done = 1;
36 2         4 return $respond->($res);
37             }
38 6         19 };
39              
40 6 100       9 my @try = @{$self->apps || []};
  6         15  
41 6         14 my $tries_left = 0 + @try;
42              
43 6 100       12 if (not $tries_left) {
44 1         3 return $respond->([ 404, [ 'Content-Type' => 'text/html' ], [ '404 Not Found' ] ])
45             }
46              
47 5         10 for my $app (@try) {
48 12         35 my $res = $app->($env);
49 12 100       103 if ($tries_left-- == 1) {
50 3         18 $respond_wrapper = sub { $respond->(shift) };
  3         25  
51             }
52              
53 12 100       29 if (ref $res eq 'CODE') {
54 4         11 $res->($respond_wrapper);
55             } else {
56 8         14 $respond_wrapper->($res);
57             }
58 12 100       100 return if $done;
59             }
60 6         58 };
61             }
62              
63             1;
64              
65             __END__