Better error message if $c->forward fails to find action or component
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Dispatcher.pm
1 package Catalyst::Dispatcher;
2
3 use strict;
4 use base 'Class::Data::Inheritable';
5 use Catalyst::Exception;
6 use Catalyst::Utils;
7 use Text::ASCIITable;
8 use Tree::Simple;
9 use Tree::Simple::Visitor::FindByPath;
10
11 __PACKAGE__->mk_classdata($_) for qw/actions tree/;
12
13 =head1 NAME
14
15 Catalyst::Dispatcher - The Catalyst Dispatcher
16
17 =head1 SYNOPSIS
18
19 See L<Catalyst>.
20
21 =head1 DESCRIPTION
22
23 =head1 METHODS
24
25 =over 4
26
27 =item $c->detach($command)
28
29 Like C<forward> but doesn't return.
30
31 =cut
32
33 sub detach {
34     my ( $c, $command ) = @_;
35     $c->forward($command) if $command;
36     die $Catalyst::Engine::DETACH;
37 }
38
39 =item $c->dispatch
40
41 Dispatch request to actions.
42
43 =cut
44
45 sub dispatch {
46     my $c         = shift;
47     my $action    = $c->req->action;
48     my $namespace = '';
49     $namespace = ( join( '/', @{ $c->req->args } ) || '/' )
50       if $action eq 'default';
51
52     unless ($namespace) {
53         if ( my $result = $c->get_action($action) ) {
54             $namespace = Catalyst::Utils::class2prefix( $result->[0]->[0]->[0],
55                 $c->config->{case_sensitive} );
56         }
57     }
58
59     my $default = $action eq 'default' ? $namespace : undef;
60     my $results = $c->get_action( $action, $default, $default ? 1 : 0 );
61     $namespace ||= '/';
62
63     if ( @{$results} ) {
64
65         # Execute last begin
66         $c->state(1);
67         if ( my $begin = @{ $c->get_action( 'begin', $namespace, 1 ) }[-1] ) {
68             $c->execute( @{ $begin->[0] } );
69             return if scalar @{ $c->error };
70         }
71
72         # Execute the auto chain
73         my $autorun = 0;
74         for my $auto ( @{ $c->get_action( 'auto', $namespace, 1 ) } ) {
75             $autorun++;
76             $c->execute( @{ $auto->[0] } );
77             return if scalar @{ $c->error };
78             last unless $c->state;
79         }
80
81         # Execute the action or last default
82         my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
83         if ( ( my $action = $c->req->action ) && $mkay ) {
84             if ( my $result = @{ $c->get_action( $action, $default, 1 ) }[-1] )
85             {
86                 $c->execute( @{ $result->[0] } );
87             }
88         }
89
90         # Execute last end
91         if ( my $end = @{ $c->get_action( 'end', $namespace, 1 ) }[-1] ) {
92             $c->execute( @{ $end->[0] } );
93             return if scalar @{ $c->error };
94         }
95     }
96
97     else {
98         my $path  = $c->req->path;
99         my $error = $path
100           ? qq/Unknown resource "$path"/
101           : "No default action defined";
102         $c->log->error($error) if $c->debug;
103         $c->error($error);
104     }
105 }
106
107 =item $c->forward( $command [, \@arguments ] )
108
109 Forward processing to a private action or a method from a class.
110 If you define a class without method it will default to process().
111 also takes an optional arrayref containing arguments to be passed
112 to the new function. $c->req->args will be reset upon returning 
113 from the function.
114
115     $c->forward('/foo');
116     $c->forward('index');
117     $c->forward(qw/MyApp::Model::CDBI::Foo do_stuff/);
118     $c->forward('MyApp::View::TT');
119
120 =cut
121
122 sub forward {
123     my $c       = shift;
124     my $command = shift;
125
126     unless ($command) {
127         $c->log->debug('Nothing to forward to') if $c->debug;
128         return 0;
129     }
130
131     my $caller    = caller(0);
132     my $namespace = '/';
133     my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
134
135     if ( $command =~ /^\// ) {
136         $command =~ /^\/(.*)\/(\w+)$/;
137         $namespace = $1 || '/';
138         $command   = $2 || $command;
139         $command =~ s/^\///;
140     }
141
142     else {
143         $namespace =
144           Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
145           || '/';
146     }
147
148     my $results = $c->get_action( $command, $namespace );
149
150     unless ( @{$results} ) {
151         
152         unless ( $c->components->{$command} ) {
153             my $error = qq/Couldn't forward to command "$command". Invalid action or component./;
154             $c->error($error);
155             $c->log->debug($error) if $c->debug;
156             return 0;
157         }
158         
159         my $class  = $command;
160         my $method = shift || 'process';
161
162         if ( my $code = $c->components->{$class}->can($method) ) {
163             $c->actions->{reverse}->{"$code"} = "$class->$method";
164             $results = [ [ [ $class, $code ] ] ];
165         }
166
167         else {
168             my $error = qq/Couldn't forward to "$class". Does not implement "$method"/;
169             $c->error($error);
170             $c->log->debug($error)
171               if $c->debug;
172             return 0;
173         }
174
175     }
176     
177     local $c->request->{arguments} = [ @{ $arguments } ];
178
179     for my $result ( @{$results} ) {
180         $c->execute( @{ $result->[0] } );
181         return if scalar @{ $c->error };
182         last unless $c->state;
183     }
184
185     return $c->state;
186 }
187
188 =item $c->get_action( $action, $namespace, $inherit )
189
190 Get an action in a given namespace.
191
192 =cut
193
194 sub get_action {
195     my ( $c, $action, $namespace, $inherit ) = @_;
196     return [] unless $action;
197     $namespace ||= '';
198     $inherit   ||= 0;
199
200     if ($namespace) {
201         $namespace = '' if $namespace eq '/';
202         my $parent = $c->tree;
203         my @results;
204
205         if ($inherit) {
206             my $result = $c->actions->{private}->{ $parent->getUID }->{$action};
207             push @results, [$result] if $result;
208             my $visitor = Tree::Simple::Visitor::FindByPath->new;
209
210             for my $part ( split '/', $namespace ) {
211                 $visitor->setSearchPath($part);
212                 $parent->accept($visitor);
213                 my $child = $visitor->getResult;
214                 my $uid   = $child->getUID if $child;
215                 my $match = $c->actions->{private}->{$uid}->{$action} if $uid;
216                 push @results, [$match] if $match;
217                 $parent = $child if $child;
218             }
219
220         }
221
222         else {
223
224             if ($namespace) {
225                 my $visitor = Tree::Simple::Visitor::FindByPath->new;
226                 $visitor->setSearchPath( split '/', $namespace );
227                 $parent->accept($visitor);
228                 my $child = $visitor->getResult;
229                 my $uid   = $child->getUID if $child;
230                 my $match = $c->actions->{private}->{$uid}->{$action}
231                   if $uid;
232                 push @results, [$match] if $match;
233             }
234
235             else {
236                 my $result =
237                   $c->actions->{private}->{ $parent->getUID }->{$action};
238                 push @results, [$result] if $result;
239             }
240
241         }
242         return \@results;
243     }
244
245     elsif ( my $p = $c->actions->{plain}->{$action} ) { return [ [$p] ] }
246     elsif ( my $r = $c->actions->{regex}->{$action} ) { return [ [$r] ] }
247
248     else {
249
250         for my $i ( 0 .. $#{ $c->actions->{compiled} } ) {
251             my $name  = $c->actions->{compiled}->[$i]->[0];
252             my $regex = $c->actions->{compiled}->[$i]->[1];
253
254             if ( my @snippets = ( $action =~ $regex ) ) {
255                 return [ [ $c->actions->{regex}->{$name}, $name, \@snippets ] ];
256             }
257
258         }
259     }
260     return [];
261 }
262
263 =item $c->set_action( $action, $code, $namespace, $attrs )
264
265 Set an action in a given namespace.
266
267 =cut
268
269 sub set_action {
270     my ( $c, $method, $code, $namespace, $attrs ) = @_;
271
272     my $prefix =
273       Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
274       || '';
275     my %flags;
276
277     for my $attr ( @{$attrs} ) {
278         if    ( $attr =~ /^(Local|Relative)$/ )    { $flags{local}++ }
279         elsif ( $attr =~ /^(Global|Absolute)$/ )   { $flags{global}++ }
280         elsif ( $attr =~ /^Path\(\s*(.+)\s*\)$/i ) { $flags{path} = $1 }
281         elsif ( $attr =~ /^Private$/i )            { $flags{private}++ }
282         elsif ( $attr =~ /^(Regex|Regexp)\(\s*(.+)\s*\)$/i ) {
283             $flags{regex} = $2;
284         }
285     }
286
287     if ( $flags{private} && ( keys %flags > 1 ) ) {
288         $c->log->debug( 'Bad action definition "'
289               . join( ' ', @{$attrs} )
290               . qq/" for "$namespace->$method"/ )
291           if $c->debug;
292         return;
293     }
294     return unless keys %flags;
295
296     my $parent  = $c->tree;
297     my $visitor = Tree::Simple::Visitor::FindByPath->new;
298
299     for my $part ( split '/', $prefix ) {
300         $visitor->setSearchPath($part);
301         $parent->accept($visitor);
302         my $child = $visitor->getResult;
303
304         unless ($child) {
305             $child = $parent->addChild( Tree::Simple->new($part) );
306             $visitor->setSearchPath($part);
307             $parent->accept($visitor);
308             $child = $visitor->getResult;
309         }
310
311         $parent = $child;
312     }
313
314     my $uid = $parent->getUID;
315     $c->actions->{private}->{$uid}->{$method} = [ $namespace, $code ];
316     my $forward = $prefix ? "$prefix/$method" : $method;
317
318     if ( $flags{path} ) {
319         $flags{path} =~ s/^\w+//;
320         $flags{path} =~ s/\w+$//;
321         if ( $flags{path} =~ /^'(.*)'$/ ) { $flags{path} = $1 }
322         if ( $flags{path} =~ /^"(.*)"$/ ) { $flags{path} = $1 }
323     }
324
325     if ( $flags{regex} ) {
326         $flags{regex} =~ s/^\w+//;
327         $flags{regex} =~ s/\w+$//;
328         if ( $flags{regex} =~ /^'(.*)'$/ ) { $flags{regex} = $1 }
329         if ( $flags{regex} =~ /^"(.*)"$/ ) { $flags{regex} = $1 }
330     }
331
332     my $reverse = $prefix ? "$prefix/$method" : $method;
333
334     if ( $flags{local} || $flags{global} || $flags{path} ) {
335         my $path     = $flags{path} || $method;
336         my $absolute = 0;
337
338         if ( $path =~ /^\/(.+)/ ) {
339             $path     = $1;
340             $absolute = 1;
341         }
342
343         $absolute = 1 if $flags{global};
344         my $name = $absolute ? $path : $prefix ? "$prefix/$path" : $path;
345         $c->actions->{plain}->{$name} = [ $namespace, $code ];
346     }
347
348     if ( my $regex = $flags{regex} ) {
349         push @{ $c->actions->{compiled} }, [ $regex, qr#$regex# ];
350         $c->actions->{regex}->{$regex} = [ $namespace, $code ];
351     }
352
353     $c->actions->{reverse}->{"$code"} = $reverse;
354 }
355
356 =item $class->setup_actions($component)
357
358 Setup actions for a component.
359
360 =cut
361
362 sub setup_actions {
363     my $self = shift;
364
365     # These are the core structures
366     $self->actions(
367         {
368             plain    => {},
369             private  => {},
370             regex    => {},
371             compiled => [],
372             reverse  => {}
373         }
374     );
375
376     # We use a tree
377     $self->tree( Tree::Simple->new( 0, Tree::Simple->ROOT ) );
378
379     for my $comp ( keys %{ $self->components } ) {
380
381         # We only setup components that inherit from Catalyst::Base
382         next unless $comp->isa('Catalyst::Base');
383
384         for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
385             my ( $code, $attrs ) = @{$action};
386             my $name = '';
387             no strict 'refs';
388             my @cache = ( $comp, @{"$comp\::ISA"} );
389             my %namespaces;
390
391             while ( my $namespace = shift @cache ) {
392                 $namespaces{$namespace}++;
393                 for my $isa ( @{"$comp\::ISA"} ) {
394                     next if $namespaces{$isa};
395                     push @cache, $isa;
396                     $namespaces{$isa}++;
397                 }
398             }
399
400             for my $namespace ( keys %namespaces ) {
401
402                 for my $sym ( values %{ $namespace . '::' } ) {
403
404                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
405
406                         $name = *{$sym}{NAME};
407                         $self->set_action( $name, $code, $comp, $attrs );
408                         last;
409                     }
410
411                 }
412
413             }
414
415         }
416
417     }
418
419     return unless $self->debug;
420
421     my $actions  = $self->actions;
422     my $privates = Text::ASCIITable->new;
423     $privates->setCols( 'Private', 'Class' );
424     $privates->setColWidth( 'Private', 36, 1 );
425     $privates->setColWidth( 'Class',   37, 1 );
426
427     my $walker = sub {
428         my ( $walker, $parent, $prefix ) = @_;
429         $prefix .= $parent->getNodeValue || '';
430         $prefix .= '/' unless $prefix =~ /\/$/;
431         my $uid = $parent->getUID;
432
433         for my $action ( keys %{ $actions->{private}->{$uid} } ) {
434             my ( $class, $code ) = @{ $actions->{private}->{$uid}->{$action} };
435             $privates->addRow( "$prefix$action", $class );
436         }
437
438         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
439     };
440
441     $walker->( $walker, $self->tree, '' );
442     $self->log->debug( "Loaded private actions:\n" . $privates->draw )
443       if ( @{ $privates->{tbl_rows} } );
444
445     my $publics = Text::ASCIITable->new;
446     $publics->setCols( 'Public', 'Private' );
447     $publics->setColWidth( 'Public',  36, 1 );
448     $publics->setColWidth( 'Private', 37, 1 );
449
450     for my $plain ( sort keys %{ $actions->{plain} } ) {
451         my ( $class, $code ) = @{ $actions->{plain}->{$plain} };
452         my $reverse = $self->actions->{reverse}->{$code};
453         $reverse = $reverse ? "/$reverse" : $code;
454         $publics->addRow( "/$plain", $reverse );
455     }
456
457     $self->log->debug( "Loaded public actions:\n" . $publics->draw )
458       if ( @{ $publics->{tbl_rows} } );
459
460     my $regexes = Text::ASCIITable->new;
461     $regexes->setCols( 'Regex', 'Private' );
462     $regexes->setColWidth( 'Regex',   36, 1 );
463     $regexes->setColWidth( 'Private', 37, 1 );
464
465     for my $regex ( sort keys %{ $actions->{regex} } ) {
466         my ( $class, $code ) = @{ $actions->{regex}->{$regex} };
467         my $reverse = $self->actions->{reverse}->{$code};
468         $reverse = $reverse ? "/$reverse" : $code;
469         $regexes->addRow( $regex, $reverse );
470     }
471
472     $self->log->debug( "Loaded regex actions:\n" . $regexes->draw )
473       if ( @{ $regexes->{tbl_rows} } );
474 }
475
476 =back
477
478 =head1 AUTHOR
479
480 Sebastian Riedel, C<sri@cpan.org>
481
482 =head1 COPYRIGHT
483
484 This program is free software, you can redistribute it and/or modify it under
485 the same terms as Perl itself.
486
487 =cut
488
489 1;