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