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