minor improvement.
[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 = 0;
69         for my $auto ( @{ $c->get_action( 'auto', $namespace ) } ) {
70             $c->execute( @{ $auto->[0] } );
71             return if scalar @{ $c->error };
72             last unless $c->state;
73             $auto++;
74         }
75
76         # Execute the action or last default
77         my $mkay = $auto ? $c->state ? 1 : 0 : 1;
78         if ( ( my $action = $c->req->action ) && $mkay ) {
79             if ( my $result = @{ $c->get_action( $action, $default ) }[-1] ) {
80                 $c->execute( @{ $result->[0] } );
81             }
82         }
83
84         # Execute last end
85         if ( my $end = @{ $c->get_action( 'end', $namespace ) }[-1] ) {
86             $c->execute( @{ $end->[0] } );
87             return if scalar @{ $c->error };
88         }
89     }
90
91     else {
92         my $path  = $c->req->path;
93         my $error = $path
94           ? qq/Unknown resource "$path"/
95           : "No default action defined";
96         $c->log->error($error) if $c->debug;
97         $c->error($error);
98     }
99 }
100
101 =item $c->forward($command)
102
103 Forward processing to a private action or a method from a class.
104 If you define a class without method it will default to process().
105
106     $c->forward('/foo');
107     $c->forward('index');
108     $c->forward(qw/MyApp::Model::CDBI::Foo do_stuff/);
109     $c->forward('MyApp::View::TT');
110
111 =cut
112
113 sub forward {
114     my $c       = shift;
115     my $command = shift;
116
117     unless ($command) {
118         $c->log->debug('Nothing to forward to') if $c->debug;
119         return 0;
120     }
121
122     my $caller    = caller(0);
123     my $namespace = '/';
124
125     if ( $command =~ /^\// ) {
126         $command =~ /^\/(.*)\/(\w+)$/;
127         $namespace = $1 || '/';
128         $command   = $2 || $command;
129         $command =~ s/^\///;
130     }
131
132     else { $namespace = Catalyst::Utils::class2prefix($caller) || '/' }
133
134     my $results = $c->get_action( $command, $namespace );
135
136     unless ( @{$results} ) {
137         my $class = $command || '';
138
139         if ( $class =~ /[^\w\:]/ ) {
140             my $error = qq/"$class" is an invalid Class name/;
141             $c->error($error);
142             $c->log->debug($error) if $c->debug;
143             return 0;
144         }
145
146         my $method = shift || 'process';
147
148         require $class;
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". Does not implement "$method"/;
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 ( my @snippets = ( $action =~ $regex ) ) {
240                 return [ [ $c->actions->{regex}->{$name}, $name, \@snippets ] ];
241             }
242
243         }
244     }
245     return [];
246 }
247
248 =item $c->set_action( $action, $code, $namespace, $attrs )
249
250 Set an action in a given namespace.
251
252 =cut
253
254 sub set_action {
255     my ( $c, $method, $code, $namespace, $attrs ) = @_;
256
257     my $prefix = Catalyst::Utils::class2prefix($namespace) || '';
258     my %flags;
259
260     for my $attr ( @{$attrs} ) {
261         if    ( $attr =~ /^(Local|Relative)$/ )        { $flags{local}++ }
262         elsif ( $attr =~ /^(Global|Absolute)$/ )       { $flags{global}++ }
263         elsif ( $attr =~ /^Path\((.+)\)$/i )           { $flags{path} = $1 }
264         elsif ( $attr =~ /^Private$/i )                { $flags{private}++ }
265         elsif ( $attr =~ /^(Regex|Regexp)\((.+)\)$/i ) { $flags{regex} = $2 }
266     }
267
268     if ( $flags{private} && ( keys %flags > 1 ) ) {
269         $c->log->debug( 'Bad action definition "'
270               . join( ' ', @{$attrs} )
271               . qq/" for "$namespace->$method"/ )
272           if $c->debug;
273         return;
274     }
275     return unless keys %flags;
276
277     my $parent  = $c->tree;
278     my $visitor = Tree::Simple::Visitor::FindByPath->new;
279
280     for my $part ( split '/', $prefix ) {
281         $visitor->setSearchPath($part);
282         $parent->accept($visitor);
283         my $child = $visitor->getResult;
284
285         unless ($child) {
286             $child = $parent->addChild( Tree::Simple->new($part) );
287             $visitor->setSearchPath($part);
288             $parent->accept($visitor);
289             $child = $visitor->getResult;
290         }
291
292         $parent = $child;
293     }
294
295     my $uid = $parent->getUID;
296     $c->actions->{private}->{$uid}->{$method} = [ $namespace, $code ];
297     my $forward = $prefix ? "$prefix/$method" : $method;
298
299     if ( $flags{path} ) {
300         $flags{path} =~ s/^\w+//;
301         $flags{path} =~ s/\w+$//;
302         if ( $flags{path} =~ /^'(.*)'$/ ) { $flags{path} = $1 }
303         if ( $flags{path} =~ /^"(.*)"$/ ) { $flags{path} = $1 }
304     }
305
306     if ( $flags{regex} ) {
307         $flags{regex} =~ s/^\w+//;
308         $flags{regex} =~ s/\w+$//;
309         if ( $flags{regex} =~ /^'(.*)'$/ ) { $flags{regex} = $1 }
310         if ( $flags{regex} =~ /^"(.*)"$/ ) { $flags{regex} = $1 }
311     }
312
313     my $reverse = $prefix ? "$prefix/$method" : $method;
314
315     if ( $flags{local} || $flags{global} || $flags{path} ) {
316         my $path     = $flags{path} || $method;
317         my $absolute = 0;
318
319         if ( $path =~ /^\/(.+)/ ) {
320             $path     = $1;
321             $absolute = 1;
322         }
323
324         $absolute = 1 if $flags{global};
325         my $name = $absolute ? $path : $prefix ? "$prefix/$path" : $path;
326         $c->actions->{plain}->{$name} = [ $namespace, $code ];
327     }
328
329     if ( my $regex = $flags{regex} ) {
330         push @{ $c->actions->{compiled} }, [ $regex, qr#$regex# ];
331         $c->actions->{regex}->{$regex} = [ $namespace, $code ];
332     }
333
334     $c->actions->{reverse}->{"$code"} = $reverse;
335 }
336
337 =item $class->setup_actions($component)
338
339 Setup actions for a component.
340
341 =cut
342
343 sub setup_actions {
344     my ( $self, $comps ) = @_;
345
346     for my $comp (@$comps) {
347         $comp = ref $comp || $comp;
348
349         for my $action ( @{ $comp->_cache } ) {
350             my ( $code, $attrs ) = @{$action};
351             my $name = '';
352             no strict 'refs';
353             my @cache = ( $comp, @{"$comp\::ISA"} );
354             my %namespaces;
355
356             while ( my $namespace = shift @cache ) {
357                 $namespaces{$namespace}++;
358                 for my $isa ( @{"$comp\::ISA"} ) {
359                     next if $namespaces{$isa};
360                     push @cache, $isa;
361                     $namespaces{$isa}++;
362                 }
363             }
364
365             for my $namespace ( keys %namespaces ) {
366
367                 for my $sym ( values %{ $namespace . '::' } ) {
368
369                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
370
371                         $name = *{$sym}{NAME};
372                         $self->set_action( $name, $code, $comp, $attrs );
373                         last;
374                     }
375
376                 }
377
378             }
379
380         }
381
382     }
383
384     my $actions  = $self->actions;
385     my $privates = Text::ASCIITable->new;
386     $privates->setCols( 'Private', 'Class' );
387     $privates->setColWidth( 'Private', 36, 1 );
388     $privates->setColWidth( 'Class',   37, 1 );
389
390     my $walker = sub {
391         my ( $walker, $parent, $prefix ) = @_;
392         $prefix .= $parent->getNodeValue || '';
393         $prefix .= '/' unless $prefix =~ /\/$/;
394         my $uid = $parent->getUID;
395
396         for my $action ( keys %{ $actions->{private}->{$uid} } ) {
397             my ( $class, $code ) = @{ $actions->{private}->{$uid}->{$action} };
398             $privates->addRow( "$prefix$action", $class );
399         }
400
401         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
402     };
403
404     $walker->( $walker, $self->tree, '' );
405     $self->log->debug( 'Loaded private actions', $privates->draw )
406       if ( @{ $privates->{tbl_rows} } && $self->debug );
407
408     my $publics = Text::ASCIITable->new;
409     $publics->setCols( 'Public', 'Private' );
410     $publics->setColWidth( 'Public',  36, 1 );
411     $publics->setColWidth( 'Private', 37, 1 );
412
413     for my $plain ( sort keys %{ $actions->{plain} } ) {
414         my ( $class, $code ) = @{ $actions->{plain}->{$plain} };
415         my $reverse = $self->actions->{reverse}->{$code};
416         $reverse = $reverse ? "/$reverse" : $code;
417         $publics->addRow( "/$plain", $reverse );
418     }
419
420     $self->log->debug( 'Loaded public actions', $publics->draw )
421       if ( @{ $publics->{tbl_rows} } && $self->debug );
422
423     my $regexes = Text::ASCIITable->new;
424     $regexes->setCols( 'Regex', 'Private' );
425     $regexes->setColWidth( 'Regex',   36, 1 );
426     $regexes->setColWidth( 'Private', 37, 1 );
427
428     for my $regex ( sort keys %{ $actions->{regex} } ) {
429         my ( $class, $code ) = @{ $actions->{regex}->{$regex} };
430         my $reverse = $self->actions->{reverse}->{$code};
431         $reverse = $reverse ? "/$reverse" : $code;
432         $regexes->addRow( $regex, $reverse );
433     }
434
435     $self->log->debug( 'Loaded regex actions', $regexes->draw )
436       if ( @{ $regexes->{tbl_rows} } && $self->debug );
437 }
438
439 =back
440
441 =head1 AUTHOR
442
443 Sebastian Riedel, C<sri@cpan.org>
444
445 =head1 COPYRIGHT
446
447 This program is free software, you can redistribute it and/or modify it under
448 the same terms as Perl itself.
449
450 =cut
451
452 1;