Reverted previous change
[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::SimpleTable;
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(
19     qw/tree dispatch_types registered_dispatch_types
20       method_action_class action_container_class/
21 );
22
23 # Preload these action types
24 our @PRELOAD = qw/Path Regex/;
25
26 # Postload these action types
27 our @POSTLOAD = qw/Index Default/;
28
29 =head1 NAME
30
31 Catalyst::Dispatcher - The Catalyst Dispatcher
32
33 =head1 SYNOPSIS
34
35 See L<Catalyst>.
36
37 =head1 DESCRIPTION
38
39 =head1 METHODS
40
41 =over 4
42
43 =item $self->detach( $c, $command [, \@arguments ] )
44
45 =cut
46
47 sub detach {
48     my ( $self, $c, $command, @args ) = @_;
49     $c->forward( $command, @args ) if $command;
50     die $Catalyst::DETACH;
51 }
52
53 =item $self->dispatch($c)
54
55 =cut
56
57 sub dispatch {
58     my ( $self, $c ) = @_;
59
60     if ( $c->action ) {
61         $c->forward( join( '/', '', $c->action->namespace, '_DISPATCH' ) );
62     }
63
64     else {
65         my $path  = $c->req->path;
66         my $error = $path
67           ? qq/Unknown resource "$path"/
68           : "No default action defined";
69         $c->log->error($error) if $c->debug;
70         $c->error($error);
71     }
72 }
73
74 =item $self->forward( $c, $command [, \@arguments ] )
75
76 =cut
77
78 sub forward {
79     my $self    = shift;
80     my $c       = shift;
81     my $command = shift;
82
83     unless ($command) {
84         $c->log->debug('Nothing to forward to') if $c->debug;
85         return 0;
86     }
87
88     my $local_args = 0;
89     my $arguments  = $c->req->args;
90     if ( ref( $_[-1] ) eq 'ARRAY' ) {
91         $arguments  = pop(@_);
92         $local_args = 1;
93     }
94
95     my $result;
96
97     unless ( ref $command ) {
98         my $command_copy = $command;
99
100         unless ( $command_copy =~ s/^\/// ) {
101             my $namespace = $c->stack->[-1]->namespace;
102             $command_copy = "${namespace}/${command}";
103         }
104
105         unless ( $command_copy =~ /\// ) {
106             $result = $c->get_action( $command_copy, '/' );
107         }
108         else {
109             my @extra_args;
110           DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
111                 my $tail = $2;
112                 $result = $c->get_action( $tail, $1 );
113                 if ($result) {
114                     $local_args = 1;
115                     $command    = $tail;
116                     unshift( @{$arguments}, @extra_args );
117                     last DESCEND;
118                 }
119                 unshift( @extra_args, $tail );
120             }
121         }
122     }
123
124     unless ($result) {
125
126         my $class  = ref($command) || ref( $c->component($command) );
127         my $method = shift         || 'process';
128
129         unless ($class) {
130             my $error =
131 qq/Couldn't forward to command "$command". Invalid action or component./;
132             $c->error($error);
133             $c->log->debug($error) if $c->debug;
134             return 0;
135         }
136
137         if ( my $code = $class->can($method) ) {
138             my $action = $self->method_action_class->new(
139                 {
140                     name      => $method,
141                     code      => $code,
142                     reverse   => "$class->$method",
143                     class     => $class,
144                     namespace => Catalyst::Utils::class2prefix(
145                         $class, $c->config->{case_sensitive}
146                     ),
147                 }
148             );
149             $result = $action;
150         }
151
152         else {
153             my $error =
154               qq/Couldn't forward to "$class". Does not implement "$method"/;
155             $c->error($error);
156             $c->log->debug($error)
157               if $c->debug;
158             return 0;
159         }
160
161     }
162
163     if ($local_args) {
164         local $c->request->{arguments} = [ @{$arguments} ];
165         $result->execute($c);
166     }
167     else { $result->execute($c) }
168
169     return $c->state;
170 }
171
172 =item $self->prepare_action($c)
173
174 =cut
175
176 sub prepare_action {
177     my ( $self, $c ) = @_;
178     my $path = $c->req->path;
179     my @path = split /\//, $c->req->path;
180     $c->req->args( \my @args );
181
182     push( @path, '/' ) unless @path;    # Root action
183
184   DESCEND: while (@path) {
185         $path = join '/', @path;
186
187         $path = '' if $path eq '/';     # Root action
188
189         # Check out dispatch types to see if any will handle the path at
190         # this level
191
192         foreach my $type ( @{ $self->dispatch_types } ) {
193             last DESCEND if $type->match( $c, $path );
194         }
195
196         # If not, move the last part path to args
197         unshift @args, pop @path;
198     }
199
200     $c->log->debug( 'Path is "' . $c->req->match . '"' )
201       if ( $c->debug && $c->req->match );
202
203     $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
204       if ( $c->debug && @args );
205 }
206
207 =item $self->get_action( $action, $namespace )
208
209 =cut
210
211 sub get_action {
212     my ( $self, $name, $namespace ) = @_;
213     return unless $name;
214     $namespace ||= '';
215     $namespace = '' if $namespace eq '/';
216
217     my @match = $self->get_containers($namespace);
218
219     return unless @match;
220
221     if ( my $action = $match[-1]->get_action($name) ) {
222         return $action if $action->namespace eq $namespace;
223     }
224 }
225
226 =item $self->get_actions( $c, $action, $namespace )
227
228 =cut
229
230 sub get_actions {
231     my ( $self, $c, $action, $namespace ) = @_;
232     return [] unless $action;
233     $namespace ||= '';
234     $namespace = '' if $namespace eq '/';
235
236     my @match = $self->get_containers($namespace);
237
238     return map { $_->get_action($action) } @match;
239 }
240
241 =item $self->get_containers( $namespace )
242
243 =cut
244
245 sub get_containers {
246     my ( $self, $namespace ) = @_;
247
248     # If the namespace is / just return the root ActionContainer
249
250     return ( $self->tree->getNodeValue )
251       if ( !$namespace || ( $namespace eq '/' ) );
252
253     # Use a visitor to recurse down the tree finding the ActionContainers
254     # for each namespace in the chain.
255
256     my $visitor = Tree::Simple::Visitor::FindByPath->new;
257     my @path = split( '/', $namespace );
258     $visitor->setSearchPath(@path);
259     $self->tree->accept($visitor);
260
261     my @match = $visitor->getResults;
262     @match = ( $self->tree ) unless @match;
263
264     if ( !defined $visitor->getResult ) {
265
266         # If we don't manage to match, the visitor doesn't return the last
267         # node is matched, so foo/bar/baz would only find the 'foo' node,
268         # not the foo and foo/bar nodes as it should. This does another
269         # single-level search to see if that's the case, and the 'last unless'
270         # should catch any failures - or short-circuit this if this *is* a
271         # bug in the visitor and gets fixed.
272
273         if ( my $extra = $path[ ( scalar @match ) - 1 ] ) {
274             $visitor->setSearchPath($extra);
275             $match[-1]->accept($visitor);
276             push( @match, $visitor->getResult ) if defined $visitor->getResult;
277         }
278     }
279
280     return map { $_->getNodeValue } @match;
281 }
282
283 =item $self->register( $c, $action )
284
285 =cut
286
287 sub register {
288     my ( $self, $c, $action ) = @_;
289
290     my $registered = $self->registered_dispatch_types;
291
292     my $priv = 0;
293     foreach my $key ( keys %{ $action->attributes } ) {
294         $priv++ if $key eq 'Private';
295         my $class = "Catalyst::DispatchType::$key";
296         unless ( $registered->{$class} ) {
297             eval "require $class";
298             push( @{ $self->dispatch_types }, $class->new ) unless $@;
299             $registered->{$class} = 1;
300         }
301     }
302
303     # Pass the action to our dispatch types so they can register it if reqd.
304     my $reg = 0;
305     foreach my $type ( @{ $self->dispatch_types } ) {
306         $reg++ if $type->register( $c, $action );
307     }
308
309     return unless $reg + $priv;
310
311     my $namespace = $action->namespace;
312     my $parent    = $self->tree;
313     my $visitor   = Tree::Simple::Visitor::FindByPath->new;
314
315     if ($namespace) {
316         for my $part ( split '/', $namespace ) {
317             $visitor->setSearchPath($part);
318             $parent->accept($visitor);
319             my $child = $visitor->getResult;
320
321             unless ($child) {
322
323                 # Create a new tree node and an ActionContainer to form
324                 # its value.
325
326                 my $container =
327                   Catalyst::ActionContainer->new(
328                     { part => $part, actions => {} } );
329                 $child = $parent->addChild( Tree::Simple->new($container) );
330                 $visitor->setSearchPath($part);
331                 $parent->accept($visitor);
332                 $child = $visitor->getResult;
333             }
334
335             $parent = $child;
336         }
337     }
338
339     # Set the method value
340     $parent->getNodeValue->actions->{ $action->name } = $action;
341 }
342
343 =item $self->setup_actions( $class, $component )
344
345 =cut
346
347 sub setup_actions {
348     my ( $self, $c ) = @_;
349
350     $self->dispatch_types( [] );
351     $self->registered_dispatch_types( {} );
352     $self->method_action_class('Catalyst::Action');
353     $self->action_container_class('Catalyst::ActionContainer');
354
355     # Preload action types
356     for my $type (@PRELOAD) {
357         my $class = "Catalyst::DispatchType::$type";
358         eval "require $class";
359         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
360           if $@;
361         push @{ $self->dispatch_types }, $class->new;
362         $self->registered_dispatch_types->{$class} = 1;
363     }
364
365     # We use a tree
366     my $container =
367       Catalyst::ActionContainer->new( { part => '/', actions => {} } );
368     $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
369
370     foreach my $comp ( values %{ $c->components } ) {
371         $comp->register_actions($c) if $comp->can('register_actions');
372     }
373
374     # Postload action types
375     for my $type (@POSTLOAD) {
376         my $class = "Catalyst::DispatchType::$type";
377         eval "require $class";
378         Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
379           if $@;
380         push @{ $self->dispatch_types }, $class->new;
381     }
382
383     return unless $c->debug;
384
385     my $privates = Text::SimpleTable->new(
386         [ 20, 'Private' ],
387         [ 38, 'Class' ],
388         [ 12, 'Method' ]
389     );
390
391     my $has_private = 0;
392     my $walker = sub {
393         my ( $walker, $parent, $prefix ) = @_;
394         $prefix .= $parent->getNodeValue || '';
395         $prefix .= '/' unless $prefix =~ /\/$/;
396         my $node = $parent->getNodeValue->actions;
397
398         for my $action ( keys %{$node} ) {
399             my $action_obj = $node->{$action};
400             next
401               if ( ( $action =~ /^_.*/ )
402                 && ( !$c->config->{show_internal_actions} ) );
403             $privates->row( "$prefix$action", $action_obj->class, $action );
404             $has_private = 1;
405         }
406
407         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
408     };
409
410     $walker->( $walker, $self->tree, '' );
411     $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
412       if ($has_private);
413
414     # List all public actions
415     $_->list($c) for @{ $self->dispatch_types };
416 }
417
418 =back
419
420 =head1 AUTHOR
421
422 Sebastian Riedel, C<sri@cpan.org>
423 Matt S Trout, C<mst@shadowcatsystems.co.uk>
424
425 =head1 COPYRIGHT
426
427 This program is free software, you can redistribute it and/or modify it under
428 the same terms as Perl itself.
429
430 =cut
431
432 1;