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 Class::Load qw(load_class try_load_class);
17 use Encode 2.21 'decode_utf8';
19 use namespace::clean -except => 'meta';
22 # do these belong as package vars or should we build these via a builder method?
23 # See Catalyst-Plugin-Server for them being added to, which should be much less ugly.
25 # Preload these action types
26 our @PRELOAD = qw/Index Path/;
28 # Postload these action types
29 our @POSTLOAD = qw/Default/;
31 # Note - see back-compat methods at end of file.
32 has _tree => (is => 'rw', builder => '_build__tree');
33 has dispatch_types => (is => 'rw', default => sub { [] }, required => 1, lazy => 1);
34 has _registered_dispatch_types => (is => 'rw', default => sub { {} }, required => 1, lazy => 1);
35 has _method_action_class => (is => 'rw', default => 'Catalyst::Action');
36 has _action_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
37 has _container_hash => (is => 'rw', required => 1, lazy => 1, default => sub { {} });
39 my %dispatch_types = ( pre => \@PRELOAD, post => \@POSTLOAD );
40 foreach my $type (keys %dispatch_types) {
41 has $type . "load_dispatch_types" => (
42 is => 'rw', required => 1, lazy => 1, default => sub { $dispatch_types{$type} },
43 traits => ['MooseX::Emulate::Class::Accessor::Fast::Meta::Role::Attribute'], # List assignment is CAF style
49 Catalyst::Dispatcher - The Catalyst Dispatcher
57 This is the class that maps public urls to actions in your Catalyst
58 application based on the attributes you set.
64 Construct a new dispatcher.
72 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
74 return Tree::Simple->new($container, Tree::Simple->ROOT);
77 =head2 $self->preload_dispatch_types
79 An arrayref of pre-loaded dispatchtype classes
81 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
82 To use a custom class outside the regular C<Catalyst> namespace, prefix
83 it with a C<+>, like so:
87 =head2 $self->postload_dispatch_types
89 An arrayref of post-loaded dispatchtype classes
91 Entries are considered to be available as C<Catalyst::DispatchType::CLASS>
92 To use a custom class outside the regular C<Catalyst> namespace, prefix
93 it with a C<+>, like so:
97 =head2 $self->dispatch($c)
99 Delegate the dispatch to the action that matched the url, or return a
100 message about unknown resource
105 my ( $self, $c ) = @_;
106 if ( my $action = $c->action ) {
107 $c->forward( join( '/', '', $action->namespace, '_DISPATCH' ) );
110 my $path = $c->req->path;
111 $path =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
112 $path = decode_utf8($path);
115 ? qq/Unknown resource "$path"/
116 : "No default action defined";
117 $c->log->error($error) if $c->debug;
122 # $self->_command2action( $c, $command [, \@arguments ] )
123 # $self->_command2action( $c, $command [, \@captures, \@arguments ] )
124 # Search for an action, from the command and returns C<($action, $args, $captures)> on
125 # success. Returns C<(0)> on error.
127 sub _command2action {
128 my ( $self, $c, $command, @extra_params ) = @_;
131 $c->log->debug('Nothing to go to') if $c->debug;
135 my (@args, @captures);
137 if ( ref( $extra_params[-2] ) eq 'ARRAY' ) {
138 @captures = @{ splice @extra_params, -2, 1 };
141 if ( ref( $extra_params[-1] ) eq 'ARRAY' ) {
142 @args = @{ pop @extra_params }
144 # this is a copy, it may take some abuse from
145 # ->_invoke_as_path if the path had trailing parts
146 @args = @{ $c->request->arguments };
151 # go to a string path ("/foo/bar/gorch")
153 if (blessed($command) && $command->isa('Catalyst::Action')) {
157 $action = $self->_invoke_as_path( $c, "$command", \@args );
160 # go to a component ( "View::Foo" or $c->component("...")
161 # - a path or an object)
163 my $method = @extra_params ? $extra_params[0] : "process";
164 $action = $self->_invoke_as_component( $c, $command, $method );
167 return $action, \@args, \@captures;
170 =head2 $self->visit( $c, $command [, \@arguments ] )
172 Documented in L<Catalyst>
178 $self->_do_visit('visit', @_);
184 my ( $c, $command ) = @_;
185 my ( $action, $args, $captures ) = $self->_command2action(@_);
186 my $error = qq/Couldn't $opname("$command"): /;
189 $error .= qq/Couldn't $opname to command "$command": /
190 .qq/Invalid action or component./;
192 elsif (!defined $action->namespace) {
193 $error .= qq/Action has no namespace: cannot $opname() to a plain /
194 .qq/method or component, must be an :Action of some sort./
196 elsif (!$action->class->can('_DISPATCH')) {
197 $error .= qq/Action cannot _DISPATCH. /
198 .qq/Did you try to $opname() a non-controller action?/;
206 $c->log->debug($error) if $c->debug;
210 $action = $self->expand_action($action);
212 local $c->request->{arguments} = $args;
213 local $c->request->{captures} = $captures;
214 local $c->{namespace} = $action->{'namespace'};
215 local $c->{action} = $action;
220 =head2 $self->go( $c, $command [, \@arguments ] )
222 Documented in L<Catalyst>
228 $self->_do_visit('go', @_);
229 Catalyst::Exception::Go->throw;
232 =head2 $self->forward( $c, $command [, \@arguments ] )
234 Documented in L<Catalyst>
240 no warnings 'recursion';
241 return $self->_do_forward(forward => @_);
247 my ( $c, $command ) = @_;
248 my ( $action, $args, $captures ) = $self->_command2action(@_);
251 my $error .= qq/Couldn't $opname to command "$command": /
252 .qq/Invalid action or component./;
254 $c->log->debug($error) if $c->debug;
259 local $c->request->{arguments} = $args;
260 no warnings 'recursion';
261 $action->dispatch( $c );
263 #If there is an error, all bets off regarding state. Documentation
264 #Specifies that when you forward, if there's an error you must expect
266 if( @{ $c->error }) {
272 =head2 $self->detach( $c, $command [, \@arguments ] )
274 Documented in L<Catalyst>
279 my ( $self, $c, $command, @args ) = @_;
280 $self->_do_forward(detach => $c, $command, @args ) if $command;
281 $c->state(0); # Needed in order to skip any auto functions
282 Catalyst::Exception::Detach->throw;
285 sub _action_rel2abs {
286 my ( $self, $c, $path ) = @_;
288 unless ( $path =~ m#^/# ) {
289 my $namespace = $c->stack->[-1]->namespace;
290 $path = "$namespace/$path";
297 sub _invoke_as_path {
298 my ( $self, $c, $rel_path, $args ) = @_;
300 my $path = $self->_action_rel2abs( $c, $rel_path );
302 my ( $tail, @extra_args );
303 while ( ( $path, $tail ) = ( $path =~ m#^(?:(.*)/)?(\w+)?$# ) )
304 { # allow $path to be empty
305 if ( my $action = $c->get_action( $tail, $path ) ) {
306 push @$args, @extra_args;
312 ; # if a match on the global namespace failed then the whole lookup failed
315 unshift @extra_args, $tail;
319 sub _find_component {
320 my ( $self, $c, $component ) = @_;
322 # fugly, why doesn't ->component('MyApp') work?
323 return $c if ($component eq blessed($c));
325 return blessed($component)
327 : $c->component($component);
330 sub _invoke_as_component {
331 my ( $self, $c, $component_or_class, $method ) = @_;
333 my $component = $self->_find_component($c, $component_or_class);
334 my $component_class = blessed $component || return 0;
336 if (my $code = $component_class->can('action_for')) {
337 my $possible_action = $component->$code($method);
338 return $possible_action if $possible_action;
341 if ( my $code = $component_class->can($method) ) {
342 return $self->_method_action_class->new(
346 reverse => "$component_class->$method",
347 class => $component_class,
348 namespace => Catalyst::Utils::class2prefix(
349 $component_class, ref($c)->config->{case_sensitive}
356 qq/Couldn't forward to "$component_class". Does not implement "$method"/;
358 $c->log->debug($error)
364 =head2 $self->prepare_action($c)
366 Find an dispatch type that matches $c->req->path, and set args from it.
371 my ( $self, $c ) = @_;
373 my $path = $req->path;
374 my @path = split /\//, $req->path;
375 $req->args( \my @args );
377 unshift( @path, '' ); # Root action
379 DESCEND: while (@path) {
380 $path = join '/', @path;
383 # Check out dispatch types to see if any will handle the path at
386 foreach my $type ( @{ $self->dispatch_types } ) {
387 last DESCEND if $type->match( $c, $path );
390 # If not, move the last part path to args
391 my $arg = pop(@path);
392 $arg =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
396 s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg for grep { defined } @{$req->captures||[]};
398 if($c->debug && defined $req->match && length $req->match) {
399 my $match = $req->match;
400 $match =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
401 $match = decode_utf8($match);
402 $c->log->debug( 'Path is "' . $match . '"' )
405 $c->log->debug( 'Arguments are "' . join( '/', map { decode_utf8 $_ } @args ) . '"' )
406 if ( $c->debug && @args );
409 =head2 $self->get_action( $action_name, $namespace )
411 returns a named action from a given namespace. C<$action_name>
412 may be a relative path on that C<$namespace> such as
414 $self->get_action('../bar', 'foo/baz');
416 In which case we look for the action at 'foo/bar'.
421 my ( $self, $name, $namespace ) = @_;
424 $namespace = join( "/", grep { length } split '/', ( defined $namespace ? $namespace : "" ) );
426 return $self->get_action_by_path("${namespace}/${name}");
429 =head2 $self->get_action_by_path( $path );
431 Returns the named action by its full private path.
433 This method performs some normalization on C<$path> so that if
434 it includes '..' it will do the right thing (for example if
435 C<$path> is '/foo/../bar' that is normalized to '/bar'.
439 sub get_action_by_path {
440 my ( $self, $path ) = @_;
441 $path =~s/[^\/]+\/\.\.\/// while $path=~m/[^\/]+\/\.\.\//;
443 $path = "/$path" unless $path =~ /\//;
444 $self->_action_hash->{$path};
447 =head2 $self->get_actions( $c, $action, $namespace )
452 my ( $self, $c, $action, $namespace ) = @_;
453 return [] unless $action;
455 $namespace = join( "/", grep { length } split '/', $namespace || "" );
457 my @match = $self->get_containers($namespace);
459 return map { $_->get_action($action) } @match;
462 =head2 $self->get_containers( $namespace )
464 Return all the action containers for a given namespace, inclusive
469 my ( $self, $namespace ) = @_;
471 $namespace = '' if $namespace eq '/';
475 if ( length $namespace ) {
477 push @containers, $self->_container_hash->{$namespace};
478 } while ( $namespace =~ s#/[^/]+$## );
481 return reverse grep { defined } @containers, $self->_container_hash->{''};
484 =head2 $self->uri_for_action($action, \@captures)
486 Takes a Catalyst::Action object and action parameters and returns a URI
487 part such that if $c->req->path were this URI part, this action would be
488 dispatched to with $c->req->captures set to the supplied arrayref.
490 If the action object is not available for external dispatch or the dispatcher
491 cannot determine an appropriate URI, this method will return undef.
496 my ( $self, $action, $captures) = @_;
498 foreach my $dispatch_type ( @{ $self->dispatch_types } ) {
499 my $uri = $dispatch_type->uri_for_action( $action, $captures );
500 return( $uri eq '' ? '/' : $uri )
508 expand an action into a full representation of the dispatch.
509 mostly useful for chained, other actions will just return a
515 my ($self, $action) = @_;
517 foreach my $dispatch_type (@{ $self->dispatch_types }) {
518 my $expanded = $dispatch_type->expand_action($action);
519 return $expanded if $expanded;
525 =head2 $self->register( $c, $action )
527 Make sure all required dispatch types for this action are loaded, then
528 pass the action to our dispatch types so they can register it if required.
529 Also, set up the tree with the action containers.
534 my ( $self, $c, $action ) = @_;
536 my $registered = $self->_registered_dispatch_types;
538 foreach my $key ( keys %{ $action->attributes } ) {
539 next if $key eq 'Private';
540 my $class = "Catalyst::DispatchType::$key";
541 unless ( $registered->{$class} ) {
542 # FIXME - Some error checking and re-throwing needed here, as
543 # we eat exceptions loading dispatch types.
544 # see also try_load_class
545 eval { load_class($class) };
546 my $load_failed = $@;
547 $self->_check_deprecated_dispatch_type( $key, $load_failed );
548 push( @{ $self->dispatch_types }, $class->new ) unless $load_failed;
549 $registered->{$class} = 1;
553 my @dtypes = @{ $self->dispatch_types };
555 my @low_precedence_dtypes;
557 for my $type ( @dtypes ) {
558 if ($type->_is_low_precedence) {
559 push @low_precedence_dtypes, $type;
561 push @normal_dtypes, $type;
565 # Pass the action to our dispatch types so they can register it if reqd.
566 my $was_registered = 0;
567 foreach my $type ( @normal_dtypes ) {
568 $was_registered = 1 if $type->register( $c, $action );
571 if (not $was_registered) {
572 foreach my $type ( @low_precedence_dtypes ) {
573 $type->register( $c, $action );
577 my $namespace = $action->namespace;
578 my $name = $action->name;
580 my $container = $self->_find_or_create_action_container($namespace);
582 # Set the method value
583 $container->add_action($action);
585 $self->_action_hash->{"$namespace/$name"} = $action;
586 $self->_container_hash->{$namespace} = $container;
589 sub _find_or_create_action_container {
590 my ( $self, $namespace ) = @_;
592 my $tree ||= $self->_tree;
594 return $tree->getNodeValue unless $namespace;
596 my @namespace = split '/', $namespace;
597 return $self->_find_or_create_namespace_node( $tree, @namespace )
601 sub _find_or_create_namespace_node {
602 my ( $self, $parent, $part, @namespace ) = @_;
604 return $parent unless $part;
607 ( grep { $_->getNodeValue->part eq $part } $parent->getAllChildren )[0];
610 my $container = Catalyst::ActionContainer->new($part);
611 $parent->addChild( $child = Tree::Simple->new($container) );
614 $self->_find_or_create_namespace_node( $child, @namespace );
617 =head2 $self->setup_actions( $class, $context )
619 Loads all of the pre-load dispatch types, registers their actions and then
620 loads all of the post-load dispatch types, and iterates over the tree of
621 actions, displaying the debug information if appropriate.
626 my ( $self, $c ) = @_;
629 $self->_load_dispatch_types( @{ $self->preload_dispatch_types } );
630 @{ $self->_registered_dispatch_types }{@classes} = (1) x @classes;
632 foreach my $comp ( map @{$_}{sort keys %$_}, $c->components ) {
633 $comp = $comp->() if ref($comp) eq 'CODE';
634 $comp->register_actions($c) if $comp->can('register_actions');
637 $self->_load_dispatch_types( @{ $self->postload_dispatch_types } );
639 return unless $c->debug;
640 $self->_display_action_tables($c);
643 sub _display_action_tables {
646 my $avail_width = Catalyst::Utils::term_width() - 12;
647 my $col1_width = ($avail_width * .25) < 20 ? 20 : int($avail_width * .25);
648 my $col2_width = ($avail_width * .50) < 36 ? 36 : int($avail_width * .50);
649 my $col3_width = $avail_width - $col1_width - $col2_width;
650 my $privates = Text::SimpleTable->new(
651 [ $col1_width, 'Private' ], [ $col2_width, 'Class' ], [ $col3_width, 'Method' ]
656 my ( $walker, $parent, $prefix ) = @_;
657 $prefix .= $parent->getNodeValue || '';
658 $prefix .= '/' unless $prefix =~ /\/$/;
659 my $node = $parent->getNodeValue->actions;
661 for my $action ( keys %{$node} ) {
662 my $action_obj = $node->{$action};
664 if ( ( $action =~ /^_.*/ )
665 && ( !$c->config->{show_internal_actions} ) );
666 $privates->row( "$prefix$action", $action_obj->class, $action );
670 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
673 $walker->( $walker, $self->_tree, '' );
674 $c->log->debug( "Loaded Private actions:\n" . $privates->draw . "\n" )
677 # List all public actions
678 $_->list($c) for @{ $self->dispatch_types };
681 sub _load_dispatch_types {
682 my ( $self, @types ) = @_;
685 # Preload action types
686 for my $type (@types) {
687 # first param is undef because we cannot get the appclass
688 my $class = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $type);
690 my ($success, $error) = try_load_class($class);
691 Catalyst::Exception->throw( message => $error ) if not $success;
692 push @{ $self->dispatch_types }, $class->new;
694 push @loaded, $class;
700 =head2 $self->dispatch_type( $type )
702 Get the DispatchType object of the relevant type, i.e. passing C<$type> of
703 C<Chained> would return a L<Catalyst::DispatchType::Chained> object (assuming
704 of course it's being used.)
709 my ($self, $name) = @_;
711 # first param is undef because we cannot get the appclass
712 $name = Catalyst::Utils::resolve_namespace(undef, 'Catalyst::DispatchType', $name);
714 for (@{ $self->dispatch_types }) {
715 return $_ if ref($_) eq $name;
720 sub _check_deprecated_dispatch_type {
721 my ($self, $key, $load_failed) = @_;
723 return unless $key =~ /^(Local)?Regexp?/;
725 # TODO: Should these throw an exception rather than just warning?
727 warn( "Attempt to use deprecated $key dispatch type.\n"
728 . " Use Chained methods or install the standalone\n"
729 . " Catalyst::DispatchType::Regex if necessary.\n" );
730 } elsif ( !defined $Catalyst::DispatchType::Regex::VERSION
731 || $Catalyst::DispatchType::Regex::VERSION le '5.90020' ) {
732 # We loaded the old core version of the Regex module this will break
733 warn( "The $key DispatchType has been removed from Catalyst core.\n"
734 . " An old version of the core Catalyst::DispatchType::Regex\n"
735 . " has been loaded and will likely fail. Please remove\n"
736 . " $INC{'Catalyst/DispatchType/Regex.pm'}\n"
737 . " and use Chained methods or install the standalone\n"
738 . " Catalyst::DispatchType::Regex if necessary.\n" );
744 # 5.70 backwards compatibility hacks.
746 # Various plugins (e.g. Plugin::Server and Plugin::Authorization::ACL)
747 # need the methods here which *should* be private..
749 # You should be able to use get_actions or get_containers appropriately
750 # instead of relying on these methods which expose implementation details
751 # of the dispatcher..
753 # IRC backlog included below, please come ask if this doesn't work for you.
755 # <@t0m> 5.80, the state of. There are things in the dispatcher which have
756 # been deprecated, that we yell at anyone for using, which there isn't
757 # a good alternative for yet..
758 # <@mst> er, get_actions/get_containers provides that doesn't it?
759 # <@mst> DispatchTypes are loaded on demand anyway
760 # <@t0m> I'm thinking of things like _tree which is aliased to 'tree' with
761 # warnings otherwise shit breaks.. We're issuing warnings about the
762 # correct set of things which you shouldn't be calling..
764 # <@mst> basically, I don't see there's a need for a replacement for anything
765 # <@mst> it was never a good idea to call ->tree
766 # <@mst> nothingmuch was the only one who did AFAIK
767 # <@mst> and he admitted it was a hack ;)
769 # See also t/lib/TestApp/Plugin/AddDispatchTypes.pm
771 # Alias _method_name to method_name, add a before modifier to warn..
772 foreach my $public_method_name (qw/
774 registered_dispatch_types
779 my $private_method_name = '_' . $public_method_name;
780 my $meta = __PACKAGE__->meta; # Calling meta method here fine as we happen at compile time.
781 $meta->add_method($public_method_name, $meta->get_method($private_method_name));
783 my %package_hash; # Only warn once per method, per package. These are infrequent enough that
784 # I haven't provided a way to disable them, patches welcome.
785 $meta->add_before_method_modifier($public_method_name, sub {
786 my $class = caller(2);
788 $package_hash{$class}++ || do {
789 warn("Class $class is calling the deprecated method\n"
790 . " Catalyst::Dispatcher::$public_method_name,\n"
791 . " this will be removed in Catalyst 5.9\n");
796 # End 5.70 backwards compatibility hacks.
798 __PACKAGE__->meta->make_immutable;
806 Catalyst Contributors, see Catalyst.pm
810 This library is free software. You can redistribute it and/or modify it under
811 the same terms as Perl itself.