4 use Scalar::Util qw(blessed);
6 sub MAGIC_MIDDLEWARE_KEY { __PACKAGE__.'.middleware' }
9 use Web::Dispatch::Parser;
10 use Web::Dispatch::Node;
12 with 'Web::Dispatch::ToApp';
14 has app => (is => 'ro', required => 1);
16 is => 'ro', default => quote_sub q{ 'Web::Dispatch::Parser' }
19 is => 'ro', default => quote_sub q{ 'Web::Dispatch::Node' }
21 has node_args => (is => 'ro', default => quote_sub q{ {} });
22 has _parser => (is => 'lazy');
26 $self->parser_class->new;
30 my ($self, $env) = @_;
31 $self->_dispatch($env, $self->app);
35 my ($self, $env, @match) = @_;
36 while (my $try = shift @match) {
37 if (ref($try) eq 'HASH') {
38 $env = { %$env, %$try };
40 } elsif (ref($try) eq 'ARRAY') {
43 my @result = $self->_to_try($try, \@match)->($env, @match);
44 next unless @result and defined($result[0]);
45 if (ref($result[0]) eq 'ARRAY') {
46 if (@{$result[0]} == 1 and ref($result[0][0]) eq 'CODE') {
50 } elsif (blessed($result[0]) && $result[0]->isa('Plack::Middleware')) {
51 die "Multiple results but first one is a middleware ($result[0])"
53 # middleware needs to uplevel exactly once to wrap the rest of the
54 # level it was created for - next elsif unwraps it
55 return { MAGIC_MIDDLEWARE_KEY, $result[0] };
58 ref($result[0]) eq 'HASH'
59 and my $mw = $result[0]->{+MAGIC_MIDDLEWARE_KEY}
61 $mw->app(sub { $self->_dispatch($_[0], @match) });
62 return $mw->to_app->($env);
63 } elsif (blessed($result[0]) && !$result[0]->can('to_app')) {
66 # make a copy so we don't screw with it assigning further up
68 unshift @match, sub { $self->_dispatch($env, @result) };
75 my ($self, $try, $more) = @_;
76 if (ref($try) eq 'CODE') {
77 if (defined(my $proto = prototype($try))) {
78 $self->_construct_node(
79 match => $self->_parser->parse($proto), run => $try
84 } elsif (!ref($try) and ref($more->[0]) eq 'CODE') {
85 $self->_construct_node(
86 match => $self->_parser->parse($try), run => shift(@$more)
88 } elsif (blessed($try) && $try->can('to_app')) {
91 die "No idea how we got here with $try";
96 my ($self, %args) = @_;
97 $self->node_class->new({ %{$self->node_args}, %args });