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