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