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