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