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 (defined(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 if (my $res = $self->_have_result($first, \@result, \@match, $env)) {
54 # make a copy so we don't screw with it assigning further up
56 unshift @match, sub { $self->_dispatch($env, @result) };
63 my ($self, $first, $result, $match, $env) = @_;
65 if (ref($first) eq 'ARRAY') {
66 return $self->_unpack_array_match($first);
68 elsif (blessed($first) && $first->isa('Plack::Middleware')) {
69 return $self->_uplevel_middleware($first, $result);
71 elsif (ref($first) eq 'HASH' and $first->{+MAGIC_MIDDLEWARE_KEY}) {
72 return $self->_redispatch_with_middleware($first, $match, $env);
74 elsif (blessed($first) && !$first->can('to_app')) {
81 sub _unpack_array_match {
82 my ($self, $match) = @_;
83 return $match->[0] if @{$match} == 1 and ref($match->[0]) eq 'CODE';
87 sub _uplevel_middleware {
88 my ($self, $match, $results) = @_;
89 die "Multiple results but first one is a middleware ($match)"
91 # middleware needs to uplevel exactly once to wrap the rest of the
92 # level it was created for - next elsif unwraps it
93 return { MAGIC_MIDDLEWARE_KEY, $match };
96 sub _redispatch_with_middleware {
97 my ($self, $first, $match, $env) = @_;
99 my $mw = $first->{+MAGIC_MIDDLEWARE_KEY};
101 $mw->app(sub { $self->_dispatch($_[0], @{$match}) });
103 return $mw->to_app->($env);
107 my ($self, $try, $more) = @_;
109 # sub (<spec>) {} becomes a dispatcher
110 # sub {} is a PSGI app and can be returned as is
111 # '<spec>' => sub {} becomes a dispatcher
112 # $obj w/to_app method is a Plack::App-like thing - call it to get a PSGI app
114 if (ref($try) eq 'CODE') {
115 if (defined(my $proto = prototype($try))) {
116 $self->_construct_node(match => $proto, run => $try)->to_app;
120 } elsif (!ref($try) and ref($more->[0]) eq 'CODE') {
121 $self->_construct_node(match => $try, run => shift(@$more))->to_app;
122 } elsif (blessed($try) && $try->can('to_app')) {
125 die "No idea how we got here with $try";
129 sub _construct_node {
130 my ($self, %args) = @_;
131 $args{match} = $self->_parser->parse($args{match});
132 $self->node_class->new({ %{$self->node_args}, %args });