Fixed private action table
[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->action->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->stack->[-1]->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 => Catalyst::Utils::class2prefix(
139                         $class, $c->config->{case_sensitive}
140                     ),
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( $action, $namespace )
198
199 =cut
200
201 sub get_action {
202     my ( $self, $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($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($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         if ( my $extra = $path[ ( scalar @match ) - 1 ] ) {
264             $visitor->setSearchPath($extra);
265             $match[-1]->accept($visitor);
266             push( @match, $visitor->getResult ) if defined $visitor->getResult;
267         }
268     }
269
270     return map { $_->getNodeValue } @match;
271 }
272
273 =item $self->register( $c, $action )
274
275 =cut
276
277 sub register {
278     my ( $self, $c, $action ) = @_;
279
280     my $registered = $self->registered_dispatch_types;
281
282     my $priv = 0;
283     foreach my $key ( keys %{ $action->attributes } ) {
284         $priv++ if $key eq 'Private';
285         my $class = "Catalyst::DispatchType::$key";
286         unless ( $registered->{$class} ) {
287             eval "require $class";
288             push( @{ $self->dispatch_types }, $class->new ) unless $@;
289             $registered->{$class} = 1;
290         }
291     }
292
293     # Pass the action to our dispatch types so they can register it if reqd.
294     my $reg = 0;
295     foreach my $type ( @{ $self->dispatch_types } ) {
296         $reg++ if $type->register( $c, $action );
297     }
298
299     return unless $reg + $priv;
300
301     my $namespace = $action->namespace;
302     my $parent    = $self->tree;
303     my $visitor   = Tree::Simple::Visitor::FindByPath->new;
304
305     if ($namespace) {
306         for my $part ( split '/', $namespace ) {
307             $visitor->setSearchPath($part);
308             $parent->accept($visitor);
309             my $child = $visitor->getResult;
310
311             unless ($child) {
312
313                 # Create a new tree node and an ActionContainer to form
314                 # its value.
315
316                 my $container =
317                   Catalyst::ActionContainer->new(
318                     { part => $part, actions => {} } );
319                 $child = $parent->addChild( Tree::Simple->new($container) );
320                 $visitor->setSearchPath($part);
321                 $parent->accept($visitor);
322                 $child = $visitor->getResult;
323             }
324
325             $parent = $child;
326         }
327     }
328
329     # Set the method value
330     $parent->getNodeValue->actions->{ $action->name } = $action;
331 }
332
333 =item $self->setup_actions( $class, $component )
334
335 =cut
336
337 sub setup_actions {
338     my ( $self, $c ) = @_;
339
340     $self->dispatch_types( [] );
341     $self->registered_dispatch_types( {} );
342     $self->method_action_class('Catalyst::Action');
343     $self->action_container_class('Catalyst::ActionContainer');
344
345     # Preload action types
346     for my $type (@PRELOAD) {
347         my $class = "Catalyst::DispatchType::$type";
348         eval "require $class";
349         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
350           if $@;
351         push @{ $self->dispatch_types }, $class->new;
352         $self->registered_dispatch_types->{$class} = 1;
353     }
354
355     # We use a tree
356     my $container =
357       Catalyst::ActionContainer->new( { part => '/', actions => {} } );
358     $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
359
360     foreach my $comp ( values %{ $c->components } ) {
361         $comp->register_actions($c) if $comp->can('register_actions');
362     }
363
364     # Postload action types
365     for my $type (@POSTLOAD) {
366         my $class = "Catalyst::DispatchType::$type";
367         eval "require $class";
368         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
369           if $@;
370         push @{ $self->dispatch_types }, $class->new;
371     }
372
373     return unless $c->debug;
374
375     my $privates = Text::SimpleTable->new(
376         [ 20, 'Private' ],
377         [ 38, 'Class' ],
378         [ 12, 'Method' ]
379     );
380
381     my $has_private = 0;
382     my $walker = sub {
383         my ( $walker, $parent, $prefix ) = @_;
384         $prefix .= $parent->getNodeValue || '';
385         $prefix .= '/' unless $prefix =~ /\/$/;
386         my $node = $parent->getNodeValue->actions;
387
388         for my $action ( keys %{$node} ) {
389             my $action_obj = $node->{$action};
390             next
391               if ( ( $action =~ /^_.*/ )
392                 && ( !$c->config->{show_internal_actions} ) );
393             $privates->row( "$prefix$action", $action_obj->class, $action );
394             $has_private = 1;
395         }
396
397         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
398     };
399
400     $walker->( $walker, $self->tree, '' );
401     $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
402       if ($has_private);
403
404     # List all public actions
405     $_->list($c) for @{ $self->dispatch_types };
406 }
407
408 =back
409
410 =head1 AUTHOR
411
412 Sebastian Riedel, C<sri@cpan.org>
413 Matt S Trout, C<mst@shadowcatsystems.co.uk>
414
415 =head1 COPYRIGHT
416
417 This program is free software, you can redistribute it and/or modify it under
418 the same terms as Perl itself.
419
420 =cut
421
422 1;