Fixed default action in appclass
[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::Path;
10 use Catalyst::DispatchType::Regex;
11 use Catalyst::DispatchType::Default;
12 use Text::ASCIITable;
13 use Tree::Simple;
14 use Tree::Simple::Visitor::FindByPath;
15
16 # Stringify to class
17 use overload '""' => sub { return ref shift }, fallback => 1;
18
19 __PACKAGE__->mk_accessors(qw/actions tree dispatch_types/);
20
21 =head1 NAME
22
23 Catalyst::Dispatcher - The Catalyst Dispatcher
24
25 =head1 SYNOPSIS
26
27 See L<Catalyst>.
28
29 =head1 DESCRIPTION
30
31 =head1 METHODS
32
33 =over 4
34
35 =item $self->detach( $c, $command [, \@arguments ] )
36
37 =cut
38
39 sub detach {
40     my ( $self, $c, $command, @args ) = @_;
41     $c->forward( $command, @args ) if $command;
42     die $Catalyst::DETACH;
43 }
44
45 =item $self->dispatch($c)
46
47 =cut
48
49 sub dispatch {
50     my ( $self, $c ) = @_;
51
52     if ( $c->action ) {
53
54         my @containers = $self->get_containers( $c->namespace );
55         my %actions;
56         foreach my $name (qw/begin auto end/) {
57
58             # Go down the container list representing each part of the
59             # current namespace inheritance tree, grabbing the actions hash
60             # of the ActionContainer object and looking for actions of the
61             # appropriate name registered to the namespace
62
63             $actions{$name} = [
64                 map    { $_->{$name} }
65                   grep { exists $_->{$name} }
66                   map  { $_->actions } @containers
67             ];
68         }
69
70         # Errors break the normal flow and the end action is instantly run
71         my $error = 0;
72
73         # Execute last begin
74         $c->state(1);
75         if ( my $begin = @{ $actions{begin} }[-1] ) {
76             $begin->execute($c);
77             $error++ if scalar @{ $c->error };
78         }
79
80         # Execute the auto chain
81         my $autorun = 0;
82         for my $auto ( @{ $actions{auto} } ) {
83             last if $error;
84             $autorun++;
85             $auto->execute($c);
86             $error++ if scalar @{ $c->error };
87             last unless $c->state;
88         }
89
90         # Execute the action or last default
91         my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
92         if ($mkay) {
93             unless ($error) {
94                 $c->action->execute($c);
95                 $error++ if scalar @{ $c->error };
96             }
97         }
98
99         # Execute last end
100         if ( my $end = @{ $actions{end} }[-1] ) {
101             $end->execute($c);
102         }
103     }
104
105     else {
106         my $path  = $c->req->path;
107         my $error = $path
108           ? qq/Unknown resource "$path"/
109           : "No default action defined";
110         $c->log->error($error) if $c->debug;
111         $c->error($error);
112     }
113 }
114
115 =item $self->forward( $c, $command [, \@arguments ] )
116
117 =cut
118
119 sub forward {
120     my $self    = shift;
121     my $c       = shift;
122     my $command = shift;
123
124     unless ($command) {
125         $c->log->debug('Nothing to forward to') if $c->debug;
126         return 0;
127     }
128
129     # Relative forwards from detach
130     my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
131       && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
132
133     my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
134
135     my $results = [];
136
137     my $command_copy = $command;
138
139     unless ( $command_copy =~ s/^\/// ) {
140         my $namespace =
141           Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
142           || '';
143         $command_copy = "${namespace}/${command}";
144     }
145
146     unless ( $command_copy =~ /\// ) {
147         $results = $c->get_action( $command_copy, '/' );
148     }
149     else {
150         my @extra_args;
151       DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
152             my $tail = $2;
153             $results = $c->get_action( $tail, $1 );
154             if ( @{$results} ) {
155                 $command = $tail;
156                 push( @{$arguments}, @extra_args );
157                 last DESCEND;
158             }
159             unshift( @extra_args, $tail );
160         }
161     }
162
163     unless ( @{$results} ) {
164
165         unless ( $c->components->{$command} ) {
166             my $error =
167 qq/Couldn't forward to command "$command". Invalid action or component./;
168             $c->error($error);
169             $c->log->debug($error) if $c->debug;
170             return 0;
171         }
172
173         my $class  = $command;
174         my $method = shift || 'process';
175
176         if ( my $code = $c->components->{$class}->can($method) ) {
177             my $action = Catalyst::Action->new(
178                 {
179                     name      => $method,
180                     code      => $code,
181                     reverse   => "$class->$method",
182                     namespace => $class,
183                     prefix    => $class,
184                 }
185             );
186             $results = [ [$action] ];
187         }
188
189         else {
190             my $error =
191               qq/Couldn't forward to "$class". Does not implement "$method"/;
192             $c->error($error);
193             $c->log->debug($error)
194               if $c->debug;
195             return 0;
196         }
197
198     }
199
200     local $c->request->{arguments} = [ @{$arguments} ];
201
202     for my $result ( @{$results} ) {
203         $result->[0]->execute($c);
204         return if scalar @{ $c->error };
205         last unless $c->state;
206     }
207
208     return $c->state;
209 }
210
211 =item $self->prepare_action($c)
212
213 =cut
214
215 sub prepare_action {
216     my ( $self, $c ) = @_;
217     my $path = $c->req->path;
218     my @path = split /\//, $c->req->path;
219     $c->req->args( \my @args );
220
221     push( @path, '/' ) unless @path;    # Root action
222
223   DESCEND: while (@path) {
224         $path = join '/', @path;
225
226         $path = '' if $path eq '/';     # Root action
227
228         # Check out dispatch types to see if any will handle the path at
229         # this level
230
231         foreach my $type ( @{ $self->dispatch_types } ) {
232             last DESCEND if $type->prepare_action( $c, $path );
233         }
234
235         # If not, move the last part path to args
236
237         unshift @args, pop @path;
238     }
239
240     $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
241       if ( $c->debug && @args );
242 }
243
244 =item $self->get_action( $c, $action, $namespace, $inherit )
245
246 =cut
247
248 sub get_action {
249     my ( $self, $c, $action, $namespace, $inherit ) = @_;
250     return [] unless $action;
251     $namespace ||= '/';
252     $inherit   ||= 0;
253
254     my @match = $self->get_containers($namespace);
255
256     my @results;
257
258     foreach my $child ( $inherit ? @match : $match[-1] ) {
259         my $node = $child->actions;
260         push( @results, [ $node->{$action} ] ) if defined $node->{$action};
261     }
262     return \@results;
263 }
264
265 =item $self->get_containers( $namespace )
266
267 =cut
268
269 sub get_containers {
270     my ( $self, $namespace ) = @_;
271
272     # If the namespace is / just return the root ActionContainer
273
274     return ( $self->tree->getNodeValue )
275       if ( !$namespace || ( $namespace eq '/' ) );
276
277     # Use a visitor to recurse down the tree finding the ActionContainers
278     # for each namespace in the chain.
279
280     my $visitor = Tree::Simple::Visitor::FindByPath->new;
281     my @path = split( '/', $namespace );
282     $visitor->setSearchPath(@path);
283     $self->tree->accept($visitor);
284
285     my @match = $visitor->getResults;
286     @match = ( $self->tree ) unless @match;
287
288     if ( !defined $visitor->getResult ) {
289
290         # If we don't manage to match, the visitor doesn't return the last
291         # node is matched, so foo/bar/baz would only find the 'foo' node,
292         # not the foo and foo/bar nodes as it should. This does another
293         # single-level search to see if that's the case, and the 'last unless'
294         # should catch any failures - or short-circuit this if this *is* a
295         # bug in the visitor and gets fixed.
296
297         my $extra = $path[ ( scalar @match ) - 1 ];
298         last unless $extra;
299         $visitor->setSearchPath($extra);
300         $match[-1]->accept($visitor);
301         push( @match, $visitor->getResult ) if defined $visitor->getResult;
302     }
303
304     return map { $_->getNodeValue } @match;
305 }
306
307 =item $self->set_action( $c, $action, $code, $namespace, $attrs )
308
309 =cut
310
311 sub set_action {
312     my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
313
314     my $prefix =
315       Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
316       || '';
317     my %attributes;
318
319     for my $attr ( @{$attrs} ) {
320
321         # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
322
323         if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
324             if ( defined $value ) {
325                 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
326             }
327             push( @{ $attributes{$key} }, $value );
328         }
329     }
330
331     if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
332         $c->log->debug( 'Bad action definition "'
333               . join( ' ', @{$attrs} )
334               . qq/" for "$namespace->$method"/ )
335           if $c->debug;
336         return;
337     }
338     return unless keys %attributes;
339
340     my $parent  = $self->tree;
341     my $visitor = Tree::Simple::Visitor::FindByPath->new;
342
343     if ($prefix) {
344         for my $part ( split '/', $prefix ) {
345             $visitor->setSearchPath($part);
346             $parent->accept($visitor);
347             my $child = $visitor->getResult;
348
349             unless ($child) {
350
351                 # Create a new tree node and an ActionContainer to form
352                 # its value.
353
354                 my $container =
355                   Catalyst::ActionContainer->new(
356                     { part => $part, actions => {} } );
357                 $child = $parent->addChild( Tree::Simple->new($container) );
358                 $visitor->setSearchPath($part);
359                 $parent->accept($visitor);
360                 $child = $visitor->getResult;
361             }
362
363             $parent = $child;
364         }
365     }
366
367     my $reverse = $prefix ? "$prefix/$method" : $method;
368
369     my $action = Catalyst::Action->new(
370         {
371             name       => $method,
372             code       => $code,
373             reverse    => $reverse,
374             namespace  => $namespace,
375             prefix     => $prefix,
376             attributes => \%attributes,
377         }
378     );
379
380     # Set the method value
381     $parent->getNodeValue->actions->{$method} = $action;
382
383     # Pass the action to our dispatch types so they can register it if reqd.
384     foreach my $type ( @{ $self->dispatch_types } ) {
385         $type->register_action( $c, $action );
386     }
387 }
388
389 =item $self->setup_actions( $class, $component )
390
391 =cut
392
393 sub setup_actions {
394     my ( $self, $class ) = @_;
395
396     # These are the core structures
397     $self->actions(
398         {
399             plain    => {},
400             private  => {},
401             regex    => {},
402             compiled => []
403         }
404     );
405
406     $self->dispatch_types(
407         [ map { "Catalyst::DispatchType::$_"->new } qw/Path Regex Default/ ] );
408
409     # We use a tree
410     my $container =
411       Catalyst::ActionContainer->new( { part => '/', actions => {} } );
412     $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
413
414     for my $comp ( keys %{ $class->components } ) {
415
416         # We only setup components that inherit from Catalyst::Base
417         next unless $comp->isa('Catalyst::Base');
418
419         for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
420             my ( $code, $attrs ) = @{$action};
421             my $name = '';
422             no strict 'refs';
423             my @cache = ( $comp, @{"$comp\::ISA"} );
424             my %namespaces;
425
426             while ( my $namespace = shift @cache ) {
427                 $namespaces{$namespace}++;
428                 for my $isa ( @{"$comp\::ISA"} ) {
429                     next if $namespaces{$isa};
430                     push @cache, $isa;
431                     $namespaces{$isa}++;
432                 }
433             }
434
435             for my $namespace ( keys %namespaces ) {
436
437                 for my $sym ( values %{ $namespace . '::' } ) {
438
439                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
440
441                         $name = *{$sym}{NAME};
442                         $class->set_action( $name, $code, $comp, $attrs );
443                         last;
444                     }
445
446                 }
447
448             }
449
450         }
451
452     }
453
454     return unless $class->debug;
455
456     my $actions  = $self->actions;
457     my $privates = Text::ASCIITable->new;
458     $privates->setCols( 'Private', 'Class' );
459     $privates->setColWidth( 'Private', 36, 1 );
460     $privates->setColWidth( 'Class',   37, 1 );
461
462     my $walker = sub {
463         my ( $walker, $parent, $prefix ) = @_;
464         $prefix .= $parent->getNodeValue || '';
465         $prefix .= '/' unless $prefix =~ /\/$/;
466         my $node = $parent->getNodeValue->actions;
467
468         for my $action ( keys %{$node} ) {
469             my $action_obj = $node->{$action};
470             $privates->addRow( "$prefix$action", $action_obj->namespace );
471         }
472
473         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
474     };
475
476     $walker->( $walker, $self->tree, '' );
477     $class->log->debug( "Loaded private actions:\n" . $privates->draw )
478       if ( @{ $privates->{tbl_rows} } );
479
480     my $publics = Text::ASCIITable->new;
481     $publics->setCols( 'Public', 'Private' );
482     $publics->setColWidth( 'Public',  36, 1 );
483     $publics->setColWidth( 'Private', 37, 1 );
484
485     for my $plain ( sort keys %{ $actions->{plain} } ) {
486         my $action = $actions->{plain}->{$plain};
487         $publics->addRow( "/$plain", "/$action" );
488     }
489
490     $class->log->debug( "Loaded public actions:\n" . $publics->draw )
491       if ( @{ $publics->{tbl_rows} } );
492
493     my $regexes = Text::ASCIITable->new;
494     $regexes->setCols( 'Regex', 'Private' );
495     $regexes->setColWidth( 'Regex',   36, 1 );
496     $regexes->setColWidth( 'Private', 37, 1 );
497
498     for my $regex ( sort keys %{ $actions->{regex} } ) {
499         my $action = $actions->{regex}->{$regex};
500         $regexes->addRow( $regex, "/$action" );
501     }
502
503     $class->log->debug( "Loaded regex actions:\n" . $regexes->draw )
504       if ( @{ $regexes->{tbl_rows} } );
505 }
506
507 =back
508
509 =head1 AUTHOR
510
511 Sebastian Riedel, C<sri@cpan.org>
512
513 =head1 COPYRIGHT
514
515 This program is free software, you can redistribute it and/or modify it under
516 the same terms as Perl itself.
517
518 =cut
519
520 1;