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