1 package Catalyst::Dispatcher;
4 use base 'Class::Accessor::Fast';
5 use Catalyst::Exception;
8 use Catalyst::ActionContainer;
9 use Catalyst::DispatchType::Default;
10 use Catalyst::DispatchType::Index;
13 use Tree::Simple::Visitor::FindByPath;
16 use overload '""' => sub { return ref shift }, fallback => 1;
18 __PACKAGE__->mk_accessors(qw/tree dispatch_types/);
20 # Preload these action types
21 our @PRELOAD = qw/Path Regex/;
25 Catalyst::Dispatcher - The Catalyst Dispatcher
37 =item $self->detach( $c, $command [, \@arguments ] )
42 my ( $self, $c, $command, @args ) = @_;
43 $c->forward( $command, @args ) if $command;
44 die $Catalyst::DETACH;
47 =item $self->dispatch($c)
52 my ( $self, $c ) = @_;
56 my @containers = $self->get_containers( $c->namespace );
58 foreach my $name (qw/begin auto end/) {
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
67 grep { exists $_->{$name} }
68 map { $_->actions } @containers
72 # Errors break the normal flow and the end action is instantly run
77 if ( my $begin = @{ $actions{begin} }[-1] ) {
79 $error++ if scalar @{ $c->error };
82 # Execute the auto chain
84 for my $auto ( @{ $actions{auto} } ) {
88 $error++ if scalar @{ $c->error };
89 last unless $c->state;
92 # Execute the action or last default
93 my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
96 $c->action->execute($c);
97 $error++ if scalar @{ $c->error };
102 if ( my $end = @{ $actions{end} }[-1] ) {
108 my $path = $c->req->path;
110 ? qq/Unknown resource "$path"/
111 : "No default action defined";
112 $c->log->error($error) if $c->debug;
117 =item $self->forward( $c, $command [, \@arguments ] )
127 $c->log->debug('Nothing to forward to') if $c->debug;
131 # Relative forwards from detach
132 my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
133 && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
135 my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
139 my $command_copy = $command;
141 unless ( $command_copy =~ s/^\/// ) {
143 Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
145 $command_copy = "${namespace}/${command}";
148 unless ( $command_copy =~ /\// ) {
149 $results = $c->get_action( $command_copy, '/' );
153 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
155 $results = $c->get_action( $tail, $1 );
158 push( @{$arguments}, @extra_args );
161 unshift( @extra_args, $tail );
165 unless ( @{$results} ) {
167 unless ( $c->components->{$command} ) {
169 qq/Couldn't forward to command "$command". Invalid action or component./;
171 $c->log->debug($error) if $c->debug;
175 my $class = $command;
176 my $method = shift || 'process';
178 if ( my $code = $c->components->{$class}->can($method) ) {
179 my $action = Catalyst::Action->new(
183 reverse => "$class->$method",
188 $results = [ [$action] ];
193 qq/Couldn't forward to "$class". Does not implement "$method"/;
195 $c->log->debug($error)
202 local $c->request->{arguments} = [ @{$arguments} ];
204 for my $result ( @{$results} ) {
205 $result->[0]->execute($c);
206 return if scalar @{ $c->error };
207 last unless $c->state;
213 =item $self->prepare_action($c)
218 my ( $self, $c ) = @_;
219 my $path = $c->req->path;
220 my @path = split /\//, $c->req->path;
221 $c->req->args( \my @args );
223 push( @path, '/' ) unless @path; # Root action
225 DESCEND: while (@path) {
226 $path = join '/', @path;
228 $path = '' if $path eq '/'; # Root action
230 # Check out dispatch types to see if any will handle the path at
233 foreach my $type ( @{ $self->dispatch_types } ) {
234 last DESCEND if $type->match( $c, $path );
237 # If not, move the last part path to args
239 unshift @args, pop @path;
242 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
243 if ( $c->debug && @args );
246 =item $self->get_action( $c, $action, $namespace, $inherit )
251 my ( $self, $c, $action, $namespace, $inherit ) = @_;
252 return [] unless $action;
256 my @match = $self->get_containers($namespace);
260 foreach my $child ( $inherit ? @match : $match[-1] ) {
261 my $node = $child->actions;
263 $namespace = '' if $namespace eq '/';
264 my $reverse = $node->{$action}->reverse;
265 my $name = $namespace
266 ? $namespace =~ /\/$/ ? "$namespace$action" : "$namespace/$action"
268 last unless $name eq $reverse;
270 push( @results, [ $node->{$action} ] ) if defined $node->{$action};
275 =item $self->get_containers( $namespace )
280 my ( $self, $namespace ) = @_;
282 # If the namespace is / just return the root ActionContainer
284 return ( $self->tree->getNodeValue )
285 if ( !$namespace || ( $namespace eq '/' ) );
287 # Use a visitor to recurse down the tree finding the ActionContainers
288 # for each namespace in the chain.
290 my $visitor = Tree::Simple::Visitor::FindByPath->new;
291 my @path = split( '/', $namespace );
292 $visitor->setSearchPath(@path);
293 $self->tree->accept($visitor);
295 my @match = $visitor->getResults;
296 @match = ( $self->tree ) unless @match;
298 if ( !defined $visitor->getResult ) {
300 # If we don't manage to match, the visitor doesn't return the last
301 # node is matched, so foo/bar/baz would only find the 'foo' node,
302 # not the foo and foo/bar nodes as it should. This does another
303 # single-level search to see if that's the case, and the 'last unless'
304 # should catch any failures - or short-circuit this if this *is* a
305 # bug in the visitor and gets fixed.
307 my $extra = $path[ ( scalar @match ) - 1 ];
309 $visitor->setSearchPath($extra);
310 $match[-1]->accept($visitor);
311 push( @match, $visitor->getResult ) if defined $visitor->getResult;
314 return map { $_->getNodeValue } @match;
317 =item $self->set_action( $c, $action, $code, $namespace, $attrs )
322 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
325 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
329 for my $attr ( @{$attrs} ) {
331 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
334 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
336 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
339 my $class = "Catalyst::DispatchType::$key";
340 unless ( $initialized{$class} ) {
341 eval "require $class";
342 push( @{ $self->dispatch_types }, $class->new ) unless $@;
343 $initialized{$class}++;
346 if ( defined $value ) {
347 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
349 push( @{ $attributes{$key} }, $value );
353 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
354 $c->log->debug( 'Bad action definition "'
355 . join( ' ', @{$attrs} )
356 . qq/" for "$namespace->$method"/ )
360 return unless keys %attributes;
362 my $parent = $self->tree;
363 my $visitor = Tree::Simple::Visitor::FindByPath->new;
366 for my $part ( split '/', $prefix ) {
367 $visitor->setSearchPath($part);
368 $parent->accept($visitor);
369 my $child = $visitor->getResult;
373 # Create a new tree node and an ActionContainer to form
377 Catalyst::ActionContainer->new(
378 { part => $part, actions => {} } );
379 $child = $parent->addChild( Tree::Simple->new($container) );
380 $visitor->setSearchPath($part);
381 $parent->accept($visitor);
382 $child = $visitor->getResult;
389 my $reverse = $prefix ? "$prefix/$method" : $method;
391 my $action = Catalyst::Action->new(
396 namespace => $namespace,
398 attributes => \%attributes,
402 # Set the method value
403 $parent->getNodeValue->actions->{$method} = $action;
405 # Pass the action to our dispatch types so they can register it if reqd.
406 foreach my $type ( @{ $self->dispatch_types } ) {
407 $type->register( $c, $action );
411 =item $self->setup_actions( $class, $component )
416 my ( $self, $class ) = @_;
418 $self->dispatch_types( [] );
420 # Preload action types
421 for my $type (@PRELOAD) {
422 my $class = "Catalyst::DispatchType::$type";
423 eval "require $class";
424 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
426 push @{ $self->dispatch_types }, $class->new;
431 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
432 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
434 for my $comp ( keys %{ $class->components } ) {
436 # We only setup components that inherit from Catalyst::Base
437 next unless $comp->isa('Catalyst::Base');
439 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
440 my ( $code, $attrs ) = @{$action};
443 my @cache = ( $comp, @{"$comp\::ISA"} );
446 while ( my $namespace = shift @cache ) {
447 $namespaces{$namespace}++;
448 for my $isa ( @{"$comp\::ISA"} ) {
449 next if $namespaces{$isa};
455 for my $namespace ( keys %namespaces ) {
456 for my $sym ( values %{ $namespace . '::' } ) {
457 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
458 $name = *{$sym}{NAME};
459 $class->set_action( $name, $code, $comp, $attrs );
467 # Default actions are always last in the chain
468 push @{ $self->dispatch_types }, Catalyst::DispatchType::Index->new;
469 push @{ $self->dispatch_types }, Catalyst::DispatchType::Default->new;
471 return unless $class->debug;
473 my $privates = Text::ASCIITable->new;
474 $privates->setCols( 'Private', 'Class' );
475 $privates->setColWidth( 'Private', 36, 1 );
476 $privates->setColWidth( 'Class', 37, 1 );
479 my ( $walker, $parent, $prefix ) = @_;
480 $prefix .= $parent->getNodeValue || '';
481 $prefix .= '/' unless $prefix =~ /\/$/;
482 my $node = $parent->getNodeValue->actions;
484 for my $action ( keys %{$node} ) {
485 my $action_obj = $node->{$action};
486 $privates->addRow( "$prefix$action", $action_obj->namespace );
489 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
492 $walker->( $walker, $self->tree, '' );
493 $class->log->debug( "Loaded Private actions:\n" . $privates->draw )
494 if ( @{ $privates->{tbl_rows} } );
496 # List all public actions
497 $_->list($class) for @{ $self->dispatch_types };
504 Sebastian Riedel, C<sri@cpan.org>
508 This program is free software, you can redistribute it and/or modify it under
509 the same terms as Perl itself.