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