- Made relative regexps work
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Dispatcher.pm
CommitLineData
68a748b9 1package Catalyst::Dispatcher;
1abd6db7 2
3use strict;
fbcc39ad 4use base 'Class::Accessor::Fast';
a2f2cde9 5use Catalyst::Exception;
f05af9ba 6use Catalyst::Utils;
fbcc39ad 7use Catalyst::Action;
b7aebc12 8use Catalyst::ActionContainer;
b96f127f 9use Catalyst::DispatchType::Default;
bcccee4e 10use Catalyst::DispatchType::Index;
1abd6db7 11use Text::ASCIITable;
1abd6db7 12use Tree::Simple;
13use Tree::Simple::Visitor::FindByPath;
14
fbcc39ad 15# Stringify to class
16use overload '""' => sub { return ref shift }, fallback => 1;
17
6d030e6f 18__PACKAGE__->mk_accessors(qw/tree dispatch_types/);
19
20# Preload these action types
21our @PRELOAD = qw/Path Regex/;
1abd6db7 22
2d1d8f91 23# Postload these action types
24our @POSTLOAD = qw/Index Default/;
25
1abd6db7 26=head1 NAME
27
9c053379 28Catalyst::Dispatcher - The Catalyst Dispatcher
1abd6db7 29
30=head1 SYNOPSIS
31
32See L<Catalyst>.
33
34=head1 DESCRIPTION
35
36=head1 METHODS
37
38=over 4
39
fbcc39ad 40=item $self->detach( $c, $command [, \@arguments ] )
6ef62eb2 41
42=cut
43
44sub detach {
fbcc39ad 45 my ( $self, $c, $command, @args ) = @_;
bd7d2e94 46 $c->forward( $command, @args ) if $command;
fbcc39ad 47 die $Catalyst::DETACH;
6ef62eb2 48}
49
fbcc39ad 50=item $self->dispatch($c)
1abd6db7 51
52=cut
53
54sub dispatch {
fbcc39ad 55 my ( $self, $c ) = @_;
cfd04b0c 56
66e28e3f 57 if ( $c->action ) {
b0bb11ec 58 $c->forward( join( '/', '', $c->namespace, '_DISPATCH' ) );
fbcc39ad 59 }
60
61 else {
1abd6db7 62 my $path = $c->req->path;
63 my $error = $path
64 ? qq/Unknown resource "$path"/
65 : "No default action defined";
66 $c->log->error($error) if $c->debug;
67 $c->error($error);
68 }
69}
70
fbcc39ad 71=item $self->forward( $c, $command [, \@arguments ] )
1abd6db7 72
73=cut
74
75sub forward {
fbcc39ad 76 my $self = shift;
1abd6db7 77 my $c = shift;
78 my $command = shift;
99fe1710 79
1abd6db7 80 unless ($command) {
81 $c->log->debug('Nothing to forward to') if $c->debug;
82 return 0;
83 }
99fe1710 84
71c3bcc3 85 # Relative forwards from detach
fbcc39ad 86 my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
87 && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
71c3bcc3 88
e0fc6749 89 my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
99fe1710 90
a9dc674c 91 my $result;
fbcc39ad 92
8199eac3 93 my $command_copy = $command;
94
95 unless ( $command_copy =~ s/^\/// ) {
5d68b17b 96 my $namespace =
78d760bb 97 Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} )
98 || '';
5d68b17b 99 $command_copy = "${namespace}/${command}";
1abd6db7 100 }
99fe1710 101
8199eac3 102 unless ( $command_copy =~ /\// ) {
a9dc674c 103 $result = $c->get_action( $command_copy, '/' );
8199eac3 104 }
e494bd6b 105 else {
8199eac3 106 my @extra_args;
107 DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
108 my $tail = $2;
a9dc674c 109 $result = $c->get_action( $tail, $1 );
110 if ( $result ) {
8199eac3 111 $command = $tail;
112 push( @{$arguments}, @extra_args );
113 last DESCEND;
114 }
115 unshift( @extra_args, $tail );
116 }
e494bd6b 117 }
99fe1710 118
a9dc674c 119 unless ( $result ) {
bd7d2e94 120
fbcc39ad 121 unless ( $c->components->{$command} ) {
bd7d2e94 122 my $error =
123qq/Couldn't forward to command "$command". Invalid action or component./;
3b2ed580 124 $c->error($error);
125 $c->log->debug($error) if $c->debug;
1abd6db7 126 return 0;
127 }
bd7d2e94 128
1f6bb799 129 my $class = $command;
1abd6db7 130 my $method = shift || 'process';
99fe1710 131
1f6bb799 132 if ( my $code = $c->components->{$class}->can($method) ) {
fbcc39ad 133 my $action = Catalyst::Action->new(
134 {
6b239949 135 name => $method,
fbcc39ad 136 code => $code,
137 reverse => "$class->$method",
11bd4e3e 138 class => $class,
fbcc39ad 139 namespace => $class,
140 }
141 );
a9dc674c 142 $result = $action;
fbcc39ad 143 }
144
145 else {
bd7d2e94 146 my $error =
147 qq/Couldn't forward to "$class". Does not implement "$method"/;
3b2ed580 148 $c->error($error);
149 $c->log->debug($error)
1abd6db7 150 if $c->debug;
151 return 0;
152 }
99fe1710 153
1abd6db7 154 }
bd7d2e94 155
156 local $c->request->{arguments} = [ @{$arguments} ];
99fe1710 157
a9dc674c 158 $result->execute($c);
99fe1710 159
1abd6db7 160 return $c->state;
161}
162
fbcc39ad 163=item $self->prepare_action($c)
164
165=cut
166
167sub prepare_action {
168 my ( $self, $c ) = @_;
169 my $path = $c->req->path;
170 my @path = split /\//, $c->req->path;
171 $c->req->args( \my @args );
172
78d760bb 173 push( @path, '/' ) unless @path; # Root action
174
b96f127f 175 DESCEND: while (@path) {
fbcc39ad 176 $path = join '/', @path;
fbcc39ad 177
78d760bb 178 $path = '' if $path eq '/'; # Root action
179
22f3a8dd 180 # Check out dispatch types to see if any will handle the path at
181 # this level
182
78d760bb 183 foreach my $type ( @{ $self->dispatch_types } ) {
2633d7dc 184 last DESCEND if $type->match( $c, $path );
66e28e3f 185 }
b96f127f 186
22f3a8dd 187 # If not, move the last part path to args
188
b96f127f 189 unshift @args, pop @path;
fbcc39ad 190 }
191
192 $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
193 if ( $c->debug && @args );
194}
195
a9dc674c 196=item $self->get_action( $c, $action, $namespace )
1abd6db7 197
198=cut
199
200sub get_action {
a9dc674c 201 my ( $self, $c, $action, $namespace ) = @_;
1abd6db7 202 return [] unless $action;
bcccee4e 203 $namespace ||= '';
772ab8ae 204 $namespace = '' if $namespace eq '/';
99fe1710 205
78d760bb 206 my @match = $self->get_containers($namespace);
c8d9780f 207
a9dc674c 208 my $node = $match[-1]->actions; # Only bother looking at the last one
772ab8ae 209
a9dc674c 210 if ( defined $node->{$action}
211 && ( $node->{$action}->namespace eq $namespace ) )
212 {
213 return $node->{$action};
1abd6db7 214 }
1abd6db7 215}
216
a9dc674c 217=item $self->get_actions( $c, $action, $namespace )
218
219=cut
220
221sub get_actions {
222 my ( $self, $c, $action, $namespace ) = @_;
223 return [] unless $action;
224 $namespace ||= '';
225 $namespace = '' if $namespace eq '/';
226
227 my @match = $self->get_containers($namespace);
228
229 return
230 map { $_->{$action} }
231 grep { defined $_->{$action} } # If it exists in the container
232 map { $_->actions } # Get action hash for container
233 @match
234}
235
cfd04b0c 236=item $self->get_containers( $namespace )
237
238=cut
239
240sub get_containers {
241 my ( $self, $namespace ) = @_;
242
90ce41ba 243 # If the namespace is / just return the root ActionContainer
244
78d760bb 245 return ( $self->tree->getNodeValue )
246 if ( !$namespace || ( $namespace eq '/' ) );
cfd04b0c 247
90ce41ba 248 # Use a visitor to recurse down the tree finding the ActionContainers
249 # for each namespace in the chain.
250
cfd04b0c 251 my $visitor = Tree::Simple::Visitor::FindByPath->new;
78d760bb 252 my @path = split( '/', $namespace );
253 $visitor->setSearchPath(@path);
cfd04b0c 254 $self->tree->accept($visitor);
255
256 my @match = $visitor->getResults;
78d760bb 257 @match = ( $self->tree ) unless @match;
cfd04b0c 258
78d760bb 259 if ( !defined $visitor->getResult ) {
90ce41ba 260
261 # If we don't manage to match, the visitor doesn't return the last
262 # node is matched, so foo/bar/baz would only find the 'foo' node,
263 # not the foo and foo/bar nodes as it should. This does another
264 # single-level search to see if that's the case, and the 'last unless'
265 # should catch any failures - or short-circuit this if this *is* a
266 # bug in the visitor and gets fixed.
267
78d760bb 268 my $extra = $path[ ( scalar @match ) - 1 ];
cfd04b0c 269 last unless $extra;
270 $visitor->setSearchPath($extra);
271 $match[-1]->accept($visitor);
78d760bb 272 push( @match, $visitor->getResult ) if defined $visitor->getResult;
cfd04b0c 273 }
274
275 return map { $_->getNodeValue } @match;
276}
277
11bd4e3e 278=item $self->set_action( $c, $action, $code, $class, $attrs )
1abd6db7 279
280=cut
281
282sub set_action {
11bd4e3e 283 my ( $self, $c, $method, $code, $class, $attrs ) = @_;
1abd6db7 284
11bd4e3e 285 my $namespace =
286 Catalyst::Utils::class2prefix( $class, $c->config->{case_sensitive} )
e494bd6b 287 || '';
b96f127f 288 my %attributes;
1abd6db7 289
290 for my $attr ( @{$attrs} ) {
22f3a8dd 291
292 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
293
6d030e6f 294 my %initialized;
295 $initialized{ ref $_ }++ for @{ $self->dispatch_types };
296
78d760bb 297 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+)\s*\))?$/ ) ) {
6d030e6f 298
299 # Initialize types
300 my $class = "Catalyst::DispatchType::$key";
301 unless ( $initialized{$class} ) {
302 eval "require $class";
303 push( @{ $self->dispatch_types }, $class->new ) unless $@;
304 $initialized{$class}++;
305 }
306
b96f127f 307 if ( defined $value ) {
78d760bb 308 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
b96f127f 309 }
78d760bb 310 push( @{ $attributes{$key} }, $value );
b96f127f 311 }
1abd6db7 312 }
313
6b239949 314 if ( $attributes{Private} && ( keys %attributes > 1 ) ) {
8d4e224b 315 $c->log->debug( 'Bad action definition "'
d0e524d2 316 . join( ' ', @{$attrs} )
11bd4e3e 317 . qq/" for "$class->$method"/ )
8d4e224b 318 if $c->debug;
d0e524d2 319 return;
320 }
6b239949 321 return unless keys %attributes;
1abd6db7 322
fbcc39ad 323 my $parent = $self->tree;
1abd6db7 324 my $visitor = Tree::Simple::Visitor::FindByPath->new;
99fe1710 325
11bd4e3e 326 if ($namespace) {
327 for my $part ( split '/', $namespace ) {
1abd6db7 328 $visitor->setSearchPath($part);
329 $parent->accept($visitor);
b7aebc12 330 my $child = $visitor->getResult;
78d760bb 331
b7aebc12 332 unless ($child) {
90ce41ba 333
334 # Create a new tree node and an ActionContainer to form
335 # its value.
336
78d760bb 337 my $container =
338 Catalyst::ActionContainer->new(
339 { part => $part, actions => {} } );
b7aebc12 340 $child = $parent->addChild( Tree::Simple->new($container) );
341 $visitor->setSearchPath($part);
342 $parent->accept($visitor);
343 $child = $visitor->getResult;
344 }
78d760bb 345
b7aebc12 346 $parent = $child;
1abd6db7 347 }
1abd6db7 348 }
99fe1710 349
11bd4e3e 350 my $reverse = $namespace ? "$namespace/$method" : $method;
fbcc39ad 351
352 my $action = Catalyst::Action->new(
353 {
6b239949 354 name => $method,
b96f127f 355 code => $code,
356 reverse => $reverse,
357 namespace => $namespace,
11bd4e3e 358 class => $class,
b96f127f 359 attributes => \%attributes,
fbcc39ad 360 }
361 );
362
90ce41ba 363 # Set the method value
b7aebc12 364 $parent->getNodeValue->actions->{$method} = $action;
fbcc39ad 365
22f3a8dd 366 # Pass the action to our dispatch types so they can register it if reqd.
b96f127f 367 foreach my $type ( @{ $self->dispatch_types } ) {
2633d7dc 368 $type->register( $c, $action );
b96f127f 369 }
1abd6db7 370}
371
fbcc39ad 372=item $self->setup_actions( $class, $component )
1abd6db7 373
374=cut
375
376sub setup_actions {
11bd4e3e 377 my ( $self, $c ) = @_;
99fe1710 378
6d030e6f 379 $self->dispatch_types( [] );
12e28165 380
6d030e6f 381 # Preload action types
382 for my $type (@PRELOAD) {
383 my $class = "Catalyst::DispatchType::$type";
384 eval "require $class";
385 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
386 if $@;
387 push @{ $self->dispatch_types }, $class->new;
388 }
b96f127f 389
12e28165 390 # We use a tree
78d760bb 391 my $container =
392 Catalyst::ActionContainer->new( { part => '/', actions => {} } );
b7aebc12 393 $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
e494bd6b 394
11bd4e3e 395 for my $comp ( keys %{ $c->components } ) {
e494bd6b 396
397 # We only setup components that inherit from Catalyst::Base
a268a011 398 next unless $comp->isa('Catalyst::Base');
99fe1710 399
812a28c9 400 for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
1abd6db7 401 my ( $code, $attrs ) = @{$action};
402 my $name = '';
403 no strict 'refs';
404 my @cache = ( $comp, @{"$comp\::ISA"} );
11bd4e3e 405 my %classes;
99fe1710 406
11bd4e3e 407 while ( my $class = shift @cache ) {
408 $classes{$class}++;
ba599d1c 409 for my $isa ( @{"$class\::ISA"} ) {
11bd4e3e 410 next if $classes{$isa};
1abd6db7 411 push @cache, $isa;
11bd4e3e 412 $classes{$isa}++;
1abd6db7 413 }
414 }
99fe1710 415
11bd4e3e 416 for my $class ( keys %classes ) {
417 for my $sym ( values %{ $class . '::' } ) {
1abd6db7 418 if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
419 $name = *{$sym}{NAME};
11bd4e3e 420 $self->set_action( $c, $name, $code, $comp, $attrs );
1abd6db7 421 last;
422 }
423 }
424 }
425 }
426 }
e494bd6b 427
2d1d8f91 428 # Postload action types
429 for my $type (@POSTLOAD) {
430 my $class = "Catalyst::DispatchType::$type";
431 eval "require $class";
432 Catalyst::Exception->throw( message => qq/Couldn't load "$class"/ )
433 if $@;
434 push @{ $self->dispatch_types }, $class->new;
435 }
6d030e6f 436
11bd4e3e 437 return unless $c->debug;
99fe1710 438
1abd6db7 439 my $privates = Text::ASCIITable->new;
5fbed090 440 $privates->setCols( 'Private', 'Class' );
441 $privates->setColWidth( 'Private', 36, 1 );
442 $privates->setColWidth( 'Class', 37, 1 );
99fe1710 443
1abd6db7 444 my $walker = sub {
445 my ( $walker, $parent, $prefix ) = @_;
446 $prefix .= $parent->getNodeValue || '';
447 $prefix .= '/' unless $prefix =~ /\/$/;
b7aebc12 448 my $node = $parent->getNodeValue->actions;
99fe1710 449
78d760bb 450 for my $action ( keys %{$node} ) {
b7aebc12 451 my $action_obj = $node->{$action};
b0bb11ec 452 next
453 if ( ( $action =~ /^_.*/ )
454 && ( !$c->config->{show_internal_actions} ) );
11bd4e3e 455 $privates->addRow( "$prefix$action", $action_obj->class );
1abd6db7 456 }
99fe1710 457
1abd6db7 458 $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
459 };
99fe1710 460
1abd6db7 461 $walker->( $walker, $self->tree, '' );
11bd4e3e 462 $c->log->debug( "Loaded Private actions:\n" . $privates->draw )
a268a011 463 if ( @{ $privates->{tbl_rows} } );
99fe1710 464
a9cbd748 465 # List all public actions
11bd4e3e 466 $_->list($c) for @{ $self->dispatch_types };
1abd6db7 467}
468
1abd6db7 469=back
470
471=head1 AUTHOR
472
473Sebastian Riedel, C<sri@cpan.org>
474
475=head1 COPYRIGHT
476
477This program is free software, you can redistribute it and/or modify it under
478the same terms as Perl itself.
479
480=cut
481
4821;