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