Looping and recursion tests plus a fix
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Dispatcher.pm
CommitLineData
68a748b9 1package Catalyst::Dispatcher;
1abd6db7 2
3use strict;
fbcc39ad 4use base 'Class::Accessor::Fast';
a2f2cde9 5use Catalyst::Exception;
f05af9ba 6use Catalyst::Utils;
fbcc39ad 7use Catalyst::Action;
b7aebc12 8use Catalyst::ActionContainer;
b96f127f 9use Catalyst::DispatchType::Default;
bcccee4e 10use Catalyst::DispatchType::Index;
87b85407 11use Text::SimpleTable;
1abd6db7 12use Tree::Simple;
13use Tree::Simple::Visitor::FindByPath;
14
fbcc39ad 15# Stringify to class
16use overload '""' => sub { return ref shift }, fallback => 1;
17
49070d25 18__PACKAGE__->mk_accessors(
19 qw/tree dispatch_types registered_dispatch_types
e7bb8d33 20 method_action_class action_container_class
21 preload_dispatch_types postload_dispatch_types
22 /
49070d25 23);
6d030e6f 24
25# Preload these action types
61a9002d 26our @PRELOAD = qw/Index Path Regex/;
1abd6db7 27
2d1d8f91 28# Postload these action types
61a9002d 29our @POSTLOAD = qw/Default/;
2d1d8f91 30
1abd6db7 31=head1 NAME
32
9c053379 33Catalyst::Dispatcher - The Catalyst Dispatcher
1abd6db7 34
35=head1 SYNOPSIS
36
37See L<Catalyst>.
38
39=head1 DESCRIPTION
40
41=head1 METHODS
42
e7bb8d33 43=cut
44
45sub new {
46 my $self = shift;
47 my $class = ref($self) || $self;
48
49 my $obj = $class->SUPER::new( @_ );
50
51 # set the default pre- and and postloads
52 $obj->preload_dispatch_types( \@PRELOAD );
53 $obj->postload_dispatch_types( \@POSTLOAD );
54 return $obj;
55}
56
57=head2 $self->preload_dispatch_types
58
59An arrayref of pre-loaded dispatchtype classes
60
61Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
62To use a custom class outside the regular C<Catalyst> namespace, prefix
63it with a C<+>, like so:
64
65 +My::Dispatch::Type
66
67=head2 $self->postload_dispatch_types
68
69An arrayref of post-loaded dispatchtype classes
70
71Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
72To use a custom class outside the regular C<Catalyst> namespace, prefix
73it with a C<+>, like so:
74
75 +My::Dispatch::Type
76
b5ecfcf0 77=head2 $self->detach( $c, $command [, \@arguments ] )
6ef62eb2 78
79=cut
80
81sub detach {
fbcc39ad 82 my ( $self, $c, $command, @args ) = @_;
bd7d2e94 83 $c->forward( $command, @args ) if $command;
fbcc39ad 84 die $Catalyst::DETACH;
6ef62eb2 85}
86
b5ecfcf0 87=head2 $self->dispatch($c)
1abd6db7 88
89=cut
90
91sub dispatch {
fbcc39ad 92 my ( $self, $c ) = @_;
66e28e3f 93 if ( $c->action ) {
28591cd7 94 $c->forward( join( '/', '', $c->action->namespace, '_DISPATCH' ) );
fbcc39ad 95 }
96
97 else {
1abd6db7 98 my $path = $c->req->path;
99 my $error = $path
100 ? qq/Unknown resource "$path"/
101 : "No default action defined";
102 $c->log->error($error) if $c->debug;
103 $c->error($error);
104 }
105}
106
b5ecfcf0 107=head2 $self->forward( $c, $command [, \@arguments ] )
1abd6db7 108
109=cut
110
111sub forward {
fbcc39ad 112 my $self = shift;
1abd6db7 113 my $c = shift;
114 my $command = shift;
99fe1710 115
1abd6db7 116 unless ($command) {
117 $c->log->debug('Nothing to forward to') if $c->debug;
118 return 0;
119 }
99fe1710 120
138ce4c0 121 my $local_args = 0;
6d12f1d4 122 my $arguments = $c->req->args;
138ce4c0 123 if ( ref( $_[-1] ) eq 'ARRAY' ) {
6d12f1d4 124 $arguments = pop(@_);
125 $local_args = 1;
138ce4c0 126 }
99fe1710 127
a9dc674c 128 my $result;
fbcc39ad 129
16aa17e9 130 unless ( ref $command ) {
131 my $command_copy = $command;
8199eac3 132
16aa17e9 133 unless ( $command_copy =~ s/^\/// ) {
46245bee 134 my $namespace = $c->stack->[-1]->namespace;
135 $command_copy = "${namespace}/${command}";
16aa17e9 136 }
99fe1710 137
16aa17e9 138 unless ( $command_copy =~ /\// ) {
139 $result = $c->get_action( $command_copy, '/' );
140 }
141 else {
142 my @extra_args;
143 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
144 my $tail = $2;
145 $result = $c->get_action( $tail, $1 );
146 if ($result) {
6d12f1d4 147 $local_args = 1;
148 $command = $tail;
d3f21b2f 149 unshift( @{$arguments}, @extra_args );
16aa17e9 150 last DESCEND;
151 }
152 unshift( @extra_args, $tail );
8199eac3 153 }
8199eac3 154 }
e494bd6b 155 }
99fe1710 156
49070d25 157 unless ($result) {
bd7d2e94 158
86d993ab 159 my $class = ref($command)
160 || ref( $c->component($command) )
161 || $c->component($command);
162 my $method = shift || 'process';
d6e0d7e6 163
f3b3f450 164 unless ($class) {
bd7d2e94 165 my $error =
166qq/Couldn't forward to command "$command". Invalid action or component./;
3b2ed580 167 $c->error($error);
168 $c->log->debug($error) if $c->debug;
1abd6db7 169 return 0;
170 }
bd7d2e94 171
d6e0d7e6 172 if ( my $code = $class->can($method) ) {
97d6d2bd 173 my $action = $self->method_action_class->new(
fbcc39ad 174 {
6b239949 175 name => $method,
fbcc39ad 176 code => $code,
177 reverse => "$class->$method",
11bd4e3e 178 class => $class,
46245bee 179 namespace => Catalyst::Utils::class2prefix(
180 $class, $c->config->{case_sensitive}
181 ),
fbcc39ad 182 }
183 );
a9dc674c 184 $result = $action;
fbcc39ad 185 }
186
187 else {
bd7d2e94 188 my $error =
189 qq/Couldn't forward to "$class". Does not implement "$method"/;
3b2ed580 190 $c->error($error);
191 $c->log->debug($error)
1abd6db7 192 if $c->debug;
193 return 0;
194 }
99fe1710 195
1abd6db7 196 }
bd7d2e94 197
6d12f1d4 198 if ($local_args) {
199 local $c->request->{arguments} = [ @{$arguments} ];
200 $result->execute($c);
201 }
202 else { $result->execute($c) }
99fe1710 203
1abd6db7 204 return $c->state;
205}
206
b5ecfcf0 207=head2 $self->prepare_action($c)
fbcc39ad 208
209=cut
210
211sub prepare_action {
212 my ( $self, $c ) = @_;
213 my $path = $c->req->path;
214 my @path = split /\//, $c->req->path;
215 $c->req->args( \my @args );
216
61a9002d 217 unshift( @path, '' ); # Root action
78d760bb 218
b96f127f 219 DESCEND: while (@path) {
fbcc39ad 220 $path = join '/', @path;
61a9002d 221 $path =~ s#^/##;
fbcc39ad 222
61a9002d 223 $path = '' if $path eq '/'; # Root action
78d760bb 224
22f3a8dd 225 # Check out dispatch types to see if any will handle the path at
226 # this level
227
78d760bb 228 foreach my $type ( @{ $self->dispatch_types } ) {
2633d7dc 229 last DESCEND if $type->match( $c, $path );
66e28e3f 230 }
b96f127f 231
22f3a8dd 232 # If not, move the last part path to args
4082e678 233 my $arg = pop(@path);
234 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
235 unshift @args, $arg;
fbcc39ad 236 }
237
e3a13771 238 $c->log->debug( 'Path is "' . $c->req->match . '"' )
239 if ( $c->debug && $c->req->match );
240
fbcc39ad 241 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
242 if ( $c->debug && @args );
243}
244
b5ecfcf0 245=head2 $self->get_action( $action, $namespace )
1abd6db7 246
247=cut
248
249sub get_action {
bcd1002b 250 my ( $self, $name, $namespace ) = @_;
79a3189a 251 return unless $name;
bcccee4e 252 $namespace ||= '';
772ab8ae 253 $namespace = '' if $namespace eq '/';
99fe1710 254
78d760bb 255 my @match = $self->get_containers($namespace);
c8d9780f 256
79a3189a 257 return unless @match;
772ab8ae 258
684d10ed 259 if ( my $action = $match[-1]->get_action($name) ) {
79a3189a 260 return $action if $action->namespace eq $namespace;
1abd6db7 261 }
1abd6db7 262}
263
b5ecfcf0 264=head2 $self->get_actions( $c, $action, $namespace )
a9dc674c 265
266=cut
267
268sub get_actions {
269 my ( $self, $c, $action, $namespace ) = @_;
270 return [] unless $action;
271 $namespace ||= '';
272 $namespace = '' if $namespace eq '/';
273
274 my @match = $self->get_containers($namespace);
275
684d10ed 276 return map { $_->get_action($action) } @match;
a9dc674c 277}
278
b5ecfcf0 279=head2 $self->get_containers( $namespace )
cfd04b0c 280
281=cut
282
283sub get_containers {
284 my ( $self, $namespace ) = @_;
285
90ce41ba 286 # If the namespace is / just return the root ActionContainer
287
78d760bb 288 return ( $self->tree->getNodeValue )
289 if ( !$namespace || ( $namespace eq '/' ) );
cfd04b0c 290
90ce41ba 291 # Use a visitor to recurse down the tree finding the ActionContainers
292 # for each namespace in the chain.
293
cfd04b0c 294 my $visitor = Tree::Simple::Visitor::FindByPath->new;
78d760bb 295 my @path = split( '/', $namespace );
296 $visitor->setSearchPath(@path);
cfd04b0c 297 $self->tree->accept($visitor);
298
299 my @match = $visitor->getResults;
78d760bb 300 @match = ( $self->tree ) unless @match;
cfd04b0c 301
78d760bb 302 if ( !defined $visitor->getResult ) {
90ce41ba 303
304 # If we don't manage to match, the visitor doesn't return the last
305 # node is matched, so foo/bar/baz would only find the 'foo' node,
306 # not the foo and foo/bar nodes as it should. This does another
307 # single-level search to see if that's the case, and the 'last unless'
308 # should catch any failures - or short-circuit this if this *is* a
309 # bug in the visitor and gets fixed.
310
f3b3f450 311 if ( my $extra = $path[ ( scalar @match ) - 1 ] ) {
540966c1 312 $visitor->setSearchPath($extra);
313 $match[-1]->accept($visitor);
314 push( @match, $visitor->getResult ) if defined $visitor->getResult;
315 }
cfd04b0c 316 }
317
318 return map { $_->getNodeValue } @match;
319}
320
b5ecfcf0 321=head2 $self->register( $c, $action )
aad72cc9 322
323=cut
324
79a3189a 325sub register {
326 my ( $self, $c, $action ) = @_;
327
694d15f1 328 my $registered = $self->registered_dispatch_types;
329
330 my $priv = 0;
331 foreach my $key ( keys %{ $action->attributes } ) {
332 $priv++ if $key eq 'Private';
333 my $class = "Catalyst::DispatchType::$key";
334 unless ( $registered->{$class} ) {
335 eval "require $class";
336 push( @{ $self->dispatch_types }, $class->new ) unless $@;
337 $registered->{$class} = 1;
338 }
339 }
340
341 # Pass the action to our dispatch types so they can register it if reqd.
01ce0928 342 my $reg = 0;
343 foreach my $type ( @{ $self->dispatch_types } ) {
344 $reg++ if $type->register( $c, $action );
694d15f1 345 }
346
347 return unless $reg + $priv;
348
79a3189a 349 my $namespace = $action->namespace;
350 my $parent = $self->tree;
351 my $visitor = Tree::Simple::Visitor::FindByPath->new;
99fe1710 352
11bd4e3e 353 if ($namespace) {
354 for my $part ( split '/', $namespace ) {
1abd6db7 355 $visitor->setSearchPath($part);
356 $parent->accept($visitor);
b7aebc12 357 my $child = $visitor->getResult;
78d760bb 358
b7aebc12 359 unless ($child) {
90ce41ba 360
361 # Create a new tree node and an ActionContainer to form
362 # its value.
363
78d760bb 364 my $container =
365 Catalyst::ActionContainer->new(
366 { part => $part, actions => {} } );
b7aebc12 367 $child = $parent->addChild( Tree::Simple->new($container) );
368 $visitor->setSearchPath($part);
369 $parent->accept($visitor);
370 $child = $visitor->getResult;
371 }
78d760bb 372
b7aebc12 373 $parent = $child;
1abd6db7 374 }
1abd6db7 375 }
99fe1710 376
90ce41ba 377 # Set the method value
49070d25 378 $parent->getNodeValue->actions->{ $action->name } = $action;
1abd6db7 379}
380
b5ecfcf0 381=head2 $self->setup_actions( $class, $component )
1abd6db7 382
383=cut
384
385sub setup_actions {
11bd4e3e 386 my ( $self, $c ) = @_;
99fe1710 387
6d030e6f 388 $self->dispatch_types( [] );
91d4abc5 389 $self->registered_dispatch_types( {} );
49070d25 390 $self->method_action_class('Catalyst::Action');
391 $self->action_container_class('Catalyst::ActionContainer');
12e28165 392
6d030e6f 393 # Preload action types
e7bb8d33 394 for my $type ( @{$self->preload_dispatch_types} ) {
395 my $class = ($type =~ /^\+(.*)$/) ? $1 : "Catalyst::DispatchType::${type}";
6d030e6f 396 eval "require $class";
397 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
398 if $@;
399 push @{ $self->dispatch_types }, $class->new;
91d4abc5 400 $self->registered_dispatch_types->{$class} = 1;
6d030e6f 401 }
b96f127f 402
12e28165 403 # We use a tree
78d760bb 404 my $container =
405 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
b7aebc12 406 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
e494bd6b 407
49070d25 408 foreach my $comp ( values %{ $c->components } ) {
409 $comp->register_actions($c) if $comp->can('register_actions');
1abd6db7 410 }
e494bd6b 411
2d1d8f91 412 # Postload action types
e7bb8d33 413 for my $type ( @{$self->postload_dispatch_types} ) {
414 my $class = ($type =~ /^\+(.*)$/) ? $1 : "Catalyst::DispatchType::${type}";
2d1d8f91 415 eval "require $class";
416 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
417 if $@;
418 push @{ $self->dispatch_types }, $class->new;
419 }
6d030e6f 420
11bd4e3e 421 return unless $c->debug;
99fe1710 422
684d10ed 423 my $privates = Text::SimpleTable->new(
dbf03873 424 [ 20, 'Private' ],
425 [ 38, 'Class' ],
426 [ 12, 'Method' ]
684d10ed 427 );
99fe1710 428
87b85407 429 my $has_private = 0;
1abd6db7 430 my $walker = sub {
431 my ( $walker, $parent, $prefix ) = @_;
432 $prefix .= $parent->getNodeValue || '';
433 $prefix .= '/' unless $prefix =~ /\/$/;
b7aebc12 434 my $node = $parent->getNodeValue->actions;
99fe1710 435
78d760bb 436 for my $action ( keys %{$node} ) {
b7aebc12 437 my $action_obj = $node->{$action};
b0bb11ec 438 next
439 if ( ( $action =~ /^_.*/ )
440 && ( !$c->config->{show_internal_actions} ) );
684d10ed 441 $privates->row( "$prefix$action", $action_obj->class, $action );
87b85407 442 $has_private = 1;
1abd6db7 443 }
99fe1710 444
1abd6db7 445 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
446 };
99fe1710 447
1abd6db7 448 $walker->( $walker, $self->tree, '' );
11bd4e3e 449 $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
49070d25 450 if ($has_private);
99fe1710 451
a9cbd748 452 # List all public actions
11bd4e3e 453 $_->list($c) for @{ $self->dispatch_types };
1abd6db7 454}
455
1abd6db7 456=head1 AUTHOR
457
458Sebastian Riedel, C<sri@cpan.org>
158c88c0 459Matt S Trout, C<mst@shadowcatsystems.co.uk>
1abd6db7 460
461=head1 COPYRIGHT
462
463This program is free software, you can redistribute it and/or modify it under
464the same terms as Perl itself.
465
466=cut
467
4681;