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