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