Fixed typo
[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;
1abd6db7 11use Text::ASCIITable;
1abd6db7 12use Tree::Simple;
13use Tree::Simple::Visitor::FindByPath;
14
fbcc39ad 15# Stringify to class
16use overload '""' => sub { return ref shift }, fallback => 1;
17
6d030e6f 18__PACKAGE__->mk_accessors(qw/tree dispatch_types/);
19
20# Preload these action types
21our @PRELOAD = qw/Path Regex/;
1abd6db7 22
2d1d8f91 23# Postload these action types
24our @POSTLOAD = qw/Index Default/;
25
1abd6db7 26=head1 NAME
27
9c053379 28Catalyst::Dispatcher - The Catalyst Dispatcher
1abd6db7 29
30=head1 SYNOPSIS
31
32See L<Catalyst>.
33
34=head1 DESCRIPTION
35
36=head1 METHODS
37
38=over 4
39
fbcc39ad 40=item $self->detach( $c, $command [, \@arguments ] )
6ef62eb2 41
42=cut
43
44sub detach {
fbcc39ad 45 my ( $self, $c, $command, @args ) = @_;
bd7d2e94 46 $c->forward( $command, @args ) if $command;
fbcc39ad 47 die $Catalyst::DETACH;
6ef62eb2 48}
49
fbcc39ad 50=item $self->dispatch($c)
1abd6db7 51
52=cut
53
54sub dispatch {
fbcc39ad 55 my ( $self, $c ) = @_;
cfd04b0c 56
66e28e3f 57 if ( $c->action ) {
58
59 my @containers = $self->get_containers( $c->namespace );
60 my %actions;
61 foreach my $name (qw/begin auto end/) {
90ce41ba 62
63 # Go down the container list representing each part of the
64 # current namespace inheritance tree, grabbing the actions hash
65 # of the ActionContainer object and looking for actions of the
66 # appropriate name registered to the namespace
67
66e28e3f 68 $actions{$name} = [
78d760bb 69 map { $_->{$name} }
70 grep { exists $_->{$name} }
71 map { $_->actions } @containers
66e28e3f 72 ];
73 }
1abd6db7 74
fbcc39ad 75 # Errors break the normal flow and the end action is instantly run
76 my $error = 0;
77
1abd6db7 78 # Execute last begin
79 $c->state(1);
66e28e3f 80 if ( my $begin = @{ $actions{begin} }[-1] ) {
cfd04b0c 81 $begin->execute($c);
fbcc39ad 82 $error++ if scalar @{ $c->error };
1abd6db7 83 }
84
85 # Execute the auto chain
1196a46d 86 my $autorun = 0;
cfd04b0c 87 for my $auto ( @{ $actions{auto} } ) {
fbcc39ad 88 last if $error;
9ddd9d05 89 $autorun++;
cfd04b0c 90 $auto->execute($c);
fbcc39ad 91 $error++ if scalar @{ $c->error };
1abd6db7 92 last unless $c->state;
93 }
94
95 # Execute the action or last default
e5f21aa2 96 my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
78d760bb 97 if ($mkay) {
fbcc39ad 98 unless ($error) {
66e28e3f 99 $c->action->execute($c);
100 $error++ if scalar @{ $c->error };
1abd6db7 101 }
102 }
103
104 # Execute last end
cfd04b0c 105 if ( my $end = @{ $actions{end} }[-1] ) {
106 $end->execute($c);
1abd6db7 107 }
fbcc39ad 108 }
109
110 else {
1abd6db7 111 my $path = $c->req->path;
112 my $error = $path
113 ? qq/Unknown resource "$path"/
114 : "No default action defined";
115 $c->log->error($error) if $c->debug;
116 $c->error($error);
117 }
118}
119
fbcc39ad 120=item $self->forward( $c, $command [, \@arguments ] )
1abd6db7 121
122=cut
123
124sub forward {
fbcc39ad 125 my $self = shift;
1abd6db7 126 my $c = shift;
127 my $command = shift;
99fe1710 128
1abd6db7 129 unless ($command) {
130 $c->log->debug('Nothing to forward to') if $c->debug;
131 return 0;
132 }
99fe1710 133
71c3bcc3 134 # Relative forwards from detach
fbcc39ad 135 my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
136 && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
71c3bcc3 137
e0fc6749 138 my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
99fe1710 139
fbcc39ad 140 my $results = [];
141
8199eac3 142 my $command_copy = $command;
143
144 unless ( $command_copy =~ s/^\/// ) {
5d68b17b 145 my $namespace =
78d760bb 146 Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
147 || '';
5d68b17b 148 $command_copy = "${namespace}/${command}";
1abd6db7 149 }
99fe1710 150
8199eac3 151 unless ( $command_copy =~ /\// ) {
152 $results = $c->get_action( $command_copy, '/' );
153 }
e494bd6b 154 else {
8199eac3 155 my @extra_args;
156 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
157 my $tail = $2;
158 $results = $c->get_action( $tail, $1 );
159 if ( @{$results} ) {
160 $command = $tail;
161 push( @{$arguments}, @extra_args );
162 last DESCEND;
163 }
164 unshift( @extra_args, $tail );
165 }
e494bd6b 166 }
99fe1710 167
1abd6db7 168 unless ( @{$results} ) {
bd7d2e94 169
fbcc39ad 170 unless ( $c->components->{$command} ) {
bd7d2e94 171 my $error =
172qq/Couldn't forward to command "$command". Invalid action or component./;
3b2ed580 173 $c->error($error);
174 $c->log->debug($error) if $c->debug;
1abd6db7 175 return 0;
176 }
bd7d2e94 177
1f6bb799 178 my $class = $command;
1abd6db7 179 my $method = shift || 'process';
99fe1710 180
1f6bb799 181 if ( my $code = $c->components->{$class}->can($method) ) {
fbcc39ad 182 my $action = Catalyst::Action->new(
183 {
6b239949 184 name => $method,
fbcc39ad 185 code => $code,
186 reverse => "$class->$method",
187 namespace => $class,
cfd04b0c 188 prefix => $class,
fbcc39ad 189 }
190 );
191 $results = [ [$action] ];
192 }
193
194 else {
bd7d2e94 195 my $error =
196 qq/Couldn't forward to "$class". Does not implement "$method"/;
3b2ed580 197 $c->error($error);
198 $c->log->debug($error)
1abd6db7 199 if $c->debug;
200 return 0;
201 }
99fe1710 202
1abd6db7 203 }
bd7d2e94 204
205 local $c->request->{arguments} = [ @{$arguments} ];
99fe1710 206
1abd6db7 207 for my $result ( @{$results} ) {
fbcc39ad 208 $result->[0]->execute($c);
e0fc6749 209 return if scalar @{ $c->error };
1abd6db7 210 last unless $c->state;
211 }
99fe1710 212
1abd6db7 213 return $c->state;
214}
215
fbcc39ad 216=item $self->prepare_action($c)
217
218=cut
219
220sub prepare_action {
221 my ( $self, $c ) = @_;
222 my $path = $c->req->path;
223 my @path = split /\//, $c->req->path;
224 $c->req->args( \my @args );
225
78d760bb 226 push( @path, '/' ) unless @path; # Root action
227
b96f127f 228 DESCEND: while (@path) {
fbcc39ad 229 $path = join '/', @path;
fbcc39ad 230
78d760bb 231 $path = '' if $path eq '/'; # Root action
232
22f3a8dd 233 # Check out dispatch types to see if any will handle the path at
234 # this level
235
78d760bb 236 foreach my $type ( @{ $self->dispatch_types } ) {
2633d7dc 237 last DESCEND if $type->match( $c, $path );
66e28e3f 238 }
b96f127f 239
22f3a8dd 240 # If not, move the last part path to args
241
b96f127f 242 unshift @args, pop @path;
fbcc39ad 243 }
244
245 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
246 if ( $c->debug && @args );
247}
248
249=item $self->get_action( $c, $action, $namespace, $inherit )
1abd6db7 250
251=cut
252
253sub get_action {
fbcc39ad 254 my ( $self, $c, $action, $namespace, $inherit ) = @_;
1abd6db7 255 return [] unless $action;
bcccee4e 256 $namespace ||= '';
2d16b61a 257 $inherit ||= 0;
99fe1710 258
78d760bb 259 my @match = $self->get_containers($namespace);
c8d9780f 260
78d760bb 261 my @results;
99fe1710 262
78d760bb 263 foreach my $child ( $inherit ? @match : $match[-1] ) {
264 my $node = $child->actions;
f3d0bbcf 265 if ( defined $node->{$action} ) {
266 unless ($inherit) {
267 $namespace = '' if $namespace eq '/';
268 my $reverse = $node->{$action}->reverse;
269 my $name = $namespace
270 ? $namespace =~ /\/$/
271 ? "$namespace$action"
272 : "$namespace/$action"
273 : $action;
274 last unless $name eq $reverse;
275 }
276 push( @results, [ $node->{$action} ] );
bcccee4e 277 }
1abd6db7 278 }
78d760bb 279 return \@results;
1abd6db7 280}
281
cfd04b0c 282=item $self->get_containers( $namespace )
283
284=cut
285
286sub get_containers {
287 my ( $self, $namespace ) = @_;
288
90ce41ba 289 # If the namespace is / just return the root ActionContainer
290
78d760bb 291 return ( $self->tree->getNodeValue )
292 if ( !$namespace || ( $namespace eq '/' ) );
cfd04b0c 293
90ce41ba 294 # Use a visitor to recurse down the tree finding the ActionContainers
295 # for each namespace in the chain.
296
cfd04b0c 297 my $visitor = Tree::Simple::Visitor::FindByPath->new;
78d760bb 298 my @path = split( '/', $namespace );
299 $visitor->setSearchPath(@path);
cfd04b0c 300 $self->tree->accept($visitor);
301
302 my @match = $visitor->getResults;
78d760bb 303 @match = ( $self->tree ) unless @match;
cfd04b0c 304
78d760bb 305 if ( !defined $visitor->getResult ) {
90ce41ba 306
307 # If we don't manage to match, the visitor doesn't return the last
308 # node is matched, so foo/bar/baz would only find the 'foo' node,
309 # not the foo and foo/bar nodes as it should. This does another
310 # single-level search to see if that's the case, and the 'last unless'
311 # should catch any failures - or short-circuit this if this *is* a
312 # bug in the visitor and gets fixed.
313
78d760bb 314 my $extra = $path[ ( scalar @match ) - 1 ];
cfd04b0c 315 last unless $extra;
316 $visitor->setSearchPath($extra);
317 $match[-1]->accept($visitor);
78d760bb 318 push( @match, $visitor->getResult ) if defined $visitor->getResult;
cfd04b0c 319 }
320
321 return map { $_->getNodeValue } @match;
322}
323
fbcc39ad 324=item $self->set_action( $c, $action, $code, $namespace, $attrs )
1abd6db7 325
326=cut
327
328sub set_action {
fbcc39ad 329 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
1abd6db7 330
e494bd6b 331 my $prefix =
332 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
333 || '';
b96f127f 334 my %attributes;
1abd6db7 335
336 for my $attr ( @{$attrs} ) {
22f3a8dd 337
338 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
339
6d030e6f 340 my %initialized;
341 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
342
78d760bb 343 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
6d030e6f 344
345 # Initialize types
346 my $class = "Catalyst::DispatchType::$key";
347 unless ( $initialized{$class} ) {
348 eval "require $class";
349 push( @{ $self->dispatch_types }, $class->new ) unless $@;
350 $initialized{$class}++;
351 }
352
b96f127f 353 if ( defined $value ) {
78d760bb 354 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
b96f127f 355 }
78d760bb 356 push( @{ $attributes{$key} }, $value );
b96f127f 357 }
1abd6db7 358 }
359
6b239949 360 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
8d4e224b 361 $c->log->debug( 'Bad action definition "'
d0e524d2 362 . join( ' ', @{$attrs} )
8d4e224b 363 . qq/" for "$namespace->$method"/ )
364 if $c->debug;
d0e524d2 365 return;
366 }
6b239949 367 return unless keys %attributes;
1abd6db7 368
fbcc39ad 369 my $parent = $self->tree;
1abd6db7 370 my $visitor = Tree::Simple::Visitor::FindByPath->new;
99fe1710 371
b7aebc12 372 if ($prefix) {
373 for my $part ( split '/', $prefix ) {
1abd6db7 374 $visitor->setSearchPath($part);
375 $parent->accept($visitor);
b7aebc12 376 my $child = $visitor->getResult;
78d760bb 377
b7aebc12 378 unless ($child) {
90ce41ba 379
380 # Create a new tree node and an ActionContainer to form
381 # its value.
382
78d760bb 383 my $container =
384 Catalyst::ActionContainer->new(
385 { part => $part, actions => {} } );
b7aebc12 386 $child = $parent->addChild( Tree::Simple->new($container) );
387 $visitor->setSearchPath($part);
388 $parent->accept($visitor);
389 $child = $visitor->getResult;
390 }
78d760bb 391
b7aebc12 392 $parent = $child;
1abd6db7 393 }
1abd6db7 394 }
99fe1710 395
fbcc39ad 396 my $reverse = $prefix ? "$prefix/$method" : $method;
397
398 my $action = Catalyst::Action->new(
399 {
6b239949 400 name => $method,
b96f127f 401 code => $code,
402 reverse => $reverse,
403 namespace => $namespace,
404 prefix => $prefix,
405 attributes => \%attributes,
fbcc39ad 406 }
407 );
408
90ce41ba 409 # Set the method value
b7aebc12 410 $parent->getNodeValue->actions->{$method} = $action;
fbcc39ad 411
22f3a8dd 412 # Pass the action to our dispatch types so they can register it if reqd.
b96f127f 413 foreach my $type ( @{ $self->dispatch_types } ) {
2633d7dc 414 $type->register( $c, $action );
b96f127f 415 }
1abd6db7 416}
417
fbcc39ad 418=item $self->setup_actions( $class, $component )
1abd6db7 419
420=cut
421
422sub setup_actions {
fbcc39ad 423 my ( $self, $class ) = @_;
99fe1710 424
6d030e6f 425 $self->dispatch_types( [] );
12e28165 426
6d030e6f 427 # Preload action types
428 for my $type (@PRELOAD) {
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 }
b96f127f 435
12e28165 436 # We use a tree
78d760bb 437 my $container =
438 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
b7aebc12 439 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
e494bd6b 440
fbcc39ad 441 for my $comp ( keys %{ $class->components } ) {
e494bd6b 442
443 # We only setup components that inherit from Catalyst::Base
a268a011 444 next unless $comp->isa('Catalyst::Base');
99fe1710 445
812a28c9 446 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
1abd6db7 447 my ( $code, $attrs ) = @{$action};
448 my $name = '';
449 no strict 'refs';
450 my @cache = ( $comp, @{"$comp\::ISA"} );
451 my %namespaces;
99fe1710 452
1abd6db7 453 while ( my $namespace = shift @cache ) {
454 $namespaces{$namespace}++;
455 for my $isa ( @{"$comp\::ISA"} ) {
456 next if $namespaces{$isa};
457 push @cache, $isa;
458 $namespaces{$isa}++;
459 }
460 }
99fe1710 461
1abd6db7 462 for my $namespace ( keys %namespaces ) {
463 for my $sym ( values %{ $namespace . '::' } ) {
464 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
465 $name = *{$sym}{NAME};
fbcc39ad 466 $class->set_action( $name, $code, $comp, $attrs );
1abd6db7 467 last;
468 }
469 }
470 }
471 }
472 }
e494bd6b 473
2d1d8f91 474 # Postload action types
475 for my $type (@POSTLOAD) {
476 my $class = "Catalyst::DispatchType::$type";
477 eval "require $class";
478 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
479 if $@;
480 push @{ $self->dispatch_types }, $class->new;
481 }
6d030e6f 482
fbcc39ad 483 return unless $class->debug;
99fe1710 484
1abd6db7 485 my $privates = Text::ASCIITable->new;
5fbed090 486 $privates->setCols( 'Private', 'Class' );
487 $privates->setColWidth( 'Private', 36, 1 );
488 $privates->setColWidth( 'Class', 37, 1 );
99fe1710 489
1abd6db7 490 my $walker = sub {
491 my ( $walker, $parent, $prefix ) = @_;
492 $prefix .= $parent->getNodeValue || '';
493 $prefix .= '/' unless $prefix =~ /\/$/;
b7aebc12 494 my $node = $parent->getNodeValue->actions;
99fe1710 495
78d760bb 496 for my $action ( keys %{$node} ) {
b7aebc12 497 my $action_obj = $node->{$action};
fbcc39ad 498 $privates->addRow( "$prefix$action", $action_obj->namespace );
1abd6db7 499 }
99fe1710 500
1abd6db7 501 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
502 };
99fe1710 503
1abd6db7 504 $walker->( $walker, $self->tree, '' );
a9cbd748 505 $class->log->debug( "Loaded Private actions:\n" . $privates->draw )
a268a011 506 if ( @{ $privates->{tbl_rows} } );
99fe1710 507
a9cbd748 508 # List all public actions
509 $_->list($class) for @{ $self->dispatch_types };
1abd6db7 510}
511
1abd6db7 512=back
513
514=head1 AUTHOR
515
516Sebastian Riedel, C<sri@cpan.org>
517
518=head1 COPYRIGHT
519
520This program is free software, you can redistribute it and/or modify it under
521the same terms as Perl itself.
522
523=cut
524
5251;