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