Fixed forward
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Dispatcher.pm
1 package Catalyst::Dispatcher;
2
3 use strict;
4 use base 'Class::Accessor::Fast';
5 use Catalyst::Exception;
6 use Catalyst::Utils;
7 use Catalyst::Action;
8 use Catalyst::ActionContainer;
9 use Catalyst::DispatchType::Default;
10 use Catalyst::DispatchType::Index;
11 use Text::SimpleTable;
12 use Tree::Simple;
13 use Tree::Simple::Visitor::FindByPath;
14
15 # Stringify to class
16 use overload '""' => sub { return ref shift }, fallback => 1;
17
18 __PACKAGE__->mk_accessors(
19     qw/tree dispatch_types registered_dispatch_types
20       method_action_class action_container_class/
21 );
22
23 # Preload these action types
24 our @PRELOAD = qw/Path Regex/;
25
26 # Postload these action types
27 our @POSTLOAD = qw/Index Default/;
28
29 =head1 NAME
30
31 Catalyst::Dispatcher - The Catalyst Dispatcher
32
33 =head1 SYNOPSIS
34
35 See L<Catalyst>.
36
37 =head1 DESCRIPTION
38
39 =head1 METHODS
40
41 =over 4
42
43 =item $self->detach( $c, $command [, \@arguments ] )
44
45 =cut
46
47 sub detach {
48     my ( $self, $c, $command, @args ) = @_;
49     $c->forward( $command, @args ) if $command;
50     die $Catalyst::DETACH;
51 }
52
53 =item $self->dispatch($c)
54
55 =cut
56
57 sub dispatch {
58     my ( $self, $c ) = @_;
59
60     if ( $c->action ) {
61         $c->forward( join( '/', '', $c->namespace, '_DISPATCH' ) );
62     }
63
64     else {
65         my $path  = $c->req->path;
66         my $error = $path
67           ? qq/Unknown resource "$path"/
68           : "No default action defined";
69         $c->log->error($error) if $c->debug;
70         $c->error($error);
71     }
72 }
73
74 =item $self->forward( $c, $command [, \@arguments ] )
75
76 =cut
77
78 sub forward {
79     my $self    = shift;
80     my $c       = shift;
81     my $command = shift;
82
83     $command = ref $command if ref $command;
84
85     unless ($command) {
86         $c->log->debug('Nothing to forward to') if $c->debug;
87         return 0;
88     }
89
90     my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
91
92     my $result;
93
94     my $command_copy = $command;
95
96     unless ( $command_copy =~ s/^\/// ) {
97         my $namespace = $c->namespace;
98         $command_copy = "${namespace}/${command}";
99     }
100
101     unless ( $command_copy =~ /\// ) {
102         $result = $c->get_action( $command_copy, '/' );
103     }
104     else {
105         my @extra_args;
106       DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
107             my $tail = $2;
108             $result = $c->get_action( $tail, $1 );
109             if ($result) {
110                 $command = $tail;
111                 push( @{$arguments}, @extra_args );
112                 last DESCEND;
113             }
114             unshift( @extra_args, $tail );
115         }
116     }
117
118     unless ($result) {
119
120         my $comp;
121
122         unless ( $comp = $c->component($command) ) {
123             my $error =
124 qq/Couldn't forward to command "$command". Invalid action or component./;
125             $c->error($error);
126             $c->log->debug($error) if $c->debug;
127             return 0;
128         }
129
130         my $class  = ref $comp;
131         my $method = shift || 'process';
132
133         if ( my $code = $class->can($method) ) {
134             my $action = $self->method_action_class->new(
135                 {
136                     name      => $method,
137                     code      => $code,
138                     reverse   => "$class->$method",
139                     class     => $class,
140                     namespace => $class,
141                 }
142             );
143             $result = $action;
144         }
145
146         else {
147             my $error =
148               qq/Couldn't forward to "$class". Does not implement "$method"/;
149             $c->error($error);
150             $c->log->debug($error)
151               if $c->debug;
152             return 0;
153         }
154
155     }
156
157     local $c->request->{arguments} = [ @{$arguments} ];
158
159     $result->execute($c);
160
161     return $c->state;
162 }
163
164 =item $self->prepare_action($c)
165
166 =cut
167
168 sub prepare_action {
169     my ( $self, $c ) = @_;
170     my $path = $c->req->path;
171     my @path = split /\//, $c->req->path;
172     $c->req->args( \my @args );
173
174     push( @path, '/' ) unless @path;    # Root action
175
176   DESCEND: while (@path) {
177         $path = join '/', @path;
178
179         $path = '' if $path eq '/';     # Root action
180
181         # Check out dispatch types to see if any will handle the path at
182         # this level
183
184         foreach my $type ( @{ $self->dispatch_types } ) {
185             last DESCEND if $type->match( $c, $path );
186         }
187
188         # If not, move the last part path to args
189
190         unshift @args, pop @path;
191     }
192
193     $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
194       if ( $c->debug && @args );
195 }
196
197 =item $self->get_action( $c, $action, $namespace )
198
199 =cut
200
201 sub get_action {
202     my ( $self, $c, $name, $namespace ) = @_;
203     return unless $name;
204     $namespace ||= '';
205     $namespace = '' if $namespace eq '/';
206
207     my @match = $self->get_containers($namespace);
208
209     return unless @match;
210
211     if ( my $action = $match[-1]->get_action( $c, $name ) ) {
212         return $action if $action->namespace eq $namespace;
213     }
214 }
215
216 =item $self->get_actions( $c, $action, $namespace )
217
218 =cut
219
220 sub get_actions {
221     my ( $self, $c, $action, $namespace ) = @_;
222     return [] unless $action;
223     $namespace ||= '';
224     $namespace = '' if $namespace eq '/';
225
226     my @match = $self->get_containers($namespace);
227
228     return map { $_->get_action( $c, $action ) } @match;
229 }
230
231 =item $self->get_containers( $namespace )
232
233 =cut
234
235 sub get_containers {
236     my ( $self, $namespace ) = @_;
237
238     # If the namespace is / just return the root ActionContainer
239
240     return ( $self->tree->getNodeValue )
241       if ( !$namespace || ( $namespace eq '/' ) );
242
243     # Use a visitor to recurse down the tree finding the ActionContainers
244     # for each namespace in the chain.
245
246     my $visitor = Tree::Simple::Visitor::FindByPath->new;
247     my @path = split( '/', $namespace );
248     $visitor->setSearchPath(@path);
249     $self->tree->accept($visitor);
250
251     my @match = $visitor->getResults;
252     @match = ( $self->tree ) unless @match;
253
254     if ( !defined $visitor->getResult ) {
255
256         # If we don't manage to match, the visitor doesn't return the last
257         # node is matched, so foo/bar/baz would only find the 'foo' node,
258         # not the foo and foo/bar nodes as it should. This does another
259         # single-level search to see if that's the case, and the 'last unless'
260         # should catch any failures - or short-circuit this if this *is* a
261         # bug in the visitor and gets fixed.
262
263         my $extra = $path[ ( scalar @match ) - 1 ];
264         last unless $extra;
265         $visitor->setSearchPath($extra);
266         $match[-1]->accept($visitor);
267         push( @match, $visitor->getResult ) if defined $visitor->getResult;
268     }
269
270     return map { $_->getNodeValue } @match;
271 }
272
273 sub register {
274     my ( $self, $c, $action ) = @_;
275
276     my $namespace = $action->namespace;
277     my $parent    = $self->tree;
278     my $visitor   = Tree::Simple::Visitor::FindByPath->new;
279
280     if ($namespace) {
281         for my $part ( split '/', $namespace ) {
282             $visitor->setSearchPath($part);
283             $parent->accept($visitor);
284             my $child = $visitor->getResult;
285
286             unless ($child) {
287
288                 # Create a new tree node and an ActionContainer to form
289                 # its value.
290
291                 my $container =
292                   Catalyst::ActionContainer->new(
293                     { part => $part, actions => {} } );
294                 $child = $parent->addChild( Tree::Simple->new($container) );
295                 $visitor->setSearchPath($part);
296                 $parent->accept($visitor);
297                 $child = $visitor->getResult;
298             }
299
300             $parent = $child;
301         }
302     }
303
304     # Set the method value
305     $parent->getNodeValue->actions->{ $action->name } = $action;
306
307     my $registered = $self->registered_dispatch_types;
308
309     foreach my $key ( keys %{ $action->attributes } ) {
310         my $class = "Catalyst::DispatchType::$key";
311         unless ( $registered->{$class} ) {
312             eval "require $class";
313             push( @{ $self->dispatch_types }, $class->new ) unless $@;
314             $registered->{$class} = 1;
315         }
316     }
317
318     # Pass the action to our dispatch types so they can register it if reqd.
319     foreach my $type ( @{ $self->dispatch_types } ) {
320         $type->register( $c, $action );
321     }
322 }
323
324 =item $self->setup_actions( $class, $component )
325
326 =cut
327
328 sub setup_actions {
329     my ( $self, $c ) = @_;
330
331     $self->dispatch_types( [] );
332     $self->registered_dispatch_types( {} );
333     $self->method_action_class('Catalyst::Action');
334     $self->action_container_class('Catalyst::ActionContainer');
335
336     # Preload action types
337     for my $type (@PRELOAD) {
338         my $class = "Catalyst::DispatchType::$type";
339         eval "require $class";
340         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
341           if $@;
342         push @{ $self->dispatch_types }, $class->new;
343         $self->registered_dispatch_types->{$class} = 1;
344     }
345
346     # We use a tree
347     my $container =
348       Catalyst::ActionContainer->new( { part => '/', actions => {} } );
349     $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
350
351     $c->register_actions($c);
352
353     foreach my $comp ( values %{ $c->components } ) {
354         $comp->register_actions($c) if $comp->can('register_actions');
355     }
356
357     # Postload action types
358     for my $type (@POSTLOAD) {
359         my $class = "Catalyst::DispatchType::$type";
360         eval "require $class";
361         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
362           if $@;
363         push @{ $self->dispatch_types }, $class->new;
364     }
365
366     return unless $c->debug;
367
368     my $privates = Text::SimpleTable->new( [ 36, 'Private' ], [ 37, 'Class' ] );
369
370     my $has_private = 0;
371     my $walker = sub {
372         my ( $walker, $parent, $prefix ) = @_;
373         $prefix .= $parent->getNodeValue || '';
374         $prefix .= '/' unless $prefix =~ /\/$/;
375         my $node = $parent->getNodeValue->actions;
376
377         for my $action ( keys %{$node} ) {
378             my $action_obj = $node->{$action};
379             next
380               if ( ( $action =~ /^_.*/ )
381                 && ( !$c->config->{show_internal_actions} ) );
382             $privates->row( "$prefix$action", $action_obj->class );
383             $has_private = 1;
384         }
385
386         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
387     };
388
389     $walker->( $walker, $self->tree, '' );
390     $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
391       if ($has_private);
392
393     # List all public actions
394     $_->list($c) for @{ $self->dispatch_types };
395 }
396
397 =back
398
399 =head1 AUTHOR
400
401 Sebastian Riedel, C<sri@cpan.org>
402 Matt S Trout, C<mst@shadowcatsystems.co.uk>
403
404 =head1 COPYRIGHT
405
406 This program is free software, you can redistribute it and/or modify it under
407 the same terms as Perl itself.
408
409 =cut
410
411 1;