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