1 package Catalyst::Dispatcher;
4 use base 'Class::Accessor::Fast';
5 use Catalyst::Exception;
8 use Catalyst::ActionContainer;
9 use Catalyst::DispatchType::Default;
12 use Tree::Simple::Visitor::FindByPath;
15 use overload '""' => sub { return ref shift }, fallback => 1;
17 __PACKAGE__->mk_accessors(qw/tree dispatch_types/);
19 # Preload these action types
20 our @PRELOAD = qw/Path Regex/;
24 Catalyst::Dispatcher - The Catalyst Dispatcher
36 =item $self->detach( $c, $command [, \@arguments ] )
41 my ( $self, $c, $command, @args ) = @_;
42 $c->forward( $command, @args ) if $command;
43 die $Catalyst::DETACH;
46 =item $self->dispatch($c)
51 my ( $self, $c ) = @_;
55 my @containers = $self->get_containers( $c->namespace );
57 foreach my $name (qw/begin auto end/) {
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
66 grep { exists $_->{$name} }
67 map { $_->actions } @containers
71 # Errors break the normal flow and the end action is instantly run
76 if ( my $begin = @{ $actions{begin} }[-1] ) {
78 $error++ if scalar @{ $c->error };
81 # Execute the auto chain
83 for my $auto ( @{ $actions{auto} } ) {
87 $error++ if scalar @{ $c->error };
88 last unless $c->state;
91 # Execute the action or last default
92 my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
95 $c->action->execute($c);
96 $error++ if scalar @{ $c->error };
101 if ( my $end = @{ $actions{end} }[-1] ) {
107 my $path = $c->req->path;
109 ? qq/Unknown resource "$path"/
110 : "No default action defined";
111 $c->log->error($error) if $c->debug;
116 =item $self->forward( $c, $command [, \@arguments ] )
126 $c->log->debug('Nothing to forward to') if $c->debug;
130 # Relative forwards from detach
131 my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
132 && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
134 my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
138 my $command_copy = $command;
140 unless ( $command_copy =~ s/^\/// ) {
142 Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
144 $command_copy = "${namespace}/${command}";
147 unless ( $command_copy =~ /\// ) {
148 $results = $c->get_action( $command_copy, '/' );
152 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
154 $results = $c->get_action( $tail, $1 );
157 push( @{$arguments}, @extra_args );
160 unshift( @extra_args, $tail );
164 unless ( @{$results} ) {
166 unless ( $c->components->{$command} ) {
168 qq/Couldn't forward to command "$command". Invalid action or component./;
170 $c->log->debug($error) if $c->debug;
174 my $class = $command;
175 my $method = shift || 'process';
177 if ( my $code = $c->components->{$class}->can($method) ) {
178 my $action = Catalyst::Action->new(
182 reverse => "$class->$method",
187 $results = [ [$action] ];
192 qq/Couldn't forward to "$class". Does not implement "$method"/;
194 $c->log->debug($error)
201 local $c->request->{arguments} = [ @{$arguments} ];
203 for my $result ( @{$results} ) {
204 $result->[0]->execute($c);
205 return if scalar @{ $c->error };
206 last unless $c->state;
212 =item $self->prepare_action($c)
217 my ( $self, $c ) = @_;
218 my $path = $c->req->path;
219 my @path = split /\//, $c->req->path;
220 $c->req->args( \my @args );
222 push( @path, '/' ) unless @path; # Root action
224 DESCEND: while (@path) {
225 $path = join '/', @path;
227 $path = '' if $path eq '/'; # Root action
229 # Check out dispatch types to see if any will handle the path at
232 foreach my $type ( @{ $self->dispatch_types } ) {
233 last DESCEND if $type->match( $c, $path );
236 # If not, move the last part path to args
238 unshift @args, pop @path;
241 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
242 if ( $c->debug && @args );
245 =item $self->get_action( $c, $action, $namespace, $inherit )
250 my ( $self, $c, $action, $namespace, $inherit ) = @_;
251 return [] unless $action;
255 my @match = $self->get_containers($namespace);
259 foreach my $child ( $inherit ? @match : $match[-1] ) {
260 my $node = $child->actions;
261 push( @results, [ $node->{$action} ] ) if defined $node->{$action};
266 =item $self->get_containers( $namespace )
271 my ( $self, $namespace ) = @_;
273 # If the namespace is / just return the root ActionContainer
275 return ( $self->tree->getNodeValue )
276 if ( !$namespace || ( $namespace eq '/' ) );
278 # Use a visitor to recurse down the tree finding the ActionContainers
279 # for each namespace in the chain.
281 my $visitor = Tree::Simple::Visitor::FindByPath->new;
282 my @path = split( '/', $namespace );
283 $visitor->setSearchPath(@path);
284 $self->tree->accept($visitor);
286 my @match = $visitor->getResults;
287 @match = ( $self->tree ) unless @match;
289 if ( !defined $visitor->getResult ) {
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.
298 my $extra = $path[ ( scalar @match ) - 1 ];
300 $visitor->setSearchPath($extra);
301 $match[-1]->accept($visitor);
302 push( @match, $visitor->getResult ) if defined $visitor->getResult;
305 return map { $_->getNodeValue } @match;
308 =item $self->set_action( $c, $action, $code, $namespace, $attrs )
313 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
316 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
320 for my $attr ( @{$attrs} ) {
322 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
325 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
327 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
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}++;
337 if ( defined $value ) {
338 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
340 push( @{ $attributes{$key} }, $value );
344 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
345 $c->log->debug( 'Bad action definition "'
346 . join( ' ', @{$attrs} )
347 . qq/" for "$namespace->$method"/ )
351 return unless keys %attributes;
353 my $parent = $self->tree;
354 my $visitor = Tree::Simple::Visitor::FindByPath->new;
357 for my $part ( split '/', $prefix ) {
358 $visitor->setSearchPath($part);
359 $parent->accept($visitor);
360 my $child = $visitor->getResult;
364 # Create a new tree node and an ActionContainer to form
368 Catalyst::ActionContainer->new(
369 { part => $part, actions => {} } );
370 $child = $parent->addChild( Tree::Simple->new($container) );
371 $visitor->setSearchPath($part);
372 $parent->accept($visitor);
373 $child = $visitor->getResult;
380 my $reverse = $prefix ? "$prefix/$method" : $method;
382 my $action = Catalyst::Action->new(
387 namespace => $namespace,
389 attributes => \%attributes,
393 # Set the method value
394 $parent->getNodeValue->actions->{$method} = $action;
396 # Pass the action to our dispatch types so they can register it if reqd.
397 foreach my $type ( @{ $self->dispatch_types } ) {
398 $type->register( $c, $action );
402 =item $self->setup_actions( $class, $component )
407 my ( $self, $class ) = @_;
409 $self->dispatch_types( [] );
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"/ )
417 push @{ $self->dispatch_types }, $class->new;
422 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
423 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
425 for my $comp ( keys %{ $class->components } ) {
427 # We only setup components that inherit from Catalyst::Base
428 next unless $comp->isa('Catalyst::Base');
430 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
431 my ( $code, $attrs ) = @{$action};
434 my @cache = ( $comp, @{"$comp\::ISA"} );
437 while ( my $namespace = shift @cache ) {
438 $namespaces{$namespace}++;
439 for my $isa ( @{"$comp\::ISA"} ) {
440 next if $namespaces{$isa};
446 for my $namespace ( keys %namespaces ) {
447 for my $sym ( values %{ $namespace . '::' } ) {
448 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
449 $name = *{$sym}{NAME};
450 $class->set_action( $name, $code, $comp, $attrs );
458 # Default actions are always last in the chain
459 push @{ $self->dispatch_types }, Catalyst::DispatchType::Default->new;
461 return unless $class->debug;
463 my $privates = Text::ASCIITable->new;
464 $privates->setCols( 'Private', 'Class' );
465 $privates->setColWidth( 'Private', 36, 1 );
466 $privates->setColWidth( 'Class', 37, 1 );
469 my ( $walker, $parent, $prefix ) = @_;
470 $prefix .= $parent->getNodeValue || '';
471 $prefix .= '/' unless $prefix =~ /\/$/;
472 my $node = $parent->getNodeValue->actions;
474 for my $action ( keys %{$node} ) {
475 my $action_obj = $node->{$action};
476 $privates->addRow( "$prefix$action", $action_obj->namespace );
479 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
482 $walker->( $walker, $self->tree, '' );
483 $class->log->debug( "Loaded Private actions:\n" . $privates->draw )
484 if ( @{ $privates->{tbl_rows} } );
486 # List all public actions
487 $_->list($class) for @{ $self->dispatch_types };
494 Sebastian Riedel, C<sri@cpan.org>
498 This program is free software, you can redistribute it and/or modify it under
499 the same terms as Perl itself.