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