Added Catalyst::Utils
[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/Couldn't forward to "$class"/;
141             $c->error($error);
142             $c->log->debug($error) if $c->debug;
143             return 0;
144         }
145
146         my $method = shift || 'process';
147
148         if ( my $code = $class->can($method) ) {
149             $c->actions->{reverse}->{"$code"} = "$class->$method";
150             $results = [ [ [ $class, $code ] ] ];
151         }
152
153         else {
154             my $error = qq/Couldn't forward to "$class"/;
155             $c->error($error);
156             $c->log->debug($error)
157               if $c->debug;
158             return 0;
159         }
160
161     }
162
163     for my $result ( @{$results} ) {
164         $c->execute( @{ $result->[0] } );
165         return if scalar @{ $c->error };
166         last unless $c->state;
167     }
168
169     return $c->state;
170 }
171
172 =item $c->get_action( $action, $namespace )
173
174 Get an action in a given namespace.
175
176 =cut
177
178 sub get_action {
179     my ( $c, $action, $namespace ) = @_;
180     return [] unless $action;
181     $namespace ||= '';
182
183     if ($namespace) {
184         $namespace = '' if $namespace eq '/';
185         my $parent = $c->tree;
186         my @results;
187         my %allowed = ( begin => 1, auto => 1, default => 1, end => 1 );
188
189         if ( $allowed{$action} ) {
190             my $result = $c->actions->{private}->{ $parent->getUID }->{$action};
191             push @results, [$result] if $result;
192             my $visitor = Tree::Simple::Visitor::FindByPath->new;
193
194             for my $part ( split '/', $namespace ) {
195                 $visitor->setSearchPath($part);
196                 $parent->accept($visitor);
197                 my $child = $visitor->getResult;
198                 my $uid   = $child->getUID if $child;
199                 my $match = $c->actions->{private}->{$uid}->{$action} if $uid;
200                 push @results, [$match] if $match;
201                 $parent = $child if $child;
202             }
203
204         }
205
206         else {
207
208             if ($namespace) {
209                 my $visitor = Tree::Simple::Visitor::FindByPath->new;
210                 $visitor->setSearchPath( split '/', $namespace );
211                 $parent->accept($visitor);
212                 my $child = $visitor->getResult;
213                 my $uid   = $child->getUID if $child;
214                 my $match = $c->actions->{private}->{$uid}->{$action}
215                   if $uid;
216                 push @results, [$match] if $match;
217             }
218
219             else {
220                 my $result =
221                   $c->actions->{private}->{ $parent->getUID }->{$action};
222                 push @results, [$result] if $result;
223             }
224
225         }
226         return \@results;
227     }
228
229     elsif ( my $p = $c->actions->{plain}->{$action} ) { return [ [$p] ] }
230     elsif ( my $r = $c->actions->{regex}->{$action} ) { return [ [$r] ] }
231
232     else {
233
234         for my $i ( 0 .. $#{ $c->actions->{compiled} } ) {
235             my $name  = $c->actions->{compiled}->[$i]->[0];
236             my $regex = $c->actions->{compiled}->[$i]->[1];
237
238             if ( $action =~ $regex ) {
239                 my @snippets;
240                 for my $i ( 1 .. 9 ) {
241                     no strict 'refs';
242                     last unless ${$i};
243                     push @snippets, ${$i};
244                 }
245                 return [ [ $c->actions->{regex}->{$name}, $name, \@snippets ] ];
246             }
247
248         }
249     }
250     return [];
251 }
252
253 =item $c->set_action( $action, $code, $namespace, $attrs )
254
255 Set an action in a given namespace.
256
257 =cut
258
259 sub set_action {
260     my ( $c, $method, $code, $namespace, $attrs ) = @_;
261
262     my $prefix = Catalyst::Utils::class2prefix($namespace) || '';
263     my %flags;
264
265     for my $attr ( @{$attrs} ) {
266         if    ( $attr =~ /^(Local|Relative)$/ )        { $flags{local}++ }
267         elsif ( $attr =~ /^(Global|Absolute)$/ )       { $flags{global}++ }
268         elsif ( $attr =~ /^Path\((.+)\)$/i )           { $flags{path} = $1 }
269         elsif ( $attr =~ /^Private$/i )                { $flags{private}++ }
270         elsif ( $attr =~ /^(Regex|Regexp)\((.+)\)$/i ) { $flags{regex} = $2 }
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     for my $comp (@$comps) {
352         $comp = ref $comp || $comp;
353
354         for my $action ( @{ $comp->_cache } ) {
355             my ( $code, $attrs ) = @{$action};
356             my $name = '';
357             no strict 'refs';
358             my @cache = ( $comp, @{"$comp\::ISA"} );
359             my %namespaces;
360
361             while ( my $namespace = shift @cache ) {
362                 $namespaces{$namespace}++;
363                 for my $isa ( @{"$comp\::ISA"} ) {
364                     next if $namespaces{$isa};
365                     push @cache, $isa;
366                     $namespaces{$isa}++;
367                 }
368             }
369
370             for my $namespace ( keys %namespaces ) {
371
372                 for my $sym ( values %{ $namespace . '::' } ) {
373
374                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
375
376                         $name = *{$sym}{NAME};
377                         $self->set_action( $name, $code, $comp, $attrs );
378                         last;
379                     }
380
381                 }
382
383             }
384
385         }
386
387     }
388
389     my $actions  = $self->actions;
390     my $privates = Text::ASCIITable->new;
391     $privates->setCols( 'Private', 'Class' );
392     $privates->setColWidth( 'Private', 36, 1 );
393     $privates->setColWidth( 'Class',   37, 1 );
394
395     my $walker = sub {
396         my ( $walker, $parent, $prefix ) = @_;
397         $prefix .= $parent->getNodeValue || '';
398         $prefix .= '/' unless $prefix =~ /\/$/;
399         my $uid = $parent->getUID;
400
401         for my $action ( keys %{ $actions->{private}->{$uid} } ) {
402             my ( $class, $code ) = @{ $actions->{private}->{$uid}->{$action} };
403             $privates->addRow( "$prefix$action", $class );
404         }
405
406         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
407     };
408
409     $walker->( $walker, $self->tree, '' );
410     $self->log->debug( 'Loaded private actions', $privates->draw )
411       if ( @{ $privates->{tbl_rows} } && $self->debug );
412
413     my $publics = Text::ASCIITable->new;
414     $publics->setCols( 'Public', 'Private' );
415     $publics->setColWidth( 'Public',  36, 1 );
416     $publics->setColWidth( 'Private', 37, 1 );
417
418     for my $plain ( sort keys %{ $actions->{plain} } ) {
419         my ( $class, $code ) = @{ $actions->{plain}->{$plain} };
420         my $reverse = $self->actions->{reverse}->{$code};
421         $reverse = $reverse ? "/$reverse" : $code;
422         $publics->addRow( "/$plain", $reverse );
423     }
424
425     $self->log->debug( 'Loaded public actions', $publics->draw )
426       if ( @{ $publics->{tbl_rows} } && $self->debug );
427
428     my $regexes = Text::ASCIITable->new;
429     $regexes->setCols( 'Regex', 'Private' );
430     $regexes->setColWidth( 'Regex',   36, 1 );
431     $regexes->setColWidth( 'Private', 37, 1 );
432
433     for my $regex ( sort keys %{ $actions->{regex} } ) {
434         my ( $class, $code ) = @{ $actions->{regex}->{$regex} };
435         my $reverse = $self->actions->{reverse}->{$code};
436         $reverse = $reverse ? "/$reverse" : $code;
437         $regexes->addRow( $regex, $reverse );
438     }
439
440     $self->log->debug( 'Loaded regex actions', $regexes->draw )
441       if ( @{ $regexes->{tbl_rows} } && $self->debug );
442 }
443
444 =back
445
446 =head1 AUTHOR
447
448 Sebastian Riedel, C<sri@cpan.org>
449
450 =head1 COPYRIGHT
451
452 This program is free software, you can redistribute it and/or modify it under
453 the same terms as Perl itself.
454
455 =cut
456
457 1;