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