- Punted get_action to ActionContainer
[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, $name, $namespace ) = @_;
202     return unless $name;
203     $namespace ||= '';
204     $namespace = '' if $namespace eq '/';
205
206     my @match = $self->get_containers($namespace);
207
208     return unless @match;
209
210     if ( my $action = $match[-1]->get_action( $c, $name ) )
211     {
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($c, $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         my $extra = $path[ ( scalar @match ) - 1 ];
264         last unless $extra;
265         $visitor->setSearchPath($extra);
266         $match[-1]->accept($visitor);
267         push( @match, $visitor->getResult ) if defined $visitor->getResult;
268     }
269
270     return map { $_->getNodeValue } @match;
271 }
272
273 =item $self->set_action( $c, $action, $code, $class, $attrs )
274
275 =cut
276
277 sub set_action {
278     my ( $self, $c, $method, $code, $class, $attrs ) = @_;
279
280     my $namespace =
281       Catalyst::Utils::class2prefix( $class, $c->config->{case_sensitive} )
282       || '';
283     my %attributes;
284
285     for my $attr ( @{$attrs} ) {
286
287         # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
288
289         my %initialized;
290         $initialized{ ref $_ }++ for @{ $self->dispatch_types };
291
292         if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
293
294             # Initialize types
295             my $class = "Catalyst::DispatchType::$key";
296             unless ( $initialized{$class} ) {
297                 eval "require $class";
298                 push( @{ $self->dispatch_types }, $class->new ) unless $@;
299                 $initialized{$class}++;
300             }
301
302             if ( defined $value ) {
303                 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
304             }
305             push( @{ $attributes{$key} }, $value );
306         }
307     }
308
309     if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
310         $c->log->debug( 'Bad action definition "'
311               . join( ' ', @{$attrs} )
312               . qq/" for "$class->$method"/ )
313           if $c->debug;
314         return;
315     }
316     return unless keys %attributes;
317
318     my $reverse = $namespace ? "$namespace/$method" : $method;
319
320     my $action = Catalyst::Action->new(
321         {
322             name       => $method,
323             code       => $code,
324             reverse    => $reverse,
325             namespace  => $namespace,
326             class      => $class,
327             attributes => \%attributes,
328         }
329     );
330
331     $self->register($c, $action);
332 }
333
334 sub register {
335     my ( $self, $c, $action ) = @_;
336
337     my $namespace = $action->namespace;
338     my $parent    = $self->tree;
339     my $visitor   = Tree::Simple::Visitor::FindByPath->new;
340
341     if ($namespace) {
342         for my $part ( split '/', $namespace ) {
343             $visitor->setSearchPath($part);
344             $parent->accept($visitor);
345             my $child = $visitor->getResult;
346
347             unless ($child) {
348
349                 # Create a new tree node and an ActionContainer to form
350                 # its value.
351
352                 my $container =
353                   Catalyst::ActionContainer->new(
354                     { part => $part, actions => {} } );
355                 $child = $parent->addChild( Tree::Simple->new($container) );
356                 $visitor->setSearchPath($part);
357                 $parent->accept($visitor);
358                 $child = $visitor->getResult;
359             }
360
361             $parent = $child;
362         }
363     }
364
365     # Set the method value
366     $parent->getNodeValue->actions->{$action->name} = $action;
367
368     # Pass the action to our dispatch types so they can register it if reqd.
369     foreach my $type ( @{ $self->dispatch_types } ) {
370         $type->register( $c, $action );
371     }
372 }
373
374 =item $self->setup_actions( $class, $component )
375
376 =cut
377
378 sub setup_actions {
379     my ( $self, $c ) = @_;
380
381     $self->dispatch_types( [] );
382
383     # Preload action types
384     for my $type (@PRELOAD) {
385         my $class = "Catalyst::DispatchType::$type";
386         eval "require $class";
387         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
388           if $@;
389         push @{ $self->dispatch_types }, $class->new;
390     }
391
392     # We use a tree
393     my $container =
394       Catalyst::ActionContainer->new( { part => '/', actions => {} } );
395     $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
396
397     for my $comp ( keys %{ $c->components } ) {
398
399         # We only setup components that inherit from Catalyst::Base
400         next unless $comp->isa('Catalyst::Base');
401
402         for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
403             my ( $code, $attrs ) = @{$action};
404             my $name = '';
405             no strict 'refs';
406             my @cache = ( $comp, @{"$comp\::ISA"} );
407             my %classes;
408
409             while ( my $class = shift @cache ) {
410                 $classes{$class}++;
411                 for my $isa ( @{"$class\::ISA"} ) {
412                     next if $classes{$isa};
413                     push @cache, $isa;
414                     $classes{$isa}++;
415                 }
416             }
417
418             for my $class ( keys %classes ) {
419                 for my $sym ( values %{ $class . '::' } ) {
420                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
421                         $name = *{$sym}{NAME};
422                         $self->set_action( $c, $name, $code, $comp, $attrs );
423                         last;
424                     }
425                 }
426             }
427         }
428     }
429
430     # Postload action types
431     for my $type (@POSTLOAD) {
432         my $class = "Catalyst::DispatchType::$type";
433         eval "require $class";
434         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
435           if $@;
436         push @{ $self->dispatch_types }, $class->new;
437     }
438
439     return unless $c->debug;
440
441     my $privates = Text::ASCIITable->new;
442     $privates->setCols( 'Private', 'Class' );
443     $privates->setColWidth( 'Private', 36, 1 );
444     $privates->setColWidth( 'Class',   37, 1 );
445
446     my $walker = sub {
447         my ( $walker, $parent, $prefix ) = @_;
448         $prefix .= $parent->getNodeValue || '';
449         $prefix .= '/' unless $prefix =~ /\/$/;
450         my $node = $parent->getNodeValue->actions;
451
452         for my $action ( keys %{$node} ) {
453             my $action_obj = $node->{$action};
454             next
455               if ( ( $action =~ /^_.*/ )
456                 && ( !$c->config->{show_internal_actions} ) );
457             $privates->addRow( "$prefix$action", $action_obj->class );
458         }
459
460         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
461     };
462
463     $walker->( $walker, $self->tree, '' );
464     $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
465       if ( @{ $privates->{tbl_rows} } );
466
467     # List all public actions
468     $_->list($c) for @{ $self->dispatch_types };
469 }
470
471 =back
472
473 =head1 AUTHOR
474
475 Sebastian Riedel, C<sri@cpan.org>
476
477 =head1 COPYRIGHT
478
479 This program is free software, you can redistribute it and/or modify it under
480 the same terms as Perl itself.
481
482 =cut
483
484 1;