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