refactored $c->forward
[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         my $class = $command || '';
152         my $path = $class . '.pm';
153         $path =~ s/::/\//g;
154
155         unless ( $INC{$path} ) {
156             my $error =
157               qq/Couldn't forward to "$class". Invalid or not loaded./;
158             $c->error($error);
159             $c->log->debug($error) if $c->debug;
160             return 0;
161         }
162
163         unless ( UNIVERSAL::isa( $class, 'Catalyst::Base' ) ) {
164             my $error =
165               qq/Can't forward to "$class". Class is not a Catalyst component./;
166             $c->error($error);
167             $c->log->debug($error) if $c->debug;
168             return 0;
169         }
170
171         my $method = shift || 'process';
172
173         if ( my $code = $class->can($method) ) {
174             $c->actions->{reverse}->{"$code"} = "$class->$method";
175             $results = [ [ [ $class, $code ] ] ];
176         }
177
178         else {
179             my $error =
180               qq/Couldn't forward to "$class". Does not implement "$method"/;
181             $c->error($error);
182             $c->log->debug($error)
183               if $c->debug;
184             return 0;
185         }
186
187     }
188     
189     local $c->request->{arguments} = $arguments;
190
191     for my $result ( @{$results} ) {
192         $c->execute( @{ $result->[0] } );
193         return if scalar @{ $c->error };
194         last unless $c->state;
195     }
196
197     return $c->state;
198 }
199
200 =item $c->get_action( $action, $namespace, $inherit )
201
202 Get an action in a given namespace.
203
204 =cut
205
206 sub get_action {
207     my ( $c, $action, $namespace, $inherit ) = @_;
208     return [] unless $action;
209     $namespace ||= '';
210     $inherit   ||= 0;
211
212     if ($namespace) {
213         $namespace = '' if $namespace eq '/';
214         my $parent = $c->tree;
215         my @results;
216
217         if ($inherit) {
218             my $result = $c->actions->{private}->{ $parent->getUID }->{$action};
219             push @results, [$result] if $result;
220             my $visitor = Tree::Simple::Visitor::FindByPath->new;
221
222             for my $part ( split '/', $namespace ) {
223                 $visitor->setSearchPath($part);
224                 $parent->accept($visitor);
225                 my $child = $visitor->getResult;
226                 my $uid   = $child->getUID if $child;
227                 my $match = $c->actions->{private}->{$uid}->{$action} if $uid;
228                 push @results, [$match] if $match;
229                 $parent = $child if $child;
230             }
231
232         }
233
234         else {
235
236             if ($namespace) {
237                 my $visitor = Tree::Simple::Visitor::FindByPath->new;
238                 $visitor->setSearchPath( split '/', $namespace );
239                 $parent->accept($visitor);
240                 my $child = $visitor->getResult;
241                 my $uid   = $child->getUID if $child;
242                 my $match = $c->actions->{private}->{$uid}->{$action}
243                   if $uid;
244                 push @results, [$match] if $match;
245             }
246
247             else {
248                 my $result =
249                   $c->actions->{private}->{ $parent->getUID }->{$action};
250                 push @results, [$result] if $result;
251             }
252
253         }
254         return \@results;
255     }
256
257     elsif ( my $p = $c->actions->{plain}->{$action} ) { return [ [$p] ] }
258     elsif ( my $r = $c->actions->{regex}->{$action} ) { return [ [$r] ] }
259
260     else {
261
262         for my $i ( 0 .. $#{ $c->actions->{compiled} } ) {
263             my $name  = $c->actions->{compiled}->[$i]->[0];
264             my $regex = $c->actions->{compiled}->[$i]->[1];
265
266             if ( my @snippets = ( $action =~ $regex ) ) {
267                 return [ [ $c->actions->{regex}->{$name}, $name, \@snippets ] ];
268             }
269
270         }
271     }
272     return [];
273 }
274
275 =item $c->set_action( $action, $code, $namespace, $attrs )
276
277 Set an action in a given namespace.
278
279 =cut
280
281 sub set_action {
282     my ( $c, $method, $code, $namespace, $attrs ) = @_;
283
284     my $prefix =
285       Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
286       || '';
287     my %flags;
288
289     for my $attr ( @{$attrs} ) {
290         if    ( $attr =~ /^(Local|Relative)$/ )    { $flags{local}++ }
291         elsif ( $attr =~ /^(Global|Absolute)$/ )   { $flags{global}++ }
292         elsif ( $attr =~ /^Path\(\s*(.+)\s*\)$/i ) { $flags{path} = $1 }
293         elsif ( $attr =~ /^Private$/i )            { $flags{private}++ }
294         elsif ( $attr =~ /^(Regex|Regexp)\(\s*(.+)\s*\)$/i ) {
295             $flags{regex} = $2;
296         }
297     }
298
299     if ( $flags{private} && ( keys %flags > 1 ) ) {
300         $c->log->debug( 'Bad action definition "'
301               . join( ' ', @{$attrs} )
302               . qq/" for "$namespace->$method"/ )
303           if $c->debug;
304         return;
305     }
306     return unless keys %flags;
307
308     my $parent  = $c->tree;
309     my $visitor = Tree::Simple::Visitor::FindByPath->new;
310
311     for my $part ( split '/', $prefix ) {
312         $visitor->setSearchPath($part);
313         $parent->accept($visitor);
314         my $child = $visitor->getResult;
315
316         unless ($child) {
317             $child = $parent->addChild( Tree::Simple->new($part) );
318             $visitor->setSearchPath($part);
319             $parent->accept($visitor);
320             $child = $visitor->getResult;
321         }
322
323         $parent = $child;
324     }
325
326     my $uid = $parent->getUID;
327     $c->actions->{private}->{$uid}->{$method} = [ $namespace, $code ];
328     my $forward = $prefix ? "$prefix/$method" : $method;
329
330     if ( $flags{path} ) {
331         $flags{path} =~ s/^\w+//;
332         $flags{path} =~ s/\w+$//;
333         if ( $flags{path} =~ /^'(.*)'$/ ) { $flags{path} = $1 }
334         if ( $flags{path} =~ /^"(.*)"$/ ) { $flags{path} = $1 }
335     }
336
337     if ( $flags{regex} ) {
338         $flags{regex} =~ s/^\w+//;
339         $flags{regex} =~ s/\w+$//;
340         if ( $flags{regex} =~ /^'(.*)'$/ ) { $flags{regex} = $1 }
341         if ( $flags{regex} =~ /^"(.*)"$/ ) { $flags{regex} = $1 }
342     }
343
344     my $reverse = $prefix ? "$prefix/$method" : $method;
345
346     if ( $flags{local} || $flags{global} || $flags{path} ) {
347         my $path     = $flags{path} || $method;
348         my $absolute = 0;
349
350         if ( $path =~ /^\/(.+)/ ) {
351             $path     = $1;
352             $absolute = 1;
353         }
354
355         $absolute = 1 if $flags{global};
356         my $name = $absolute ? $path : $prefix ? "$prefix/$path" : $path;
357         $c->actions->{plain}->{$name} = [ $namespace, $code ];
358     }
359
360     if ( my $regex = $flags{regex} ) {
361         push @{ $c->actions->{compiled} }, [ $regex, qr#$regex# ];
362         $c->actions->{regex}->{$regex} = [ $namespace, $code ];
363     }
364
365     $c->actions->{reverse}->{"$code"} = $reverse;
366 }
367
368 =item $class->setup_actions($component)
369
370 Setup actions for a component.
371
372 =cut
373
374 sub setup_actions {
375     my $self = shift;
376
377     # These are the core structures
378     $self->actions(
379         {
380             plain    => {},
381             private  => {},
382             regex    => {},
383             compiled => [],
384             reverse  => {}
385         }
386     );
387
388     # We use a tree
389     $self->tree( Tree::Simple->new( 0, Tree::Simple->ROOT ) );
390
391     for my $comp ( keys %{ $self->components } ) {
392
393         # We only setup components that inherit from Catalyst::Base
394         next unless $comp->isa('Catalyst::Base');
395
396         for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
397             my ( $code, $attrs ) = @{$action};
398             my $name = '';
399             no strict 'refs';
400             my @cache = ( $comp, @{"$comp\::ISA"} );
401             my %namespaces;
402
403             while ( my $namespace = shift @cache ) {
404                 $namespaces{$namespace}++;
405                 for my $isa ( @{"$comp\::ISA"} ) {
406                     next if $namespaces{$isa};
407                     push @cache, $isa;
408                     $namespaces{$isa}++;
409                 }
410             }
411
412             for my $namespace ( keys %namespaces ) {
413
414                 for my $sym ( values %{ $namespace . '::' } ) {
415
416                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
417
418                         $name = *{$sym}{NAME};
419                         $self->set_action( $name, $code, $comp, $attrs );
420                         last;
421                     }
422
423                 }
424
425             }
426
427         }
428
429     }
430
431     return unless $self->debug;
432
433     my $actions  = $self->actions;
434     my $privates = Text::ASCIITable->new;
435     $privates->setCols( 'Private', 'Class' );
436     $privates->setColWidth( 'Private', 36, 1 );
437     $privates->setColWidth( 'Class',   37, 1 );
438
439     my $walker = sub {
440         my ( $walker, $parent, $prefix ) = @_;
441         $prefix .= $parent->getNodeValue || '';
442         $prefix .= '/' unless $prefix =~ /\/$/;
443         my $uid = $parent->getUID;
444
445         for my $action ( keys %{ $actions->{private}->{$uid} } ) {
446             my ( $class, $code ) = @{ $actions->{private}->{$uid}->{$action} };
447             $privates->addRow( "$prefix$action", $class );
448         }
449
450         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
451     };
452
453     $walker->( $walker, $self->tree, '' );
454     $self->log->debug( "Loaded private actions:\n" . $privates->draw )
455       if ( @{ $privates->{tbl_rows} } );
456
457     my $publics = Text::ASCIITable->new;
458     $publics->setCols( 'Public', 'Private' );
459     $publics->setColWidth( 'Public',  36, 1 );
460     $publics->setColWidth( 'Private', 37, 1 );
461
462     for my $plain ( sort keys %{ $actions->{plain} } ) {
463         my ( $class, $code ) = @{ $actions->{plain}->{$plain} };
464         my $reverse = $self->actions->{reverse}->{$code};
465         $reverse = $reverse ? "/$reverse" : $code;
466         $publics->addRow( "/$plain", $reverse );
467     }
468
469     $self->log->debug( "Loaded public actions:\n" . $publics->draw )
470       if ( @{ $publics->{tbl_rows} } );
471
472     my $regexes = Text::ASCIITable->new;
473     $regexes->setCols( 'Regex', 'Private' );
474     $regexes->setColWidth( 'Regex',   36, 1 );
475     $regexes->setColWidth( 'Private', 37, 1 );
476
477     for my $regex ( sort keys %{ $actions->{regex} } ) {
478         my ( $class, $code ) = @{ $actions->{regex}->{$regex} };
479         my $reverse = $self->actions->{reverse}->{$code};
480         $reverse = $reverse ? "/$reverse" : $code;
481         $regexes->addRow( $regex, $reverse );
482     }
483
484     $self->log->debug( "Loaded regex actions:\n" . $regexes->draw )
485       if ( @{ $regexes->{tbl_rows} } );
486 }
487
488 =back
489
490 =head1 AUTHOR
491
492 Sebastian Riedel, C<sri@cpan.org>
493
494 =head1 COPYRIGHT
495
496 This program is free software, you can redistribute it and/or modify it under
497 the same terms as Perl itself.
498
499 =cut
500
501 1;