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