- Shifted Path dispatch into a DispatchType and nuked old set_action stuff
[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
6b239949 224 foreach my $type (@{$self->dispatch_types}) {
225 last DESCEND if $type->prepare_action($c, $path);
66e28e3f 226 }
b96f127f 227
228 unshift @args, pop @path;
fbcc39ad 229 }
230
231 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
232 if ( $c->debug && @args );
233}
234
235=item $self->get_action( $c, $action, $namespace, $inherit )
1abd6db7 236
237=cut
238
239sub get_action {
fbcc39ad 240 my ( $self, $c, $action, $namespace, $inherit ) = @_;
1abd6db7 241 return [] unless $action;
242 $namespace ||= '';
2d16b61a 243 $inherit ||= 0;
99fe1710 244
1abd6db7 245 if ($namespace) {
c8d9780f 246
cfd04b0c 247 my @match = $self->get_containers( $namespace );
99fe1710 248
c8d9780f 249 my @results;
99fe1710 250
cfd04b0c 251 foreach my $child ($inherit ? @match: $match[-1]) {
252 my $node = $child->actions;
c8d9780f 253 push(@results, [ $node->{$action} ]) if defined $node->{$action};
1abd6db7 254 }
255 return \@results;
256 }
99fe1710 257
1abd6db7 258 return [];
259}
260
cfd04b0c 261=item $self->get_containers( $namespace )
262
263=cut
264
265sub get_containers {
266 my ( $self, $namespace ) = @_;
267
90ce41ba 268 # If the namespace is / just return the root ActionContainer
269
cfd04b0c 270 return ($self->tree->getNodeValue) if $namespace eq '/';
271
90ce41ba 272 # Use a visitor to recurse down the tree finding the ActionContainers
273 # for each namespace in the chain.
274
cfd04b0c 275 my $visitor = Tree::Simple::Visitor::FindByPath->new;
276 my @path = split('/', $namespace);
277 $visitor->setSearchPath( @path );
278 $self->tree->accept($visitor);
279
280 my @match = $visitor->getResults;
281 @match = ($self->tree) unless @match;
282
283 if (!defined $visitor->getResult) {
90ce41ba 284
285 # If we don't manage to match, the visitor doesn't return the last
286 # node is matched, so foo/bar/baz would only find the 'foo' node,
287 # not the foo and foo/bar nodes as it should. This does another
288 # single-level search to see if that's the case, and the 'last unless'
289 # should catch any failures - or short-circuit this if this *is* a
290 # bug in the visitor and gets fixed.
291
cfd04b0c 292 my $extra = $path[(scalar @match) - 1];
293 last unless $extra;
294 $visitor->setSearchPath($extra);
295 $match[-1]->accept($visitor);
296 push(@match, $visitor->getResult) if defined $visitor->getResult;
297 }
298
299 return map { $_->getNodeValue } @match;
300}
301
fbcc39ad 302=item $self->set_action( $c, $action, $code, $namespace, $attrs )
1abd6db7 303
304=cut
305
306sub set_action {
fbcc39ad 307 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
1abd6db7 308
e494bd6b 309 my $prefix =
310 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
311 || '';
b96f127f 312 my %attributes;
1abd6db7 313
314 for my $attr ( @{$attrs} ) {
b96f127f 315 if ( my ($key, $value) = ($attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/) ) {
316 if ( defined $value ) {
317 ($value =~ s/^'(.*)'$/$1/) || ($value =~ s/^"(.*)"/$1/);
318 }
319 push(@{$attributes{$key}}, $value);
320 }
1abd6db7 321 }
322
6b239949 323 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
8d4e224b 324 $c->log->debug( 'Bad action definition "'
d0e524d2 325 . join( ' ', @{$attrs} )
8d4e224b 326 . qq/" for "$namespace->$method"/ )
327 if $c->debug;
d0e524d2 328 return;
329 }
6b239949 330 return unless keys %attributes;
1abd6db7 331
fbcc39ad 332 my $parent = $self->tree;
1abd6db7 333 my $visitor = Tree::Simple::Visitor::FindByPath->new;
99fe1710 334
b7aebc12 335 if ($prefix) {
336 for my $part ( split '/', $prefix ) {
1abd6db7 337 $visitor->setSearchPath($part);
338 $parent->accept($visitor);
b7aebc12 339 my $child = $visitor->getResult;
340
341 unless ($child) {
90ce41ba 342
343 # Create a new tree node and an ActionContainer to form
344 # its value.
345
b7aebc12 346 my $container = Catalyst::ActionContainer->new(
347 { part => $part, actions => {} });
348 $child = $parent->addChild( Tree::Simple->new($container) );
349 $visitor->setSearchPath($part);
350 $parent->accept($visitor);
351 $child = $visitor->getResult;
352 }
353
354 $parent = $child;
1abd6db7 355 }
1abd6db7 356 }
99fe1710 357
fbcc39ad 358 my $reverse = $prefix ? "$prefix/$method" : $method;
359
360 my $action = Catalyst::Action->new(
361 {
6b239949 362 name => $method,
b96f127f 363 code => $code,
364 reverse => $reverse,
365 namespace => $namespace,
366 prefix => $prefix,
367 attributes => \%attributes,
fbcc39ad 368 }
369 );
370
90ce41ba 371 # Set the method value
b7aebc12 372 $parent->getNodeValue->actions->{$method} = $action;
fbcc39ad 373
b96f127f 374 foreach my $type ( @{ $self->dispatch_types } ) {
375 $type->register_action($c, $action);
376 }
1abd6db7 377}
378
fbcc39ad 379=item $self->setup_actions( $class, $component )
1abd6db7 380
381=cut
382
383sub setup_actions {
fbcc39ad 384 my ( $self, $class ) = @_;
99fe1710 385
12e28165 386 # These are the core structures
387 $self->actions(
388 {
389 plain => {},
390 private => {},
391 regex => {},
fbcc39ad 392 compiled => []
12e28165 393 }
394 );
395
b96f127f 396 $self->dispatch_types([
397 map { "Catalyst::DispatchType::$_"->new }
6b239949 398 qw/Path Regex Default/ ]);
b96f127f 399
12e28165 400 # We use a tree
b7aebc12 401 my $container = Catalyst::ActionContainer->new(
402 { part => '/', actions => {} } );
403 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
e494bd6b 404
fbcc39ad 405 for my $comp ( keys %{ $class->components } ) {
e494bd6b 406
407 # We only setup components that inherit from Catalyst::Base
a268a011 408 next unless $comp->isa('Catalyst::Base');
99fe1710 409
812a28c9 410 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
1abd6db7 411 my ( $code, $attrs ) = @{$action};
412 my $name = '';
413 no strict 'refs';
414 my @cache = ( $comp, @{"$comp\::ISA"} );
415 my %namespaces;
99fe1710 416
1abd6db7 417 while ( my $namespace = shift @cache ) {
418 $namespaces{$namespace}++;
419 for my $isa ( @{"$comp\::ISA"} ) {
420 next if $namespaces{$isa};
421 push @cache, $isa;
422 $namespaces{$isa}++;
423 }
424 }
99fe1710 425
1abd6db7 426 for my $namespace ( keys %namespaces ) {
99fe1710 427
1abd6db7 428 for my $sym ( values %{ $namespace . '::' } ) {
99fe1710 429
1abd6db7 430 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
99fe1710 431
1abd6db7 432 $name = *{$sym}{NAME};
fbcc39ad 433 $class->set_action( $name, $code, $comp, $attrs );
1abd6db7 434 last;
435 }
99fe1710 436
1abd6db7 437 }
99fe1710 438
1abd6db7 439 }
99fe1710 440
1abd6db7 441 }
99fe1710 442
1abd6db7 443 }
e494bd6b 444
fbcc39ad 445 return unless $class->debug;
99fe1710 446
1abd6db7 447 my $actions = $self->actions;
448 my $privates = Text::ASCIITable->new;
5fbed090 449 $privates->setCols( 'Private', 'Class' );
450 $privates->setColWidth( 'Private', 36, 1 );
451 $privates->setColWidth( 'Class', 37, 1 );
99fe1710 452
1abd6db7 453 my $walker = sub {
454 my ( $walker, $parent, $prefix ) = @_;
455 $prefix .= $parent->getNodeValue || '';
456 $prefix .= '/' unless $prefix =~ /\/$/;
b7aebc12 457 my $node = $parent->getNodeValue->actions;
99fe1710 458
b7aebc12 459 for my $action ( keys %{ $node } ) {
460 my $action_obj = $node->{$action};
fbcc39ad 461 $privates->addRow( "$prefix$action", $action_obj->namespace );
1abd6db7 462 }
99fe1710 463
1abd6db7 464 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
465 };
99fe1710 466
1abd6db7 467 $walker->( $walker, $self->tree, '' );
fbcc39ad 468 $class->log->debug( "Loaded private actions:\n" . $privates->draw )
a268a011 469 if ( @{ $privates->{tbl_rows} } );
99fe1710 470
1abd6db7 471 my $publics = Text::ASCIITable->new;
472 $publics->setCols( 'Public', 'Private' );
699e1247 473 $publics->setColWidth( 'Public', 36, 1 );
474 $publics->setColWidth( 'Private', 37, 1 );
99fe1710 475
1abd6db7 476 for my $plain ( sort keys %{ $actions->{plain} } ) {
fbcc39ad 477 my $action = $actions->{plain}->{$plain};
478 $publics->addRow( "/$plain", "/$action" );
1abd6db7 479 }
99fe1710 480
fbcc39ad 481 $class->log->debug( "Loaded public actions:\n" . $publics->draw )
a268a011 482 if ( @{ $publics->{tbl_rows} } );
99fe1710 483
1abd6db7 484 my $regexes = Text::ASCIITable->new;
485 $regexes->setCols( 'Regex', 'Private' );
699e1247 486 $regexes->setColWidth( 'Regex', 36, 1 );
487 $regexes->setColWidth( 'Private', 37, 1 );
99fe1710 488
1abd6db7 489 for my $regex ( sort keys %{ $actions->{regex} } ) {
fbcc39ad 490 my $action = $actions->{regex}->{$regex};
491 $regexes->addRow( $regex, "/$action" );
1abd6db7 492 }
99fe1710 493
fbcc39ad 494 $class->log->debug( "Loaded regex actions:\n" . $regexes->draw )
a268a011 495 if ( @{ $regexes->{tbl_rows} } );
1abd6db7 496}
497
1abd6db7 498=back
499
500=head1 AUTHOR
501
502Sebastian Riedel, C<sri@cpan.org>
503
504=head1 COPYRIGHT
505
506This program is free software, you can redistribute it and/or modify it under
507the same terms as Perl itself.
508
509=cut
510
5111;