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