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