Private flag is exclusive
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Dispatcher.pm
1 package Catalyst::Dispatcher;
2
3 use strict;
4 use base 'Class::Data::Inheritable';
5 use Memoize;
6 use Text::ASCIITable;
7 use Text::ASCIITable::Wrap 'wrap';
8 use Tree::Simple;
9 use Tree::Simple::Visitor::FindByPath;
10
11 __PACKAGE__->mk_classdata($_) for qw/actions tree/;
12
13 __PACKAGE__->actions(
14     { plain => {}, private => {}, regex => {}, compiled => [], reverse => {} }
15 );
16 __PACKAGE__->tree( Tree::Simple->new( 0, Tree::Simple->ROOT ) );
17
18 memoize('_class2prefix');
19
20 =head1 NAME
21
22 Catalyst::Dispatch - 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     unless ($namespace) {
47         if ( my $result = $c->get_action($action) ) {
48             $namespace = _class2prefix( $result->[0]->[0]->[0] );
49         }
50     }
51     my $default = $action eq 'default' ? $namespace : undef;
52     my $results = $c->get_action( $action, $default );
53     $namespace ||= '/';
54     if ( @{$results} ) {
55
56         # Execute last begin
57         $c->state(1);
58         if ( my $begin = @{ $c->get_action( 'begin', $namespace ) }[-1] ) {
59             $c->execute( @{ $begin->[0] } );
60             return if scalar @{ $c->error };
61         }
62
63         # Execute the auto chain
64         for my $auto ( @{ $c->get_action( 'auto', $namespace ) } ) {
65             $c->execute( @{ $auto->[0] } );
66             return if scalar @{ $c->error };
67             last unless $c->state;
68         }
69
70         # Execute the action or last default
71         if ( ( my $action = $c->req->action ) && $c->state ) {
72             if ( my $result = @{ $c->get_action( $action, $default ) }[-1] ) {
73                 $c->execute( @{ $result->[0] } );
74             }
75         }
76
77         # Execute last end
78         if ( my $end = @{ $c->get_action( 'end', $namespace ) }[-1] ) {
79             $c->execute( @{ $end->[0] } );
80             return if scalar @{ $c->error };
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     unless ($command) {
109         $c->log->debug('Nothing to forward to') if $c->debug;
110         return 0;
111     }
112     my $caller    = caller(0);
113     my $namespace = '/';
114     if ( $command =~ /^\// ) {
115         $command =~ /^(.*)\/(\w+)$/;
116         $namespace = $1 || '/';
117         $command = $2;
118     }
119     else { $namespace = _class2prefix($caller) || '/' }
120     my $results = $c->get_action( $command, $namespace );
121     unless ( @{$results} ) {
122         my $class = $command;
123         if ( $class =~ /[^\w\:]/ ) {
124             $c->log->debug(qq/Couldn't forward to "$class"/) if $c->debug;
125             return 0;
126         }
127         my $method = shift || 'process';
128         if ( my $code = $class->can($method) ) {
129             $c->actions->{reverse}->{"$code"} = "$class->$method";
130             $results = [ [ [ $class, $code ] ] ];
131         }
132         else {
133             $c->log->debug(qq/Couldn't forward to "$class->$method"/)
134               if $c->debug;
135             return 0;
136         }
137     }
138     for my $result ( @{$results} ) {
139         $c->execute( @{ $result->[0] } );
140         return if scalar @{ $c->error };
141         last unless $c->state;
142     }
143     return $c->state;
144 }
145
146 =item $c->get_action( $action, $namespace )
147
148 Get an action in a given namespace.
149
150 =cut
151
152 sub get_action {
153     my ( $c, $action, $namespace ) = @_;
154     return [] unless $action;
155     $namespace ||= '';
156     if ($namespace) {
157         $namespace = '' if $namespace eq '/';
158         my $parent = $c->tree;
159         my @results;
160         my %allowed = ( begin => 1, auto => 1, default => 1, end => 1 );
161         if ( $allowed{$action} ) {
162             my $result = $c->actions->{private}->{ $parent->getUID }->{$action};
163             push @results, [$result] if $result;
164             my $visitor = Tree::Simple::Visitor::FindByPath->new;
165             for my $part ( split '/', $namespace ) {
166                 $visitor->setSearchPath($part);
167                 $parent->accept($visitor);
168                 my $child = $visitor->getResult;
169                 my $uid   = $child->getUID if $child;
170                 my $match = $c->actions->{private}->{$uid}->{$action} if $uid;
171                 push @results, [$match] if $match;
172                 $parent = $child if $child;
173             }
174         }
175         else {
176             if ($namespace) {
177                 my $visitor = Tree::Simple::Visitor::FindByPath->new;
178                 $visitor->setSearchPath( split '/', $namespace );
179                 $parent->accept($visitor);
180                 my $child = $visitor->getResult;
181                 my $uid   = $child->getUID if $child;
182                 my $match = $c->actions->{private}->{$uid}->{$action}
183                   if $uid;
184                 push @results, [$match] if $match;
185             }
186             else {
187                 my $result =
188                   $c->actions->{private}->{ $parent->getUID }->{$action};
189                 push @results, [$result] if $result;
190             }
191         }
192         return \@results;
193     }
194     elsif ( my $p = $c->actions->{plain}->{$action} ) { return [ [$p] ] }
195     elsif ( my $r = $c->actions->{regex}->{$action} ) { return [ [$r] ] }
196     else {
197         for my $i ( 0 .. $#{ $c->actions->{compiled} } ) {
198             my $name  = $c->actions->{compiled}->[$i]->[0];
199             my $regex = $c->actions->{compiled}->[$i]->[1];
200             if ( $action =~ $regex ) {
201                 my @snippets;
202                 for my $i ( 1 .. 9 ) {
203                     no strict 'refs';
204                     last unless ${$i};
205                     push @snippets, ${$i};
206                 }
207                 return [ [ $c->actions->{regex}->{$name}, $name, \@snippets ] ];
208             }
209         }
210     }
211     return [];
212 }
213
214 =item $c->set_action( $action, $code, $namespace, $attrs )
215
216 Set an action in a given namespace.
217
218 =cut
219
220 sub set_action {
221     my ( $c, $method, $code, $namespace, $attrs ) = @_;
222
223     my $prefix = _class2prefix($namespace) || '';
224     my %flags;
225
226     for my $attr ( @{$attrs} ) {
227         if    ( $attr =~ /^(Local|Relative)$/ )        { $flags{local}++ }
228         elsif ( $attr =~ /^(Global|Absolute)$/ )       { $flags{global}++ }
229         elsif ( $attr =~ /^Path\((.+)\)$/i )           { $flags{path} = $1 }
230         elsif ( $attr =~ /^Private$/i )                { $flags{private}++ }
231         elsif ( $attr =~ /^(Regex|Regexp)\((.+)\)$/i ) { $flags{regex} = $2 }
232     }
233
234     if ( $flags{private} && ( keys %flags > 1 ) ) {
235         $c->log->error( 'Bad action definition "'
236               . join( ' ', @{$attrs} )
237               . qq/" for "$namespace->$method"/ );
238         return;
239     }
240     return unless keys %flags;
241
242     my $parent  = $c->tree;
243     my $visitor = Tree::Simple::Visitor::FindByPath->new;
244     for my $part ( split '/', $prefix ) {
245         $visitor->setSearchPath($part);
246         $parent->accept($visitor);
247         my $child = $visitor->getResult;
248         unless ($child) {
249             $child = $parent->addChild( Tree::Simple->new($part) );
250             $visitor->setSearchPath($part);
251             $parent->accept($visitor);
252             $child = $visitor->getResult;
253         }
254         $parent = $child;
255     }
256     my $uid = $parent->getUID;
257     $c->actions->{private}->{$uid}->{$method} = [ $namespace, $code ];
258     my $forward = $prefix ? "$prefix/$method" : $method;
259
260     if ( $flags{path} ) {
261         $flags{path} =~ s/^\w+//;
262         $flags{path} =~ s/\w+$//;
263         if ( $flags{path} =~ /^'(.*)'$/ ) { $flags{path} = $1 }
264         if ( $flags{path} =~ /^"(.*)"$/ ) { $flags{path} = $1 }
265     }
266     if ( $flags{regex} ) {
267         $flags{regex} =~ s/^\w+//;
268         $flags{regex} =~ s/\w+$//;
269         if ( $flags{regex} =~ /^'(.*)'$/ ) { $flags{regex} = $1 }
270         if ( $flags{regex} =~ /^"(.*)"$/ ) { $flags{regex} = $1 }
271     }
272
273     my $reverse = $prefix ? "$prefix/$method" : $method;
274
275     if ( $flags{local} || $flags{global} || $flags{path} ) {
276         my $path = $flags{path} || $method;
277         my $absolute = 0;
278         if ( $path =~ /^\/(.+)/ ) {
279             $path     = $1;
280             $absolute = 1;
281         }
282         $absolute = 1 if $flags{global};
283         my $name = $absolute ? $path : $prefix ? "$prefix/$path" : $path;
284         $c->actions->{plain}->{$name} = [ $namespace, $code ];
285     }
286     if ( my $regex = $flags{regex} ) {
287         push @{ $c->actions->{compiled} }, [ $regex, qr#$regex# ];
288         $c->actions->{regex}->{$regex} = [ $namespace, $code ];
289     }
290
291     $c->actions->{reverse}->{"$code"} = $reverse;
292 }
293
294 =item $class->setup_actions($component)
295
296 Setup actions for a component.
297
298 =cut
299
300 sub setup_actions {
301     my ( $self, $comps ) = @_;
302     for my $comp (@$comps) {
303         $comp = ref $comp || $comp;
304         for my $action ( @{ $comp->_cache } ) {
305             my ( $code, $attrs ) = @{$action};
306             my $name = '';
307             no strict 'refs';
308             my @cache = ( $comp, @{"$comp\::ISA"} );
309             my %namespaces;
310             while ( my $namespace = shift @cache ) {
311                 $namespaces{$namespace}++;
312                 for my $isa ( @{"$comp\::ISA"} ) {
313                     next if $namespaces{$isa};
314                     push @cache, $isa;
315                     $namespaces{$isa}++;
316                 }
317             }
318             for my $namespace ( keys %namespaces ) {
319                 for my $sym ( values %{ $namespace . '::' } ) {
320                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
321                         $name = *{$sym}{NAME};
322                         $self->set_action( $name, $code, $comp, $attrs );
323                         last;
324                     }
325                 }
326             }
327         }
328     }
329     my $actions  = $self->actions;
330     my $privates = Text::ASCIITable->new;
331     $privates->setCols( 'Private', 'Class' );
332     $privates->setColWidth( 'Private', 36, 1 );
333     $privates->setColWidth( 'Class',   37, 1 );
334     my $walker = sub {
335         my ( $walker, $parent, $prefix ) = @_;
336         $prefix .= $parent->getNodeValue || '';
337         $prefix .= '/' unless $prefix =~ /\/$/;
338         my $uid = $parent->getUID;
339         for my $action ( keys %{ $actions->{private}->{$uid} } ) {
340             my ( $class, $code ) = @{ $actions->{private}->{$uid}->{$action} };
341             $privates->addRow( wrap( "$prefix$action", 36 ),
342                 wrap( $class, 37 ) );
343         }
344         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
345     };
346     $walker->( $walker, $self->tree, '' );
347     $self->log->debug( 'Loaded private actions', $privates->draw )
348       if ( @{ $privates->{tbl_rows} } && $self->debug );
349     my $publics = Text::ASCIITable->new;
350     $publics->setCols( 'Public', 'Private' );
351     $publics->setColWidth( 'Public',  36, 1 );
352     $publics->setColWidth( 'Private', 37, 1 );
353     for my $plain ( sort keys %{ $actions->{plain} } ) {
354         my ( $class, $code ) = @{ $actions->{plain}->{$plain} };
355         my $reverse = $self->actions->{reverse}->{$code};
356         $reverse = $reverse ? "/$reverse" : $code;
357         $publics->addRow( wrap( "/$plain", 36 ), wrap( $reverse, 37 ) );
358     }
359     $self->log->debug( 'Loaded public actions', $publics->draw )
360       if ( @{ $publics->{tbl_rows} } && $self->debug );
361     my $regexes = Text::ASCIITable->new;
362     $regexes->setCols( 'Regex', 'Private' );
363     $regexes->setColWidth( 'Regex',   36, 1 );
364     $regexes->setColWidth( 'Private', 37, 1 );
365     for my $regex ( sort keys %{ $actions->{regex} } ) {
366         my ( $class, $code ) = @{ $actions->{regex}->{$regex} };
367         my $reverse = $self->actions->{reverse}->{$code};
368         $reverse = $reverse ? "/$reverse" : $code;
369         $regexes->addRow( wrap( $regex, 36 ), wrap( $reverse, 37 ) );
370     }
371     $self->log->debug( 'Loaded regex actions', $regexes->draw )
372       if ( @{ $regexes->{tbl_rows} } && $self->debug );
373 }
374
375 sub _prefix {
376     my ( $class, $name ) = @_;
377     my $prefix = _class2prefix($class);
378     $name = "$prefix/$name" if $prefix;
379     return $name;
380 }
381
382 sub _class2prefix {
383     my $class = shift || '';
384     my $prefix;
385     if ( $class =~ /^.*::([MVC]|Model|View|Controller)?::(.*)$/ ) {
386         $prefix = lc $2;
387         $prefix =~ s/\:\:/\//g;
388     }
389     return $prefix;
390 }
391
392 =back
393
394 =head1 AUTHOR
395
396 Sebastian Riedel, C<sri@cpan.org>
397
398 =head1 COPYRIGHT
399
400 This program is free software, you can redistribute it and/or modify it under
401 the same terms as Perl itself.
402
403 =cut
404
405 1;