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