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