- Refactored get_action into get_action and get_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::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/);
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     # Relative forwards from detach
86     my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
87       && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
88
89     my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
90
91     my $result;
92
93     my $command_copy = $command;
94
95     unless ( $command_copy =~ s/^\/// ) {
96         my $namespace =
97           Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
98           || '';
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                 $command = $tail;
112                 push( @{$arguments}, @extra_args );
113                 last DESCEND;
114             }
115             unshift( @extra_args, $tail );
116         }
117     }
118
119     unless ( $result ) {
120
121         unless ( $c->components->{$command} ) {
122             my $error =
123 qq/Couldn't forward to command "$command". Invalid action or component./;
124             $c->error($error);
125             $c->log->debug($error) if $c->debug;
126             return 0;
127         }
128
129         my $class  = $command;
130         my $method = shift || 'process';
131
132         if ( my $code = $c->components->{$class}->can($method) ) {
133             my $action = Catalyst::Action->new(
134                 {
135                     name      => $method,
136                     code      => $code,
137                     reverse   => "$class->$method",
138                     class     => $class,
139                     namespace => $class,
140                 }
141             );
142             $result = $action;
143         }
144
145         else {
146             my $error =
147               qq/Couldn't forward to "$class". Does not implement "$method"/;
148             $c->error($error);
149             $c->log->debug($error)
150               if $c->debug;
151             return 0;
152         }
153
154     }
155
156     local $c->request->{arguments} = [ @{$arguments} ];
157
158     $result->execute($c);
159
160     return $c->state;
161 }
162
163 =item $self->prepare_action($c)
164
165 =cut
166
167 sub prepare_action {
168     my ( $self, $c ) = @_;
169     my $path = $c->req->path;
170     my @path = split /\//, $c->req->path;
171     $c->req->args( \my @args );
172
173     push( @path, '/' ) unless @path;    # Root action
174
175   DESCEND: while (@path) {
176         $path = join '/', @path;
177
178         $path = '' if $path eq '/';     # Root action
179
180         # Check out dispatch types to see if any will handle the path at
181         # this level
182
183         foreach my $type ( @{ $self->dispatch_types } ) {
184             last DESCEND if $type->match( $c, $path );
185         }
186
187         # If not, move the last part path to args
188
189         unshift @args, pop @path;
190     }
191
192     $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
193       if ( $c->debug && @args );
194 }
195
196 =item $self->get_action( $c, $action, $namespace )
197
198 =cut
199
200 sub get_action {
201     my ( $self, $c, $action, $namespace ) = @_;
202     return [] unless $action;
203     $namespace ||= '';
204     $namespace = '' if $namespace eq '/';
205
206     my @match = $self->get_containers($namespace);
207
208     my $node = $match[-1]->actions;    # Only bother looking at the last one
209
210     if ( defined $node->{$action}
211         && ( $node->{$action}->namespace eq $namespace ) )
212     {
213         return $node->{$action};
214     }
215 }
216
217 =item $self->get_actions( $c, $action, $namespace )
218
219 =cut
220
221 sub get_actions {
222     my ( $self, $c, $action, $namespace ) = @_;
223     return [] unless $action;
224     $namespace ||= '';
225     $namespace = '' if $namespace eq '/';
226
227     my @match = $self->get_containers($namespace);
228
229     return
230         map    { $_->{$action} }
231           grep { defined $_->{$action} }    # If it exists in the container
232           map  { $_->actions }              # Get action hash for container
233           @match
234 }
235
236 =item $self->get_containers( $namespace )
237
238 =cut
239
240 sub get_containers {
241     my ( $self, $namespace ) = @_;
242
243     # If the namespace is / just return the root ActionContainer
244
245     return ( $self->tree->getNodeValue )
246       if ( !$namespace || ( $namespace eq '/' ) );
247
248     # Use a visitor to recurse down the tree finding the ActionContainers
249     # for each namespace in the chain.
250
251     my $visitor = Tree::Simple::Visitor::FindByPath->new;
252     my @path = split( '/', $namespace );
253     $visitor->setSearchPath(@path);
254     $self->tree->accept($visitor);
255
256     my @match = $visitor->getResults;
257     @match = ( $self->tree ) unless @match;
258
259     if ( !defined $visitor->getResult ) {
260
261         # If we don't manage to match, the visitor doesn't return the last
262         # node is matched, so foo/bar/baz would only find the 'foo' node,
263         # not the foo and foo/bar nodes as it should. This does another
264         # single-level search to see if that's the case, and the 'last unless'
265         # should catch any failures - or short-circuit this if this *is* a
266         # bug in the visitor and gets fixed.
267
268         my $extra = $path[ ( scalar @match ) - 1 ];
269         last unless $extra;
270         $visitor->setSearchPath($extra);
271         $match[-1]->accept($visitor);
272         push( @match, $visitor->getResult ) if defined $visitor->getResult;
273     }
274
275     return map { $_->getNodeValue } @match;
276 }
277
278 =item $self->set_action( $c, $action, $code, $class, $attrs )
279
280 =cut
281
282 sub set_action {
283     my ( $self, $c, $method, $code, $class, $attrs ) = @_;
284
285     my $namespace =
286       Catalyst::Utils::class2prefix( $class, $c->config->{case_sensitive} )
287       || '';
288     my %attributes;
289
290     for my $attr ( @{$attrs} ) {
291
292         # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
293
294         my %initialized;
295         $initialized{ ref $_ }++ for @{ $self->dispatch_types };
296
297         if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
298
299             # Initialize types
300             my $class = "Catalyst::DispatchType::$key";
301             unless ( $initialized{$class} ) {
302                 eval "require $class";
303                 push( @{ $self->dispatch_types }, $class->new ) unless $@;
304                 $initialized{$class}++;
305             }
306
307             if ( defined $value ) {
308                 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
309             }
310             push( @{ $attributes{$key} }, $value );
311         }
312     }
313
314     if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
315         $c->log->debug( 'Bad action definition "'
316               . join( ' ', @{$attrs} )
317               . qq/" for "$class->$method"/ )
318           if $c->debug;
319         return;
320     }
321     return unless keys %attributes;
322
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     my $reverse = $namespace ? "$namespace/$method" : $method;
351
352     my $action = Catalyst::Action->new(
353         {
354             name       => $method,
355             code       => $code,
356             reverse    => $reverse,
357             namespace  => $namespace,
358             class      => $class,
359             attributes => \%attributes,
360         }
361     );
362
363     # Set the method value
364     $parent->getNodeValue->actions->{$method} = $action;
365
366     # Pass the action to our dispatch types so they can register it if reqd.
367     foreach my $type ( @{ $self->dispatch_types } ) {
368         $type->register( $c, $action );
369     }
370 }
371
372 =item $self->setup_actions( $class, $component )
373
374 =cut
375
376 sub setup_actions {
377     my ( $self, $c ) = @_;
378
379     $self->dispatch_types( [] );
380
381     # Preload action types
382     for my $type (@PRELOAD) {
383         my $class = "Catalyst::DispatchType::$type";
384         eval "require $class";
385         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
386           if $@;
387         push @{ $self->dispatch_types }, $class->new;
388     }
389
390     # We use a tree
391     my $container =
392       Catalyst::ActionContainer->new( { part => '/', actions => {} } );
393     $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
394
395     for my $comp ( keys %{ $c->components } ) {
396
397         # We only setup components that inherit from Catalyst::Base
398         next unless $comp->isa('Catalyst::Base');
399
400         for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
401             my ( $code, $attrs ) = @{$action};
402             my $name = '';
403             no strict 'refs';
404             my @cache = ( $comp, @{"$comp\::ISA"} );
405             my %classes;
406
407             while ( my $class = shift @cache ) {
408                 $classes{$class}++;
409                 for my $isa ( @{"$class\::ISA"} ) {
410                     next if $classes{$isa};
411                     push @cache, $isa;
412                     $classes{$isa}++;
413                 }
414             }
415
416             for my $class ( keys %classes ) {
417                 for my $sym ( values %{ $class . '::' } ) {
418                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
419                         $name = *{$sym}{NAME};
420                         $self->set_action( $c, $name, $code, $comp, $attrs );
421                         last;
422                     }
423                 }
424             }
425         }
426     }
427
428     # Postload action types
429     for my $type (@POSTLOAD) {
430         my $class = "Catalyst::DispatchType::$type";
431         eval "require $class";
432         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
433           if $@;
434         push @{ $self->dispatch_types }, $class->new;
435     }
436
437     return unless $c->debug;
438
439     my $privates = Text::ASCIITable->new;
440     $privates->setCols( 'Private', 'Class' );
441     $privates->setColWidth( 'Private', 36, 1 );
442     $privates->setColWidth( 'Class',   37, 1 );
443
444     my $walker = sub {
445         my ( $walker, $parent, $prefix ) = @_;
446         $prefix .= $parent->getNodeValue || '';
447         $prefix .= '/' unless $prefix =~ /\/$/;
448         my $node = $parent->getNodeValue->actions;
449
450         for my $action ( keys %{$node} ) {
451             my $action_obj = $node->{$action};
452             next
453               if ( ( $action =~ /^_.*/ )
454                 && ( !$c->config->{show_internal_actions} ) );
455             $privates->addRow( "$prefix$action", $action_obj->class );
456         }
457
458         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
459     };
460
461     $walker->( $walker, $self->tree, '' );
462     $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
463       if ( @{ $privates->{tbl_rows} } );
464
465     # List all public actions
466     $_->list($c) for @{ $self->dispatch_types };
467 }
468
469 =back
470
471 =head1 AUTHOR
472
473 Sebastian Riedel, C<sri@cpan.org>
474
475 =head1 COPYRIGHT
476
477 This program is free software, you can redistribute it and/or modify it under
478 the same terms as Perl itself.
479
480 =cut
481
482 1;