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