- Dispatcher refactor, part trois
[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;
1abd6db7 9use Text::ASCIITable;
1abd6db7 10use Tree::Simple;
11use Tree::Simple::Visitor::FindByPath;
12
fbcc39ad 13# Stringify to class
14use overload '""' => sub { return ref shift }, fallback => 1;
15
16__PACKAGE__->mk_accessors(qw/actions tree/);
1abd6db7 17
1abd6db7 18=head1 NAME
19
9c053379 20Catalyst::Dispatcher - The Catalyst Dispatcher
1abd6db7 21
22=head1 SYNOPSIS
23
24See L<Catalyst>.
25
26=head1 DESCRIPTION
27
28=head1 METHODS
29
30=over 4
31
fbcc39ad 32=item $self->detach( $c, $command [, \@arguments ] )
6ef62eb2 33
34=cut
35
36sub detach {
fbcc39ad 37 my ( $self, $c, $command, @args ) = @_;
bd7d2e94 38 $c->forward( $command, @args ) if $command;
fbcc39ad 39 die $Catalyst::DETACH;
6ef62eb2 40}
41
fbcc39ad 42=item $self->dispatch($c)
1abd6db7 43
44=cut
45
46sub dispatch {
fbcc39ad 47 my ( $self, $c ) = @_;
1abd6db7 48 my $action = $c->req->action;
49 my $namespace = '';
50 $namespace = ( join( '/', @{ $c->req->args } ) || '/' )
51 if $action eq 'default';
99fe1710 52
1abd6db7 53 unless ($namespace) {
54 if ( my $result = $c->get_action($action) ) {
fbcc39ad 55 $namespace =
56 Catalyst::Utils::class2prefix( $result->[0]->[0]->namespace,
e494bd6b 57 $c->config->{case_sensitive} );
1abd6db7 58 }
59 }
99fe1710 60
1abd6db7 61 my $default = $action eq 'default' ? $namespace : undef;
2d16b61a 62 my $results = $c->get_action( $action, $default, $default ? 1 : 0 );
1abd6db7 63 $namespace ||= '/';
99fe1710 64
1abd6db7 65 if ( @{$results} ) {
66
fbcc39ad 67 # Errors break the normal flow and the end action is instantly run
68 my $error = 0;
69
1abd6db7 70 # Execute last begin
71 $c->state(1);
2d16b61a 72 if ( my $begin = @{ $c->get_action( 'begin', $namespace, 1 ) }[-1] ) {
fbcc39ad 73 $begin->[0]->execute($c);
74 $error++ if scalar @{ $c->error };
1abd6db7 75 }
76
77 # Execute the auto chain
1196a46d 78 my $autorun = 0;
9ddd9d05 79 for my $auto ( @{ $c->get_action( 'auto', $namespace, 1 ) } ) {
fbcc39ad 80 last if $error;
9ddd9d05 81 $autorun++;
fbcc39ad 82 $auto->[0]->execute($c);
83 $error++ if scalar @{ $c->error };
1abd6db7 84 last unless $c->state;
85 }
86
87 # Execute the action or last default
e5f21aa2 88 my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
61cfdd57 89 if ( ( my $action = $c->req->action ) && $mkay ) {
fbcc39ad 90 unless ($error) {
91 if ( my $result =
92 @{ $c->get_action( $action, $default, 1 ) }[-1] )
93 {
94 $result->[0]->execute($c);
95 $error++ if scalar @{ $c->error };
96 }
1abd6db7 97 }
98 }
99
100 # Execute last end
2d16b61a 101 if ( my $end = @{ $c->get_action( 'end', $namespace, 1 ) }[-1] ) {
fbcc39ad 102 $end->[0]->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 {
179 code => $code,
180 reverse => "$class->$method",
181 namespace => $class,
182 }
183 );
184 $results = [ [$action] ];
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
198 local $c->request->{arguments} = [ @{$arguments} ];
99fe1710 199
1abd6db7 200 for my $result ( @{$results} ) {
fbcc39ad 201 $result->[0]->execute($c);
e0fc6749 202 return if scalar @{ $c->error };
1abd6db7 203 last unless $c->state;
204 }
99fe1710 205
1abd6db7 206 return $c->state;
207}
208
fbcc39ad 209=item $self->prepare_action($c)
210
211=cut
212
213sub prepare_action {
214 my ( $self, $c ) = @_;
215 my $path = $c->req->path;
216 my @path = split /\//, $c->req->path;
217 $c->req->args( \my @args );
218
219 while (@path) {
220 $path = join '/', @path;
221 if ( my $result = ${ $c->get_action($path) }[0] ) {
222
223 # It's a regex
224 if ($#$result) {
225 my $match = $result->[1];
226 my @snippets = @{ $result->[2] };
227 $c->log->debug(
228 qq/Requested action is "$path" and matched "$match"/)
229 if $c->debug;
230 $c->log->debug(
231 'Snippets are "' . join( ' ', @snippets ) . '"' )
232 if ( $c->debug && @snippets );
233 $c->req->action($match);
234 $c->req->snippets( \@snippets );
235 }
236
237 else {
238 $c->req->action($path);
239 $c->log->debug(qq/Requested action is "$path"/) if $c->debug;
240 }
1abd6db7 241
fbcc39ad 242 $c->req->match($path);
243 last;
244 }
245 unshift @args, pop @path;
246 }
247
248 unless ( $c->req->action ) {
249 $c->req->action('default');
250 $c->req->match('');
251 }
252
253 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
254 if ( $c->debug && @args );
255}
256
257=item $self->get_action( $c, $action, $namespace, $inherit )
1abd6db7 258
259=cut
260
261sub get_action {
fbcc39ad 262 my ( $self, $c, $action, $namespace, $inherit ) = @_;
1abd6db7 263 return [] unless $action;
264 $namespace ||= '';
2d16b61a 265 $inherit ||= 0;
99fe1710 266
1abd6db7 267 if ($namespace) {
c8d9780f 268
fbcc39ad 269 my $parent = $self->tree;
c8d9780f 270 my @match;
99fe1710 271
c8d9780f 272 if ($namespace ne '/') {
99fe1710 273
c8d9780f 274 my $visitor = Tree::Simple::Visitor::FindByPath->new;
275 my @path = split('/', $namespace);
d1b0d31d 276 $visitor->setSearchPath( @path );
277 $parent->accept($visitor);
278
c8d9780f 279 if ($inherit) {
d1b0d31d 280
c8d9780f 281 @match = $visitor->getResults;
282 @match = ($parent) unless @match;
d1b0d31d 283
c8d9780f 284 if (!defined $visitor->getResult) {
285 my $extra = $path[(scalar @match) - 1];
286 last unless $extra;
287 $visitor->setSearchPath($extra);
288 $match[-1]->accept($visitor);
289 push(@match, $visitor->getResult) if defined $visitor->getResult;
290 }
291 } else {
292 @match = ($visitor->getResult) if $visitor->getResult;
d1b0d31d 293 }
294
1abd6db7 295 }
99fe1710 296
c8d9780f 297 @match = ($parent) unless @match;
99fe1710 298
c8d9780f 299 my @results;
99fe1710 300
c8d9780f 301 foreach my $child (@match) {
b7aebc12 302 my $node = $child->getNodeValue->actions;
c8d9780f 303 push(@results, [ $node->{$action} ]) if defined $node->{$action};
1abd6db7 304 }
305 return \@results;
306 }
99fe1710 307
fbcc39ad 308 elsif ( my $p = $self->actions->{plain}->{$action} ) { return [ [$p] ] }
309 elsif ( my $r = $self->actions->{regex}->{$action} ) { return [ [$r] ] }
99fe1710 310
1abd6db7 311 else {
99fe1710 312
fbcc39ad 313 for my $i ( 0 .. $#{ $self->actions->{compiled} } ) {
314 my $name = $self->actions->{compiled}->[$i]->[0];
315 my $regex = $self->actions->{compiled}->[$i]->[1];
99fe1710 316
2d752b2a 317 if ( my @snippets = ( $action =~ $regex ) ) {
fbcc39ad 318 return [
319 [ $self->actions->{regex}->{$name}, $name, \@snippets ] ];
1abd6db7 320 }
99fe1710 321
1abd6db7 322 }
323 }
324 return [];
325}
326
fbcc39ad 327=item $self->set_action( $c, $action, $code, $namespace, $attrs )
1abd6db7 328
329=cut
330
331sub set_action {
fbcc39ad 332 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
1abd6db7 333
e494bd6b 334 my $prefix =
335 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
336 || '';
1abd6db7 337 my %flags;
338
339 for my $attr ( @{$attrs} ) {
0299ba22 340 if ( $attr =~ /^(Local|Relative)$/ ) { $flags{local}++ }
341 elsif ( $attr =~ /^(Global|Absolute)$/ ) { $flags{global}++ }
749472d6 342 elsif ( $attr =~ /^Path\(\s*(.+)\s*\)$/i ) {
343 push @{ $flags{path} }, $1;
344 }
345 elsif ( $attr =~ /^Private$/i ) { $flags{private}++ }
0299ba22 346 elsif ( $attr =~ /^(Regex|Regexp)\(\s*(.+)\s*\)$/i ) {
749472d6 347 push @{ $flags{regex} }, $2;
0299ba22 348 }
1abd6db7 349 }
350
d0e524d2 351 if ( $flags{private} && ( keys %flags > 1 ) ) {
8d4e224b 352 $c->log->debug( 'Bad action definition "'
d0e524d2 353 . join( ' ', @{$attrs} )
8d4e224b 354 . qq/" for "$namespace->$method"/ )
355 if $c->debug;
d0e524d2 356 return;
357 }
1abd6db7 358 return unless keys %flags;
359
fbcc39ad 360 my $parent = $self->tree;
1abd6db7 361 my $visitor = Tree::Simple::Visitor::FindByPath->new;
99fe1710 362
b7aebc12 363 if ($prefix) {
364 for my $part ( split '/', $prefix ) {
1abd6db7 365 $visitor->setSearchPath($part);
366 $parent->accept($visitor);
b7aebc12 367 my $child = $visitor->getResult;
368
369 unless ($child) {
370 my $container = Catalyst::ActionContainer->new(
371 { part => $part, actions => {} });
372 $child = $parent->addChild( Tree::Simple->new($container) );
373 $visitor->setSearchPath($part);
374 $parent->accept($visitor);
375 $child = $visitor->getResult;
376 }
377
378 $parent = $child;
1abd6db7 379 }
1abd6db7 380 }
99fe1710 381
fbcc39ad 382 my $reverse = $prefix ? "$prefix/$method" : $method;
383
384 my $action = Catalyst::Action->new(
385 {
386 code => $code,
387 reverse => $reverse,
388 namespace => $namespace,
389 }
390 );
391
b7aebc12 392 $parent->getNodeValue->actions->{$method} = $action;
fbcc39ad 393
749472d6 394 my @path;
395 for my $path ( @{ $flags{path} } ) {
396 $path =~ s/^\w+//;
397 $path =~ s/\w+$//;
398 if ( $path =~ /^\s*'(.*)'\s*$/ ) { $path = $1 }
399 if ( $path =~ /^\s*"(.*)"\s*$/ ) { $path = $1 }
400 push @path, $path;
1abd6db7 401 }
749472d6 402 $flags{path} = \@path;
403
404 my @regex;
405 for my $regex ( @{ $flags{regex} } ) {
406 $regex =~ s/^\w+//;
407 $regex =~ s/\w+$//;
408 if ( $regex =~ /^\s*'(.*)'\s*$/ ) { $regex = $1 }
409 if ( $regex =~ /^\s*"(.*)"\s*$/ ) { $regex = $1 }
410 push @regex, $regex;
1abd6db7 411 }
749472d6 412 $flags{regex} = \@regex;
1abd6db7 413
749472d6 414 if ( $flags{local} || $flags{global} ) {
415 push( @{ $flags{path} }, $prefix ? "/$prefix/$method" : "/$method" )
416 if $flags{local};
99fe1710 417
749472d6 418 push( @{ $flags{path} }, "/$method" ) if $flags{global};
419 }
99fe1710 420
749472d6 421 for my $path ( @{ $flags{path} } ) {
422 if ( $path =~ /^\// ) { $path =~ s/^\/// }
423 else { $path = $prefix ? "$prefix/$path" : $path }
424 $self->actions->{plain}->{$path} = $action;
1abd6db7 425 }
99fe1710 426
749472d6 427 for my $regex ( @{ $flags{regex} } ) {
fbcc39ad 428 push @{ $self->actions->{compiled} }, [ $regex, qr#$regex# ];
429 $self->actions->{regex}->{$regex} = $action;
1abd6db7 430 }
1abd6db7 431}
432
fbcc39ad 433=item $self->setup_actions( $class, $component )
1abd6db7 434
435=cut
436
437sub setup_actions {
fbcc39ad 438 my ( $self, $class ) = @_;
99fe1710 439
12e28165 440 # These are the core structures
441 $self->actions(
442 {
443 plain => {},
444 private => {},
445 regex => {},
fbcc39ad 446 compiled => []
12e28165 447 }
448 );
449
450 # We use a tree
b7aebc12 451 my $container = Catalyst::ActionContainer->new(
452 { part => '/', actions => {} } );
453 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
e494bd6b 454
fbcc39ad 455 for my $comp ( keys %{ $class->components } ) {
e494bd6b 456
457 # We only setup components that inherit from Catalyst::Base
a268a011 458 next unless $comp->isa('Catalyst::Base');
99fe1710 459
812a28c9 460 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
1abd6db7 461 my ( $code, $attrs ) = @{$action};
462 my $name = '';
463 no strict 'refs';
464 my @cache = ( $comp, @{"$comp\::ISA"} );
465 my %namespaces;
99fe1710 466
1abd6db7 467 while ( my $namespace = shift @cache ) {
468 $namespaces{$namespace}++;
469 for my $isa ( @{"$comp\::ISA"} ) {
470 next if $namespaces{$isa};
471 push @cache, $isa;
472 $namespaces{$isa}++;
473 }
474 }
99fe1710 475
1abd6db7 476 for my $namespace ( keys %namespaces ) {
99fe1710 477
1abd6db7 478 for my $sym ( values %{ $namespace . '::' } ) {
99fe1710 479
1abd6db7 480 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
99fe1710 481
1abd6db7 482 $name = *{$sym}{NAME};
fbcc39ad 483 $class->set_action( $name, $code, $comp, $attrs );
1abd6db7 484 last;
485 }
99fe1710 486
1abd6db7 487 }
99fe1710 488
1abd6db7 489 }
99fe1710 490
1abd6db7 491 }
99fe1710 492
1abd6db7 493 }
e494bd6b 494
fbcc39ad 495 return unless $class->debug;
99fe1710 496
1abd6db7 497 my $actions = $self->actions;
498 my $privates = Text::ASCIITable->new;
5fbed090 499 $privates->setCols( 'Private', 'Class' );
500 $privates->setColWidth( 'Private', 36, 1 );
501 $privates->setColWidth( 'Class', 37, 1 );
99fe1710 502
1abd6db7 503 my $walker = sub {
504 my ( $walker, $parent, $prefix ) = @_;
505 $prefix .= $parent->getNodeValue || '';
506 $prefix .= '/' unless $prefix =~ /\/$/;
b7aebc12 507 my $node = $parent->getNodeValue->actions;
99fe1710 508
b7aebc12 509 for my $action ( keys %{ $node } ) {
510 my $action_obj = $node->{$action};
fbcc39ad 511 $privates->addRow( "$prefix$action", $action_obj->namespace );
1abd6db7 512 }
99fe1710 513
1abd6db7 514 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
515 };
99fe1710 516
1abd6db7 517 $walker->( $walker, $self->tree, '' );
fbcc39ad 518 $class->log->debug( "Loaded private actions:\n" . $privates->draw )
a268a011 519 if ( @{ $privates->{tbl_rows} } );
99fe1710 520
1abd6db7 521 my $publics = Text::ASCIITable->new;
522 $publics->setCols( 'Public', 'Private' );
699e1247 523 $publics->setColWidth( 'Public', 36, 1 );
524 $publics->setColWidth( 'Private', 37, 1 );
99fe1710 525
1abd6db7 526 for my $plain ( sort keys %{ $actions->{plain} } ) {
fbcc39ad 527 my $action = $actions->{plain}->{$plain};
528 $publics->addRow( "/$plain", "/$action" );
1abd6db7 529 }
99fe1710 530
fbcc39ad 531 $class->log->debug( "Loaded public actions:\n" . $publics->draw )
a268a011 532 if ( @{ $publics->{tbl_rows} } );
99fe1710 533
1abd6db7 534 my $regexes = Text::ASCIITable->new;
535 $regexes->setCols( 'Regex', 'Private' );
699e1247 536 $regexes->setColWidth( 'Regex', 36, 1 );
537 $regexes->setColWidth( 'Private', 37, 1 );
99fe1710 538
1abd6db7 539 for my $regex ( sort keys %{ $actions->{regex} } ) {
fbcc39ad 540 my $action = $actions->{regex}->{$regex};
541 $regexes->addRow( $regex, "/$action" );
1abd6db7 542 }
99fe1710 543
fbcc39ad 544 $class->log->debug( "Loaded regex actions:\n" . $regexes->draw )
a268a011 545 if ( @{ $regexes->{tbl_rows} } );
1abd6db7 546}
547
1abd6db7 548=back
549
550=head1 AUTHOR
551
552Sebastian Riedel, C<sri@cpan.org>
553
554=head1 COPYRIGHT
555
556This program is free software, you can redistribute it and/or modify it under
557the same terms as Perl itself.
558
559=cut
560
5611;