fixed sort order bug
[catagits/Catalyst-Runtime.git] / lib / Catalyst / DispatchType / Chained.pm
1 package Catalyst::DispatchType::Chained;
2
3 use strict;
4 use base qw/Catalyst::DispatchType/;
5 use Text::SimpleTable;
6 use Catalyst::ActionChain;
7 use URI;
8
9 # please don't perltidy this. hairy code within.
10
11 =head1 NAME
12
13 Catalyst::DispatchType::Chained - Path Part DispatchType
14
15 =head1 SYNOPSIS
16
17 See L<Catalyst>.
18
19 =head1 DESCRIPTION
20
21 =head1 METHODS
22
23 =head2 $self->list($c)
24
25 Debug output for Path Part dispatch points
26
27 =cut
28
29 sub list {
30     my ( $self, $c ) = @_;
31
32     return unless $self->{endpoints};
33
34     my $paths = Text::SimpleTable->new(
35                     [ 35, 'Path Spec' ], [ 36, 'Private' ]
36                 );
37
38     ENDPOINT: foreach my $endpoint (
39                   sort { $a->reverse cmp $b->reverse }
40                            @{ $self->{endpoints} }
41                   ) {
42         my $args = $endpoint->attributes->{Args}->[0];
43         my @parts = (defined($args) ? (("*") x $args) : '...');
44         my @parents = ();
45         my $parent = "DUMMY";
46         my $curr = $endpoint;
47         while ($curr) {
48             if (my $cap = $curr->attributes->{CaptureArgs}) {
49                 unshift(@parts, (("*") x $cap->[0]));
50             }
51             if (my $pp = $curr->attributes->{PartPath}) {
52                 unshift(@parts, $pp->[0])
53                     if (defined $pp->[0] && length $pp->[0]);
54             }
55             $parent = $curr->attributes->{Chained}->[0];
56             $curr = $self->{actions}{$parent};
57             unshift(@parents, $curr) if $curr;
58         }
59         next ENDPOINT unless $parent eq '/'; # skip dangling action
60         my @rows;
61         foreach my $p (@parents) {
62             my $name = "/${p}";
63             if (my $cap = $p->attributes->{CaptureArgs}) {
64                 $name .= ' ('.$cap->[0].')';
65             }
66             unless ($p eq $parents[0]) {
67                 $name = "-> ${name}";
68             }
69             push(@rows, [ '', $name ]);
70         }
71         push(@rows, [ '', (@rows ? "=> " : '')."/${endpoint}" ]);
72         $rows[0][0] = join('/', '', @parts);
73         $paths->row(@$_) for @rows;
74     }
75
76     $c->log->debug( "Loaded Path Part actions:\n" . $paths->draw );
77 }
78
79 =head2 $self->match( $c, $path )
80
81 Matt is an idiot and hasn't documented this yet.
82
83 =cut
84
85 sub match {
86     my ( $self, $c, $path ) = @_;
87
88     return 0 if @{$c->req->args};
89
90     my @parts = split('/', $path);
91
92     my ($chain, $captures) = $self->recurse_match($c, '/', \@parts);
93
94     return 0 unless $chain;
95
96     my $action = Catalyst::ActionChain->from_chain($chain);
97
98     $c->req->action("/${action}");
99     $c->req->match("/${action}");
100     $c->req->captures($captures);
101     $c->action($action);
102     $c->namespace( $action->namespace );
103
104     return 1;
105 }
106
107 =head2 $self->recurse_match( $c, $parent, \@path_parts )
108
109 Matt is an idiot and hasn't documented this yet.
110
111 =cut
112
113 sub recurse_match {
114     my ( $self, $c, $parent, $path_parts ) = @_;
115     my $children = $self->{children_of}{$parent};
116     return () unless $children;
117     my @captures;
118     TRY: foreach my $try_part (sort { length($b) <=> length($a) }
119                                    keys %$children) {
120                                # $b then $a to try longest part first
121         my @parts = @$path_parts;
122         if (length $try_part) { # test and strip PathPart
123             next TRY unless
124               ($try_part eq join('/', # assemble equal number of parts
125                               splice( # and strip them off @parts as well
126                                 @parts, 0, scalar(@{[split('/', $try_part)]})
127                               ))); # @{[]} to avoid split to @_
128         }
129         my @try_actions = @{$children->{$try_part}};
130         TRY_ACTION: foreach my $action (@try_actions) {
131             if (my $capture_attr = $action->attributes->{CaptureArgs}) {
132                 my @captures;
133                 my @parts = @parts; # localise
134
135                 # strip CaptureArgs into list
136                 push(@captures, splice(@parts, 0, $capture_attr->[0]));
137
138                 # try the remaining parts against children of this action
139                 my ($actions, $captures) = $self->recurse_match(
140                                              $c, '/'.$action->reverse, \@parts
141                                            );
142                 if ($actions) {
143                     return [ $action, @$actions ], [ @captures, @$captures ];
144                 }
145             } else {
146                 {
147                     local $c->req->{arguments} = [ @{$c->req->args}, @parts ];
148                     next TRY_ACTION unless $action->match($c);
149                 }
150                 push(@{$c->req->args}, @parts);
151                 return [ $action ], [ ];
152             }
153         }
154     }
155     return ();
156 }
157
158 =head2 $self->register( $c, $action )
159
160 Matt is an idiot and hasn't documented this yet.
161
162 =cut
163
164 sub register {
165     my ( $self, $c, $action ) = @_;
166
167     my @chained_attr = @{ $action->attributes->{Chained} || [] };
168
169     return 0 unless @chained_attr;
170
171     if (@chained_attr > 2) {
172         Catalyst::Exception->throw(
173           "Multiple Chained attributes not supported registering ${action}"
174         );
175     }
176
177     my $parent = $chained_attr[0];
178
179     if (defined($parent) && length($parent)) {
180         if ($parent eq '.') {
181             $parent = '/'.$action->namespace;
182         } elsif ($parent !~ m/^\//) {
183             $parent = '/'.join('/', $action->namespace, $parent);
184         }
185     } else {
186         $parent = '/'
187     }
188
189     $action->attributes->{Chained} = [ $parent ];
190
191     my $children = ($self->{children_of}{$parent} ||= {});
192
193     my @path_part = @{ $action->attributes->{PathPart} || [] };
194
195     my $part = $action->name;
196
197     if (@path_part == 1 && defined $path_part[0]) {
198         $part = $path_part[0];
199     } elsif (@path_part > 1) {
200         Catalyst::Exception->throw(
201           "Multiple PathPart attributes not supported registering ${action}"
202         );
203     }
204
205     $action->attributes->{PartPath} = [ $part ];
206
207     unshift(@{ $children->{$part} ||= [] }, $action);
208
209     ($self->{actions} ||= {})->{'/'.$action->reverse} = $action;
210
211     unless ($action->attributes->{CaptureArgs}) {
212         unshift(@{ $self->{endpoints} ||= [] }, $action);
213     }
214
215     return 1;
216 }
217
218 =head2 $self->uri_for_action($action, $captures)
219
220 Matt is an idiot and hasn't documented this yet.
221
222 =cut
223
224 sub uri_for_action {
225     my ( $self, $action, $captures ) = @_;
226
227     return undef unless ($action->attributes->{Chained}
228                            && $action->attributes->{Args});
229
230     my @parts = ();
231     my @captures = @$captures;
232     my $parent = "DUMMY";
233     my $curr = $action;
234     while ($curr) {
235         if (my $cap = $curr->attributes->{CaptureArgs}) {
236             return undef unless @captures >= $cap->[0]; # not enough captures
237             unshift(@parts, splice(@captures, -$cap->[0]));
238         }
239         if (my $pp = $curr->attributes->{PartPath}) {
240             unshift(@parts, $pp->[0])
241                 if (defined $pp->[0] && length $pp->[0]);
242         }
243         $parent = $curr->attributes->{Chained}->[0];
244         $curr = $self->{actions}{$parent};
245     }
246
247     return undef unless $parent eq '/'; # fail for dangling action
248
249     return undef if @captures; # fail for too many captures
250
251     return join('/', '', @parts);
252    
253 }
254
255 =head1 AUTHOR
256
257 Matt S Trout <mst@shadowcatsystems.co.uk>
258
259 =head1 COPYRIGHT
260
261 This program is free software, you can redistribute it and/or modify it under
262 the same terms as Perl itself.
263
264 =cut
265
266 1;