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