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