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