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