1 package Catalyst::Dispatcher;
5 with 'MooseX::Emulate::Class::Accessor::Fast';
7 use Catalyst::Exception;
10 use Catalyst::ActionContainer;
11 use Catalyst::DispatchType::Default;
12 use Catalyst::DispatchType::Index;
14 use Text::SimpleTable;
16 use Tree::Simple::Visitor::FindByPath;
17 use Class::Load qw(load_class try_load_class);
18 use Encode 2.21 'decode_utf8';
19 use Ref::Util qw(is_plain_arrayref is_plain_coderef);
21 use namespace::clean -except => 'meta';
24 # do these belong as package vars or should we build these via a builder method?
25 # See Catalyst-Plugin-Server for them being added to, which should be much less ugly.
27 # Preload these action types
28 our @PRELOAD = qw/Index Path/;
30 # Postload these action types
31 our @POSTLOAD = qw/Default/;
33 # Note - see back-compat methods at end of file.
34 has _tree => (is => 'rw', builder => '_build__tree');
35 has dispatch_types => (is => 'rw', default => sub { [] }, required => 1, lazy => 1);
36 has _registered_dispatch_types => (is => 'rw', default => sub { {} }, required => 1, lazy => 1);
37 has _method_action_class => (is => 'rw', default => 'Catalyst::Action');
38 has _action_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
39 has _container_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
41 my %dispatch_types = ( pre => \@PRELOAD, post => \@POSTLOAD );
42 foreach my $type (keys %dispatch_types) {
43 has $type . "load_dispatch_types" => (
44 is => 'rw', required => 1, lazy => 1, default => sub { $dispatch_types{$type} },
45 traits => ['MooseX::Emulate::Class::Accessor::Fast::Meta::Role::Attribute'], # List assignment is CAF style
51 Catalyst::Dispatcher - The Catalyst Dispatcher
59 This is the class that maps public urls to actions in your Catalyst
60 application based on the attributes you set.
66 Construct a new dispatcher.
74 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
76 return Tree::Simple->new($container, Tree::Simple->ROOT);
79 =head2 $self->preload_dispatch_types
81 An arrayref of pre-loaded dispatchtype classes
83 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
84 To use a custom class outside the regular C<Catalyst> namespace, prefix
85 it with a C<+>, like so:
89 =head2 $self->postload_dispatch_types
91 An arrayref of post-loaded dispatchtype classes
93 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
94 To use a custom class outside the regular C<Catalyst> namespace, prefix
95 it with a C<+>, like so:
99 =head2 $self->dispatch($c)
101 Delegate the dispatch to the action that matched the url, or return a
102 message about unknown resource
107 my ( $self, $c ) = @_;
108 if ( my $action = $c->action ) {
109 $c->forward( join( '/', '', $action->namespace, '_DISPATCH' ) );
112 my $path = $c->req->path;
113 $path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
114 $path = decode_utf8($path);
117 ? qq/Unknown resource "$path"/
118 : "No default action defined";
119 $c->log->error($error) if $c->debug;
124 # $self->_command2action( $c, $command [, \@arguments ] )
125 # $self->_command2action( $c, $command [, \@captures, \@arguments ] )
126 # Search for an action, from the command and returns C<($action, $args, $captures)> on
127 # success. Returns C<(0)> on error.
129 sub _command2action {
130 my ( $self, $c, $command, @extra_params ) = @_;
133 $c->log->debug('Nothing to go to') if $c->debug;
137 my (@args, @captures);
139 if ( is_plain_arrayref($extra_params[-2]) ) {
140 @captures = @{ splice @extra_params, -2, 1 };
143 if ( is_plain_arrayref($extra_params[-1]) ) {
144 @args = @{ pop @extra_params }
146 # this is a copy, it may take some abuse from
147 # ->_invoke_as_path if the path had trailing parts
148 @args = @{ $c->request->arguments };
153 # go to a string path ("/foo/bar/gorch")
155 if (blessed($command) && $command->isa('Catalyst::Action')) {
159 $action = $self->_invoke_as_path( $c, "$command", \@args );
162 # go to a component ( "View::Foo" or $c->component("...")
163 # - a path or an object)
165 my $method = @extra_params ? $extra_params[0] : "process";
166 $action = $self->_invoke_as_component( $c, $command, $method );
169 return $action, \@args, \@captures;
172 =head2 $self->visit( $c, $command [, \@arguments ] )
174 Documented in L<Catalyst>
180 $self->_do_visit('visit', @_);
186 my ( $c, $command ) = @_;
187 my ( $action, $args, $captures ) = $self->_command2action(@_);
188 my $error = qq/Couldn't $opname("$command"): /;
191 $error .= qq/Couldn't $opname to command "$command": /
192 .qq/Invalid action or component./;
194 elsif (!defined $action->namespace) {
195 $error .= qq/Action has no namespace: cannot $opname() to a plain /
196 .qq/method or component, must be an :Action of some sort./
198 elsif (!$action->class->can('_DISPATCH')) {
199 $error .= qq/Action cannot _DISPATCH. /
200 .qq/Did you try to $opname() a non-controller action?/;
208 $c->log->debug($error) if $c->debug;
212 $action = $self->expand_action($action);
214 local $c->request->{arguments} = $args;
215 local $c->request->{captures} = $captures;
216 local $c->{namespace} = $action->{'namespace'};
217 local $c->{action} = $action;
222 =head2 $self->go( $c, $command [, \@arguments ] )
224 Documented in L<Catalyst>
230 $self->_do_visit('go', @_);
231 Catalyst::Exception::Go->throw;
234 =head2 $self->forward( $c, $command [, \@arguments ] )
236 Documented in L<Catalyst>
242 no warnings 'recursion';
243 return $self->_do_forward(forward => @_);
249 my ( $c, $command ) = @_;
250 my ( $action, $args, $captures ) = $self->_command2action(@_);
253 my $error .= qq/Couldn't $opname to command "$command": /
254 .qq/Invalid action or component./;
256 $c->log->debug($error) if $c->debug;
261 local $c->request->{arguments} = $args;
262 no warnings 'recursion';
263 $action->dispatch( $c );
265 #If there is an error, all bets off regarding state. Documentation
266 #Specifies that when you forward, if there's an error you must expect
268 if( @{ $c->error }) {
274 =head2 $self->detach( $c, $command [, \@arguments ] )
276 Documented in L<Catalyst>
281 my ( $self, $c, $command, @args ) = @_;
282 $self->_do_forward(detach => $c, $command, @args ) if $command;
283 $c->state(0); # Needed in order to skip any auto functions
284 Catalyst::Exception::Detach->throw;
287 sub _action_rel2abs {
288 my ( $self, $c, $path ) = @_;
290 unless ( $path =~ m#^/# ) {
291 my $namespace = $c->stack->[-1]->namespace;
292 $path = "$namespace/$path";
299 sub _invoke_as_path {
300 my ( $self, $c, $rel_path, $args ) = @_;
302 my $path = $self->_action_rel2abs( $c, $rel_path );
304 my ( $tail, @extra_args );
305 while ( ( $path, $tail ) = ( $path =~ m#^(?:(.*)/)?(\w+)?$# ) )
306 { # allow $path to be empty
307 if ( my $action = $c->get_action( $tail, $path ) ) {
308 push @$args, @extra_args;
314 ; # if a match on the global namespace failed then the whole lookup failed
317 unshift @extra_args, $tail;
321 sub _find_component {
322 my ( $self, $c, $component ) = @_;
324 # fugly, why doesn't ->component('MyApp') work?
325 return $c if ($component eq blessed($c));
327 return blessed($component)
329 : $c->component($component);
332 sub _invoke_as_component {
333 my ( $self, $c, $component_or_class, $method ) = @_;
335 my $component = $self->_find_component($c, $component_or_class);
336 my $component_class = blessed $component || return 0;
338 if (my $code = $component_class->can('action_for')) {
339 my $possible_action = $component->$code($method);
340 return $possible_action if $possible_action;
343 if ( my $code = $component_class->can($method) ) {
344 return $self->_method_action_class->new(
348 reverse => "$component_class->$method",
349 class => $component_class,
350 namespace => Catalyst::Utils::class2prefix(
351 $component_class, ref($c)->config->{case_sensitive}
358 qq/Couldn't forward to "$component_class". Does not implement "$method"/;
360 $c->log->debug($error)
366 =head2 $self->prepare_action($c)
368 Find an dispatch type that matches $c->req->path, and set args from it.
373 my ( $self, $c ) = @_;
375 my $path = $req->path;
376 my @path = split /\//, $req->path;
377 $req->args( \my @args );
379 unshift( @path, '' ); # Root action
381 DESCEND: while (@path) {
382 $path = join '/', @path;
385 # Check out dispatch types to see if any will handle the path at
388 foreach my $type ( @{ $self->dispatch_types } ) {
389 last DESCEND if $type->match( $c, $path );
392 # If not, move the last part path to args
393 my $arg = pop(@path);
394 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
398 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg for grep { defined } @{$req->captures||[]};
400 if($c->debug && defined $req->match && length $req->match) {
401 my $match = $req->match;
402 $match =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
403 $match = decode_utf8($match);
404 $c->log->debug( 'Path is "' . $match . '"' )
407 $c->log->debug( 'Arguments are "' . join( '/', map { decode_utf8 $_ } @args ) . '"' )
408 if ( $c->debug && @args );
411 =head2 $self->get_action( $action_name, $namespace )
413 returns a named action from a given namespace. C<$action_name>
414 may be a relative path on that C<$namespace> such as
416 $self->get_action('../bar', 'foo/baz');
418 In which case we look for the action at 'foo/bar'.
423 my ( $self, $name, $namespace ) = @_;
426 $namespace = join( "/", grep { length } split '/', ( defined $namespace ? $namespace : "" ) );
428 return $self->get_action_by_path("${namespace}/${name}");
431 =head2 $self->get_action_by_path( $path );
433 Returns the named action by its full private path.
435 This method performs some normalization on C<$path> so that if
436 it includes '..' it will do the right thing (for example if
437 C<$path> is '/foo/../bar' that is normalized to '/bar'.
441 sub get_action_by_path {
442 my ( $self, $path ) = @_;
443 $path =~s/[^\/]+\/\.\.\/// while $path=~m/[^\/]+\/\.\.\//;
445 $path = "/$path" unless $path =~ /\//;
446 $self->_action_hash->{$path};
449 =head2 $self->get_actions( $c, $action, $namespace )
454 my ( $self, $c, $action, $namespace ) = @_;
455 return [] unless $action;
457 $namespace = join( "/", grep { length } split '/', $namespace || "" );
459 my @match = $self->get_containers($namespace);
461 return map { $_->get_action($action) } @match;
464 =head2 $self->get_containers( $namespace )
466 Return all the action containers for a given namespace, inclusive
471 my ( $self, $namespace ) = @_;
473 $namespace = '' if $namespace eq '/';
477 if ( length $namespace ) {
479 push @containers, $self->_container_hash->{$namespace};
480 } while ( $namespace =~ s#/[^/]+$## );
483 return reverse grep { defined } @containers, $self->_container_hash->{''};
486 =head2 $self->uri_for_action($action, \@captures)
488 Takes a Catalyst::Action object and action parameters and returns a URI
489 part such that if $c->req->path were this URI part, this action would be
490 dispatched to with $c->req->captures set to the supplied arrayref.
492 If the action object is not available for external dispatch or the dispatcher
493 cannot determine an appropriate URI, this method will return undef.
498 my ( $self, $action, $captures) = @_;
500 foreach my $dispatch_type ( @{ $self->dispatch_types } ) {
501 my $uri = $dispatch_type->uri_for_action( $action, $captures );
502 return( $uri eq '' ? '/' : $uri )
510 expand an action into a full representation of the dispatch.
511 mostly useful for chained, other actions will just return a
517 my ($self, $action) = @_;
519 foreach my $dispatch_type (@{ $self->dispatch_types }) {
520 my $expanded = $dispatch_type->expand_action($action);
521 return $expanded if $expanded;
527 =head2 $self->register( $c, $action )
529 Make sure all required dispatch types for this action are loaded, then
530 pass the action to our dispatch types so they can register it if required.
531 Also, set up the tree with the action containers.
536 my ( $self, $c, $action ) = @_;
538 my $registered = $self->_registered_dispatch_types;
540 foreach my $key ( keys %{ $action->attributes } ) {
541 next if $key eq 'Private';
542 my $class = "Catalyst::DispatchType::$key";
543 unless ( $registered->{$class} ) {
544 # FIXME - Some error checking and re-throwing needed here, as
545 # we eat exceptions loading dispatch types.
546 # see also try_load_class
547 eval { load_class($class) };
548 my $load_failed = $@;
549 $self->_check_deprecated_dispatch_type( $key, $load_failed );
550 push( @{ $self->dispatch_types }, $class->new ) unless $load_failed;
551 $registered->{$class} = 1;
555 my @dtypes = @{ $self->dispatch_types };
557 my @low_precedence_dtypes;
559 for my $type ( @dtypes ) {
560 if ($type->_is_low_precedence) {
561 push @low_precedence_dtypes, $type;
563 push @normal_dtypes, $type;
567 # Pass the action to our dispatch types so they can register it if reqd.
568 my $was_registered = 0;
569 foreach my $type ( @normal_dtypes ) {
570 $was_registered = 1 if $type->register( $c, $action );
573 if (not $was_registered) {
574 foreach my $type ( @low_precedence_dtypes ) {
575 $type->register( $c, $action );
579 my $namespace = $action->namespace;
580 my $name = $action->name;
582 my $container = $self->_find_or_create_action_container($namespace);
584 # Set the method value
585 $container->add_action($action);
587 $self->_action_hash->{"$namespace/$name"} = $action;
588 $self->_container_hash->{$namespace} = $container;
591 sub _find_or_create_action_container {
592 my ( $self, $namespace ) = @_;
594 my $tree ||= $self->_tree;
596 return $tree->getNodeValue unless $namespace;
598 my @namespace = split '/', $namespace;
599 return $self->_find_or_create_namespace_node( $tree, @namespace )
603 sub _find_or_create_namespace_node {
604 my ( $self, $parent, $part, @namespace ) = @_;
606 return $parent unless $part;
609 ( grep { $_->getNodeValue->part eq $part } $parent->getAllChildren )[0];
612 my $container = Catalyst::ActionContainer->new($part);
613 $parent->addChild( $child = Tree::Simple->new($container) );
616 $self->_find_or_create_namespace_node( $child, @namespace );
619 =head2 $self->setup_actions( $class, $context )
621 Loads all of the pre-load dispatch types, registers their actions and then
622 loads all of the post-load dispatch types, and iterates over the tree of
623 actions, displaying the debug information if appropriate.
628 my ( $self, $c ) = @_;
631 $self->_load_dispatch_types( @{ $self->preload_dispatch_types } );
632 @{ $self->_registered_dispatch_types }{@classes} = (1) x @classes;
634 foreach my $comp ( map @{$_}{sort keys %$_}, $c->components ) {
635 $comp = $comp->() if is_plain_coderef($comp);
636 $comp->register_actions($c) if $comp->can('register_actions');
639 $self->_load_dispatch_types( @{ $self->postload_dispatch_types } );
641 return unless $c->debug;
642 $self->_display_action_tables($c);
645 sub _display_action_tables {
648 my $avail_width = Catalyst::Utils::term_width() - 12;
649 my $col1_width = ($avail_width * .25) < 20 ? 20 : int($avail_width * .25);
650 my $col2_width = ($avail_width * .50) < 36 ? 36 : int($avail_width * .50);
651 my $col3_width = $avail_width - $col1_width - $col2_width;
652 my $privates = Text::SimpleTable->new(
653 [ $col1_width, 'Private' ], [ $col2_width, 'Class' ], [ $col3_width, 'Method' ]
658 my ( $walker, $parent, $prefix ) = @_;
659 $prefix .= $parent->getNodeValue || '';
660 $prefix .= '/' unless $prefix =~ /\/$/;
661 my $node = $parent->getNodeValue->actions;
663 for my $action ( keys %{$node} ) {
664 my $action_obj = $node->{$action};
666 if ( ( $action =~ /^_.*/ )
667 && ( !$c->config->{show_internal_actions} ) );
668 $privates->row( "$prefix$action", $action_obj->class, $action );
672 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
675 $walker->( $walker, $self->_tree, '' );
676 $c->log->debug( "Loaded Private actions:\n" . $privates->draw . "\n" )
679 # List all public actions
680 $_->list($c) for @{ $self->dispatch_types };
683 sub _load_dispatch_types {
684 my ( $self, @types ) = @_;
687 # Preload action types
688 for my $type (@types) {
689 # first param is undef because we cannot get the appclass
690 my $class = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $type);
692 my ($success, $error) = try_load_class($class);
693 Catalyst::Exception->throw( message => $error ) if not $success;
694 push @{ $self->dispatch_types }, $class->new;
696 push @loaded, $class;
702 =head2 $self->dispatch_type( $type )
704 Get the DispatchType object of the relevant type, i.e. passing C<$type> of
705 C<Chained> would return a L<Catalyst::DispatchType::Chained> object (assuming
706 of course it's being used.)
711 my ($self, $name) = @_;
713 # first param is undef because we cannot get the appclass
714 $name = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $name);
716 for (@{ $self->dispatch_types }) {
717 return $_ if ref($_) eq $name;
722 sub _check_deprecated_dispatch_type {
723 my ($self, $key, $load_failed) = @_;
725 return unless $key =~ /^(Local)?Regexp?/;
727 # TODO: Should these throw an exception rather than just warning?
729 warn( "Attempt to use deprecated $key dispatch type.\n"
730 . " Use Chained methods or install the standalone\n"
731 . " Catalyst::DispatchType::Regex if necessary.\n" );
732 } elsif ( !defined $Catalyst::DispatchType::Regex::VERSION
733 || $Catalyst::DispatchType::Regex::VERSION le '5.90020' ) {
734 # We loaded the old core version of the Regex module this will break
735 warn( "The $key DispatchType has been removed from Catalyst core.\n"
736 . " An old version of the core Catalyst::DispatchType::Regex\n"
737 . " has been loaded and will likely fail. Please remove\n"
738 . " $INC{'Catalyst/DispatchType/Regex.pm'}\n"
739 . " and use Chained methods or install the standalone\n"
740 . " Catalyst::DispatchType::Regex if necessary.\n" );
746 # 5.70 backwards compatibility hacks.
748 # Various plugins (e.g. Plugin::Server and Plugin::Authorization::ACL)
749 # need the methods here which *should* be private..
751 # You should be able to use get_actions or get_containers appropriately
752 # instead of relying on these methods which expose implementation details
753 # of the dispatcher..
755 # IRC backlog included below, please come ask if this doesn't work for you.
757 # <@t0m> 5.80, the state of. There are things in the dispatcher which have
758 # been deprecated, that we yell at anyone for using, which there isn't
759 # a good alternative for yet..
760 # <@mst> er, get_actions/get_containers provides that doesn't it?
761 # <@mst> DispatchTypes are loaded on demand anyway
762 # <@t0m> I'm thinking of things like _tree which is aliased to 'tree' with
763 # warnings otherwise shit breaks.. We're issuing warnings about the
764 # correct set of things which you shouldn't be calling..
766 # <@mst> basically, I don't see there's a need for a replacement for anything
767 # <@mst> it was never a good idea to call ->tree
768 # <@mst> nothingmuch was the only one who did AFAIK
769 # <@mst> and he admitted it was a hack ;)
771 # See also t/lib/TestApp/Plugin/AddDispatchTypes.pm
773 # Alias _method_name to method_name, add a before modifier to warn..
774 foreach my $public_method_name (qw/
776 registered_dispatch_types
781 my $private_method_name = '_' . $public_method_name;
782 my $meta = __PACKAGE__->meta; # Calling meta method here fine as we happen at compile time.
783 $meta->add_method($public_method_name, $meta->get_method($private_method_name));
785 my %package_hash; # Only warn once per method, per package. These are infrequent enough that
786 # I haven't provided a way to disable them, patches welcome.
787 $meta->add_before_method_modifier($public_method_name, sub {
788 my $class = caller(2);
790 $package_hash{$class}++ || do {
791 warn("Class $class is calling the deprecated method\n"
792 . " Catalyst::Dispatcher::$public_method_name,\n"
793 . " this will be removed in Catalyst 5.9\n");
798 # End 5.70 backwards compatibility hacks.
800 __PACKAGE__->meta->make_immutable;
808 Catalyst Contributors, see Catalyst.pm
812 This library is free software. You can redistribute it and/or modify it under
813 the same terms as Perl itself.