1 package Catalyst::Dispatcher;
4 use base 'Class::Accessor::Fast';
5 use Catalyst::Exception;
8 use Catalyst::ActionContainer;
9 use Catalyst::DispatchType::Path;
10 use Catalyst::DispatchType::Regex;
11 use Catalyst::DispatchType::Default;
14 use Tree::Simple::Visitor::FindByPath;
17 use overload '""' => sub { return ref shift }, fallback => 1;
19 __PACKAGE__->mk_accessors(qw/actions tree dispatch_types/);
23 Catalyst::Dispatcher - The Catalyst Dispatcher
35 =item $self->detach( $c, $command [, \@arguments ] )
40 my ( $self, $c, $command, @args ) = @_;
41 $c->forward( $command, @args ) if $command;
42 die $Catalyst::DETACH;
45 =item $self->dispatch($c)
50 my ( $self, $c ) = @_;
54 my @containers = $self->get_containers( $c->namespace );
56 foreach my $name (qw/begin auto end/) {
58 # Go down the container list representing each part of the
59 # current namespace inheritance tree, grabbing the actions hash
60 # of the ActionContainer object and looking for actions of the
61 # appropriate name registered to the namespace
65 grep { exists $_->{$name} }
66 map { $_->actions } @containers
70 # Errors break the normal flow and the end action is instantly run
75 if ( my $begin = @{ $actions{begin} }[-1] ) {
77 $error++ if scalar @{ $c->error };
80 # Execute the auto chain
82 for my $auto ( @{ $actions{auto} } ) {
86 $error++ if scalar @{ $c->error };
87 last unless $c->state;
90 # Execute the action or last default
91 my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
94 $c->action->execute($c);
95 $error++ if scalar @{ $c->error };
100 if ( my $end = @{ $actions{end} }[-1] ) {
106 my $path = $c->req->path;
108 ? qq/Unknown resource "$path"/
109 : "No default action defined";
110 $c->log->error($error) if $c->debug;
115 =item $self->forward( $c, $command [, \@arguments ] )
125 $c->log->debug('Nothing to forward to') if $c->debug;
129 # Relative forwards from detach
130 my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
131 && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
133 my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
137 my $command_copy = $command;
139 unless ( $command_copy =~ s/^\/// ) {
141 Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
143 $command_copy = "${namespace}/${command}";
146 unless ( $command_copy =~ /\// ) {
147 $results = $c->get_action( $command_copy, '/' );
151 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
153 $results = $c->get_action( $tail, $1 );
156 push( @{$arguments}, @extra_args );
159 unshift( @extra_args, $tail );
163 unless ( @{$results} ) {
165 unless ( $c->components->{$command} ) {
167 qq/Couldn't forward to command "$command". Invalid action or component./;
169 $c->log->debug($error) if $c->debug;
173 my $class = $command;
174 my $method = shift || 'process';
176 if ( my $code = $c->components->{$class}->can($method) ) {
177 my $action = Catalyst::Action->new(
181 reverse => "$class->$method",
186 $results = [ [$action] ];
191 qq/Couldn't forward to "$class". Does not implement "$method"/;
193 $c->log->debug($error)
200 local $c->request->{arguments} = [ @{$arguments} ];
202 for my $result ( @{$results} ) {
203 $result->[0]->execute($c);
204 return if scalar @{ $c->error };
205 last unless $c->state;
211 =item $self->prepare_action($c)
216 my ( $self, $c ) = @_;
217 my $path = $c->req->path;
218 my @path = split /\//, $c->req->path;
219 $c->req->args( \my @args );
221 push( @path, '/' ) unless @path; # Root action
223 DESCEND: while (@path) {
224 $path = join '/', @path;
226 $path = '' if $path eq '/'; # Root action
228 # Check out dispatch types to see if any will handle the path at
231 foreach my $type ( @{ $self->dispatch_types } ) {
232 last DESCEND if $type->match( $c, $path );
235 # If not, move the last part path to args
237 unshift @args, pop @path;
240 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
241 if ( $c->debug && @args );
244 =item $self->get_action( $c, $action, $namespace, $inherit )
249 my ( $self, $c, $action, $namespace, $inherit ) = @_;
250 return [] unless $action;
254 my @match = $self->get_containers($namespace);
258 foreach my $child ( $inherit ? @match : $match[-1] ) {
259 my $node = $child->actions;
260 push( @results, [ $node->{$action} ] ) if defined $node->{$action};
265 =item $self->get_containers( $namespace )
270 my ( $self, $namespace ) = @_;
272 # If the namespace is / just return the root ActionContainer
274 return ( $self->tree->getNodeValue )
275 if ( !$namespace || ( $namespace eq '/' ) );
277 # Use a visitor to recurse down the tree finding the ActionContainers
278 # for each namespace in the chain.
280 my $visitor = Tree::Simple::Visitor::FindByPath->new;
281 my @path = split( '/', $namespace );
282 $visitor->setSearchPath(@path);
283 $self->tree->accept($visitor);
285 my @match = $visitor->getResults;
286 @match = ( $self->tree ) unless @match;
288 if ( !defined $visitor->getResult ) {
290 # If we don't manage to match, the visitor doesn't return the last
291 # node is matched, so foo/bar/baz would only find the 'foo' node,
292 # not the foo and foo/bar nodes as it should. This does another
293 # single-level search to see if that's the case, and the 'last unless'
294 # should catch any failures - or short-circuit this if this *is* a
295 # bug in the visitor and gets fixed.
297 my $extra = $path[ ( scalar @match ) - 1 ];
299 $visitor->setSearchPath($extra);
300 $match[-1]->accept($visitor);
301 push( @match, $visitor->getResult ) if defined $visitor->getResult;
304 return map { $_->getNodeValue } @match;
307 =item $self->set_action( $c, $action, $code, $namespace, $attrs )
312 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
315 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
319 for my $attr ( @{$attrs} ) {
321 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
323 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
324 if ( defined $value ) {
325 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
327 push( @{ $attributes{$key} }, $value );
331 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
332 $c->log->debug( 'Bad action definition "'
333 . join( ' ', @{$attrs} )
334 . qq/" for "$namespace->$method"/ )
338 return unless keys %attributes;
340 my $parent = $self->tree;
341 my $visitor = Tree::Simple::Visitor::FindByPath->new;
344 for my $part ( split '/', $prefix ) {
345 $visitor->setSearchPath($part);
346 $parent->accept($visitor);
347 my $child = $visitor->getResult;
351 # Create a new tree node and an ActionContainer to form
355 Catalyst::ActionContainer->new(
356 { part => $part, actions => {} } );
357 $child = $parent->addChild( Tree::Simple->new($container) );
358 $visitor->setSearchPath($part);
359 $parent->accept($visitor);
360 $child = $visitor->getResult;
367 my $reverse = $prefix ? "$prefix/$method" : $method;
369 my $action = Catalyst::Action->new(
374 namespace => $namespace,
376 attributes => \%attributes,
380 # Set the method value
381 $parent->getNodeValue->actions->{$method} = $action;
383 # Pass the action to our dispatch types so they can register it if reqd.
384 foreach my $type ( @{ $self->dispatch_types } ) {
385 $type->register( $c, $action );
389 =item $self->setup_actions( $class, $component )
394 my ( $self, $class ) = @_;
396 # These are the core structures
406 $self->dispatch_types(
407 [ map { "Catalyst::DispatchType::$_"->new } qw/Path Regex Default/ ] );
411 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
412 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
414 for my $comp ( keys %{ $class->components } ) {
416 # We only setup components that inherit from Catalyst::Base
417 next unless $comp->isa('Catalyst::Base');
419 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
420 my ( $code, $attrs ) = @{$action};
423 my @cache = ( $comp, @{"$comp\::ISA"} );
426 while ( my $namespace = shift @cache ) {
427 $namespaces{$namespace}++;
428 for my $isa ( @{"$comp\::ISA"} ) {
429 next if $namespaces{$isa};
435 for my $namespace ( keys %namespaces ) {
437 for my $sym ( values %{ $namespace . '::' } ) {
439 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
441 $name = *{$sym}{NAME};
442 $class->set_action( $name, $code, $comp, $attrs );
454 return unless $class->debug;
456 my $actions = $self->actions;
457 my $privates = Text::ASCIITable->new;
458 $privates->setCols( 'Private', 'Class' );
459 $privates->setColWidth( 'Private', 36, 1 );
460 $privates->setColWidth( 'Class', 37, 1 );
463 my ( $walker, $parent, $prefix ) = @_;
464 $prefix .= $parent->getNodeValue || '';
465 $prefix .= '/' unless $prefix =~ /\/$/;
466 my $node = $parent->getNodeValue->actions;
468 for my $action ( keys %{$node} ) {
469 my $action_obj = $node->{$action};
470 $privates->addRow( "$prefix$action", $action_obj->namespace );
473 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
476 $walker->( $walker, $self->tree, '' );
477 $class->log->debug( "Loaded Private actions:\n" . $privates->draw )
478 if ( @{ $privates->{tbl_rows} } );
480 # List all public actions
481 $_->list($class) for @{ $self->dispatch_types };
488 Sebastian Riedel, C<sri@cpan.org>
492 This program is free software, you can redistribute it and/or modify it under
493 the same terms as Perl itself.