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