1 package Catalyst::Dispatcher;
4 use base 'Class::Accessor::Fast';
5 use Catalyst::Exception;
8 use Catalyst::ActionContainer;
9 use Catalyst::DispatchType::Regex;
10 use Catalyst::DispatchType::Default;
13 use Tree::Simple::Visitor::FindByPath;
16 use overload '""' => sub { return ref shift }, fallback => 1;
18 __PACKAGE__->mk_accessors(qw/actions tree dispatch_types/);
22 Catalyst::Dispatcher - The Catalyst Dispatcher
34 =item $self->detach( $c, $command [, \@arguments ] )
39 my ( $self, $c, $command, @args ) = @_;
40 $c->forward( $command, @args ) if $command;
41 die $Catalyst::DETACH;
44 =item $self->dispatch($c)
49 my ( $self, $c ) = @_;
53 my @containers = $self->get_containers( $c->namespace );
55 foreach my $name (qw/begin auto end/) {
57 # Go down the container list representing each part of the
58 # current namespace inheritance tree, grabbing the actions hash
59 # of the ActionContainer object and looking for actions of the
60 # appropriate name registered to the namespace
64 grep { exists $_->{$name} }
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} ) || '';
142 $command_copy = "${namespace}/${command}";
145 unless ( $command_copy =~ /\// ) {
146 $results = $c->get_action( $command_copy, '/' );
150 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
152 $results = $c->get_action( $tail, $1 );
155 push( @{$arguments}, @extra_args );
158 unshift( @extra_args, $tail );
162 unless ( @{$results} ) {
164 unless ( $c->components->{$command} ) {
166 qq/Couldn't forward to command "$command". Invalid action or component./;
168 $c->log->debug($error) if $c->debug;
172 my $class = $command;
173 my $method = shift || 'process';
175 if ( my $code = $c->components->{$class}->can($method) ) {
176 my $action = Catalyst::Action->new(
179 reverse => "$class->$method",
184 $results = [ [$action] ];
189 qq/Couldn't forward to "$class". Does not implement "$method"/;
191 $c->log->debug($error)
198 local $c->request->{arguments} = [ @{$arguments} ];
200 for my $result ( @{$results} ) {
201 $result->[0]->execute($c);
202 return if scalar @{ $c->error };
203 last unless $c->state;
209 =item $self->prepare_action($c)
214 my ( $self, $c ) = @_;
215 my $path = $c->req->path;
216 my @path = split /\//, $c->req->path;
217 $c->req->args( \my @args );
219 DESCEND: while (@path) {
220 $path = join '/', @path;
221 if ( my $result = ${ $c->get_action($path) }[0] ) {
225 my $match = $result->[1];
226 my @snippets = @{ $result->[2] };
228 qq/Requested action is "$path" and matched "$match"/)
231 'Snippets are "' . join( ' ', @snippets ) . '"' )
232 if ( $c->debug && @snippets );
233 $c->req->action($match);
234 $c->req->snippets( \@snippets );
238 $c->req->action($path);
239 $c->log->debug(qq/Requested action is "$path"/) if $c->debug;
242 $c->req->match($path);
243 $c->action($result->[0]);
244 $c->namespace($result->[0]->prefix);
248 unless ( $c->action ) {
249 foreach my $type (@{$self->dispatch_types}) {
250 last DESCEND if $type->prepare_action($c, $path);
251 #last DESCEND if $c->action;
255 unshift @args, pop @path;
258 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
259 if ( $c->debug && @args );
262 =item $self->get_action( $c, $action, $namespace, $inherit )
267 my ( $self, $c, $action, $namespace, $inherit ) = @_;
268 return [] unless $action;
274 my @match = $self->get_containers( $namespace );
278 foreach my $child ($inherit ? @match: $match[-1]) {
279 my $node = $child->actions;
280 push(@results, [ $node->{$action} ]) if defined $node->{$action};
285 elsif ( my $p = $self->actions->{plain}->{$action} ) { return [ [$p] ] }
286 #elsif ( my $r = $self->actions->{regex}->{$action} ) { return [ [$r] ] }
290 # for my $i ( 0 .. $#{ $self->actions->{compiled} } ) {
291 # my $name = $self->actions->{compiled}->[$i]->[0];
292 # my $regex = $self->actions->{compiled}->[$i]->[1];
294 # if ( my @snippets = ( $action =~ $regex ) ) {
296 # [ $self->actions->{regex}->{$name}, $name, \@snippets ] ];
304 =item $self->get_containers( $namespace )
309 my ( $self, $namespace ) = @_;
311 # If the namespace is / just return the root ActionContainer
313 return ($self->tree->getNodeValue) if $namespace eq '/';
315 # Use a visitor to recurse down the tree finding the ActionContainers
316 # for each namespace in the chain.
318 my $visitor = Tree::Simple::Visitor::FindByPath->new;
319 my @path = split('/', $namespace);
320 $visitor->setSearchPath( @path );
321 $self->tree->accept($visitor);
323 my @match = $visitor->getResults;
324 @match = ($self->tree) unless @match;
326 if (!defined $visitor->getResult) {
328 # If we don't manage to match, the visitor doesn't return the last
329 # node is matched, so foo/bar/baz would only find the 'foo' node,
330 # not the foo and foo/bar nodes as it should. This does another
331 # single-level search to see if that's the case, and the 'last unless'
332 # should catch any failures - or short-circuit this if this *is* a
333 # bug in the visitor and gets fixed.
335 my $extra = $path[(scalar @match) - 1];
337 $visitor->setSearchPath($extra);
338 $match[-1]->accept($visitor);
339 push(@match, $visitor->getResult) if defined $visitor->getResult;
342 return map { $_->getNodeValue } @match;
345 =item $self->set_action( $c, $action, $code, $namespace, $attrs )
350 my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
353 Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
358 for my $attr ( @{$attrs} ) {
359 if ( $attr =~ /^(Local|Relative)$/ ) { $flags{local}++ }
360 elsif ( $attr =~ /^(Global|Absolute)$/ ) { $flags{global}++ }
361 elsif ( $attr =~ /^Path\(\s*(.+)\s*\)$/i ) {
362 push @{ $flags{path} }, $1;
364 elsif ( $attr =~ /^Private$/i ) { $flags{private}++ }
365 elsif ( $attr =~ /^(Regex|Regexp)\(\s*(.+)\s*\)$/i ) {
366 push @{ $flags{regex} }, $2;
368 if ( my ($key, $value) = ($attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/) ) {
369 if ( defined $value ) {
370 ($value =~ s/^'(.*)'$/$1/) || ($value =~ s/^"(.*)"/$1/);
372 push(@{$attributes{$key}}, $value);
376 if ( $flags{private} && ( keys %flags > 1 ) ) {
377 $c->log->debug( 'Bad action definition "'
378 . join( ' ', @{$attrs} )
379 . qq/" for "$namespace->$method"/ )
383 return unless keys %flags;
385 my $parent = $self->tree;
386 my $visitor = Tree::Simple::Visitor::FindByPath->new;
389 for my $part ( split '/', $prefix ) {
390 $visitor->setSearchPath($part);
391 $parent->accept($visitor);
392 my $child = $visitor->getResult;
396 # Create a new tree node and an ActionContainer to form
399 my $container = Catalyst::ActionContainer->new(
400 { part => $part, actions => {} });
401 $child = $parent->addChild( Tree::Simple->new($container) );
402 $visitor->setSearchPath($part);
403 $parent->accept($visitor);
404 $child = $visitor->getResult;
411 my $reverse = $prefix ? "$prefix/$method" : $method;
413 my $action = Catalyst::Action->new(
417 namespace => $namespace,
419 attributes => \%attributes,
423 # Set the method value
424 $parent->getNodeValue->actions->{$method} = $action;
427 for my $path ( @{ $flags{path} } ) {
430 if ( $path =~ /^\s*'(.*)'\s*$/ ) { $path = $1 }
431 if ( $path =~ /^\s*"(.*)"\s*$/ ) { $path = $1 }
434 $flags{path} = \@path;
437 for my $regex ( @{ $flags{regex} } ) {
440 if ( $regex =~ /^\s*'(.*)'\s*$/ ) { $regex = $1 }
441 if ( $regex =~ /^\s*"(.*)"\s*$/ ) { $regex = $1 }
444 $flags{regex} = \@regex;
446 if ( $flags{local} || $flags{global} ) {
447 push( @{ $flags{path} }, $prefix ? "/$prefix/$method" : "/$method" )
450 push( @{ $flags{path} }, "/$method" ) if $flags{global};
453 for my $path ( @{ $flags{path} } ) {
454 if ( $path =~ /^\// ) { $path =~ s/^\/// }
455 else { $path = $prefix ? "$prefix/$path" : $path }
456 $self->actions->{plain}->{$path} = $action;
459 for my $regex ( @{ $flags{regex} } ) {
460 push @{ $self->actions->{compiled} }, [ $regex, qr#$regex# ];
461 $self->actions->{regex}->{$regex} = $action;
464 foreach my $type ( @{ $self->dispatch_types } ) {
465 $type->register_action($c, $action);
469 =item $self->setup_actions( $class, $component )
474 my ( $self, $class ) = @_;
476 # These are the core structures
486 $self->dispatch_types([
487 map { "Catalyst::DispatchType::$_"->new }
488 qw/Regex Default/ ]);
491 my $container = Catalyst::ActionContainer->new(
492 { part => '/', actions => {} } );
493 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
495 for my $comp ( keys %{ $class->components } ) {
497 # We only setup components that inherit from Catalyst::Base
498 next unless $comp->isa('Catalyst::Base');
500 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
501 my ( $code, $attrs ) = @{$action};
504 my @cache = ( $comp, @{"$comp\::ISA"} );
507 while ( my $namespace = shift @cache ) {
508 $namespaces{$namespace}++;
509 for my $isa ( @{"$comp\::ISA"} ) {
510 next if $namespaces{$isa};
516 for my $namespace ( keys %namespaces ) {
518 for my $sym ( values %{ $namespace . '::' } ) {
520 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
522 $name = *{$sym}{NAME};
523 $class->set_action( $name, $code, $comp, $attrs );
535 return unless $class->debug;
537 my $actions = $self->actions;
538 my $privates = Text::ASCIITable->new;
539 $privates->setCols( 'Private', 'Class' );
540 $privates->setColWidth( 'Private', 36, 1 );
541 $privates->setColWidth( 'Class', 37, 1 );
544 my ( $walker, $parent, $prefix ) = @_;
545 $prefix .= $parent->getNodeValue || '';
546 $prefix .= '/' unless $prefix =~ /\/$/;
547 my $node = $parent->getNodeValue->actions;
549 for my $action ( keys %{ $node } ) {
550 my $action_obj = $node->{$action};
551 $privates->addRow( "$prefix$action", $action_obj->namespace );
554 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
557 $walker->( $walker, $self->tree, '' );
558 $class->log->debug( "Loaded private actions:\n" . $privates->draw )
559 if ( @{ $privates->{tbl_rows} } );
561 my $publics = Text::ASCIITable->new;
562 $publics->setCols( 'Public', 'Private' );
563 $publics->setColWidth( 'Public', 36, 1 );
564 $publics->setColWidth( 'Private', 37, 1 );
566 for my $plain ( sort keys %{ $actions->{plain} } ) {
567 my $action = $actions->{plain}->{$plain};
568 $publics->addRow( "/$plain", "/$action" );
571 $class->log->debug( "Loaded public actions:\n" . $publics->draw )
572 if ( @{ $publics->{tbl_rows} } );
574 my $regexes = Text::ASCIITable->new;
575 $regexes->setCols( 'Regex', 'Private' );
576 $regexes->setColWidth( 'Regex', 36, 1 );
577 $regexes->setColWidth( 'Private', 37, 1 );
579 for my $regex ( sort keys %{ $actions->{regex} } ) {
580 my $action = $actions->{regex}->{$regex};
581 $regexes->addRow( $regex, "/$action" );
584 $class->log->debug( "Loaded regex actions:\n" . $regexes->draw )
585 if ( @{ $regexes->{tbl_rows} } );
592 Sebastian Riedel, C<sri@cpan.org>
596 This program is free software, you can redistribute it and/or modify it under
597 the same terms as Perl itself.