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) {
38 return $try if ref($try) eq 'ARRAY';
39 if (ref($try) eq 'HASH') {
40 $env = { %$env, %$try };
44 my @result = $self->_to_try($try, \@match)->($env, @match);
45 next unless @result and defined($result[0]);
47 my $first = $result[0];
49 return $self->_unpack_array_match( $first )
50 if ref($first) eq 'ARRAY';
52 return $self->_prepare_middleware( $first, \@result )
53 if blessed($first) && $first->isa('Plack::Middleware');
55 return $self->_unwrap_middleware( $first, \@match, $env )
56 if ref($first) eq 'HASH' and $first->{+MAGIC_MIDDLEWARE_KEY};
59 if blessed($first) && !$first->can('to_app');
61 # make a copy so we don't screw with it assigning further up
63 unshift @match, sub { $self->_dispatch($env, @result) };
69 sub _unpack_array_match {
70 my ( $self, $match ) = @_;
71 return $match->[0] if @{$match} == 1 and ref($match->[0]) eq 'CODE';
75 sub _prepare_middleware {
76 my ( $self, $match, $results ) = @_;
77 die "Multiple results but first one is a middleware ($match)"
79 # middleware needs to uplevel exactly once to wrap the rest of the
80 # level it was created for - next elsif unwraps it
81 return { MAGIC_MIDDLEWARE_KEY, $match };
84 sub _unwrap_middleware {
85 my ( $self, $first, $match, $env ) = @_;
87 my $mw = $first->{+MAGIC_MIDDLEWARE_KEY};
89 $mw->app(sub { $self->_dispatch($_[0], @{$match}) });
91 return $mw->to_app->($env);
95 my ($self, $try, $more) = @_;
96 if (ref($try) eq 'CODE') {
97 if (defined(my $proto = prototype($try))) {
98 $self->_construct_node(
99 match => $self->_parser->parse($proto), run => $try
104 } elsif (!ref($try) and ref($more->[0]) eq 'CODE') {
105 $self->_construct_node(
106 match => $self->_parser->parse($try), run => shift(@$more)
108 } elsif (blessed($try) && $try->can('to_app')) {
111 die "No idea how we got here with $try";
115 sub _construct_node {
116 my ($self, %args) = @_;
117 $self->node_class->new({ %{$self->node_args}, %args });