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