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