- Dispatcher refactor, part trois
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Dispatcher.pm
1 package Catalyst::Dispatcher;
2
3 use strict;
4 use base 'Class::Accessor::Fast';
5 use Catalyst::Exception;
6 use Catalyst::Utils;
7 use Catalyst::Action;
8 use Catalyst::ActionContainer;
9 use Text::ASCIITable;
10 use Tree::Simple;
11 use Tree::Simple::Visitor::FindByPath;
12
13 # Stringify to class
14 use overload '""' => sub { return ref shift }, fallback => 1;
15
16 __PACKAGE__->mk_accessors(qw/actions tree/);
17
18 =head1 NAME
19
20 Catalyst::Dispatcher - The Catalyst Dispatcher
21
22 =head1 SYNOPSIS
23
24 See L<Catalyst>.
25
26 =head1 DESCRIPTION
27
28 =head1 METHODS
29
30 =over 4
31
32 =item $self->detach( $c, $command [, \@arguments ] )
33
34 =cut
35
36 sub detach {
37     my ( $self, $c, $command, @args ) = @_;
38     $c->forward( $command, @args ) if $command;
39     die $Catalyst::DETACH;
40 }
41
42 =item $self->dispatch($c)
43
44 =cut
45
46 sub dispatch {
47     my ( $self, $c ) = @_;
48     my $action    = $c->req->action;
49     my $namespace = '';
50     $namespace = ( join( '/', @{ $c->req->args } ) || '/' )
51       if $action eq 'default';
52
53     unless ($namespace) {
54         if ( my $result = $c->get_action($action) ) {
55             $namespace =
56               Catalyst::Utils::class2prefix( $result->[0]->[0]->namespace,
57                 $c->config->{case_sensitive} );
58         }
59     }
60
61     my $default = $action eq 'default' ? $namespace : undef;
62     my $results = $c->get_action( $action, $default, $default ? 1 : 0 );
63     $namespace ||= '/';
64
65     if ( @{$results} ) {
66
67         # Errors break the normal flow and the end action is instantly run
68         my $error = 0;
69
70         # Execute last begin
71         $c->state(1);
72         if ( my $begin = @{ $c->get_action( 'begin', $namespace, 1 ) }[-1] ) {
73             $begin->[0]->execute($c);
74             $error++ if scalar @{ $c->error };
75         }
76
77         # Execute the auto chain
78         my $autorun = 0;
79         for my $auto ( @{ $c->get_action( 'auto', $namespace, 1 ) } ) {
80             last if $error;
81             $autorun++;
82             $auto->[0]->execute($c);
83             $error++ if scalar @{ $c->error };
84             last unless $c->state;
85         }
86
87         # Execute the action or last default
88         my $mkay = $autorun ? $c->state ? 1 : 0 : 1;
89         if ( ( my $action = $c->req->action ) && $mkay ) {
90             unless ($error) {
91                 if ( my $result =
92                     @{ $c->get_action( $action, $default, 1 ) }[-1] )
93                 {
94                     $result->[0]->execute($c);
95                     $error++ if scalar @{ $c->error };
96                 }
97             }
98         }
99
100         # Execute last end
101         if ( my $end = @{ $c->get_action( 'end', $namespace, 1 ) }[-1] ) {
102             $end->[0]->execute($c);
103         }
104     }
105
106     else {
107         my $path  = $c->req->path;
108         my $error = $path
109           ? qq/Unknown resource "$path"/
110           : "No default action defined";
111         $c->log->error($error) if $c->debug;
112         $c->error($error);
113     }
114 }
115
116 =item $self->forward( $c, $command [, \@arguments ] )
117
118 =cut
119
120 sub forward {
121     my $self    = shift;
122     my $c       = shift;
123     my $command = shift;
124
125     unless ($command) {
126         $c->log->debug('Nothing to forward to') if $c->debug;
127         return 0;
128     }
129
130     # Relative forwards from detach
131     my $caller = ( caller(1) )[0]->isa('Catalyst::Dispatcher')
132       && ( ( caller(2) )[3] =~ /::detach$/ ) ? caller(3) : caller(1);
133
134     my $arguments = ( ref( $_[-1] ) eq 'ARRAY' ) ? pop(@_) : $c->req->args;
135
136     my $results = [];
137
138     my $command_copy = $command;
139
140     unless ( $command_copy =~ s/^\/// ) {
141         my $namespace =
142           Catalyst::Utils::class2prefix( $caller, $c->config->{case_sensitive} ) || '';
143         $command_copy = "${namespace}/${command}";
144     }
145
146     unless ( $command_copy =~ /\// ) {
147         $results = $c->get_action( $command_copy, '/' );
148     }
149     else {
150         my @extra_args;
151       DESCEND: while ( $command_copy =~ s/^(.*)\/(\w+)$/$1/ ) {
152             my $tail = $2;
153             $results = $c->get_action( $tail, $1 );
154             if ( @{$results} ) {
155                 $command = $tail;
156                 push( @{$arguments}, @extra_args );
157                 last DESCEND;
158             }
159             unshift( @extra_args, $tail );
160         }
161     }
162
163     unless ( @{$results} ) {
164
165         unless ( $c->components->{$command} ) {
166             my $error =
167 qq/Couldn't forward to command "$command". Invalid action or component./;
168             $c->error($error);
169             $c->log->debug($error) if $c->debug;
170             return 0;
171         }
172
173         my $class  = $command;
174         my $method = shift || 'process';
175
176         if ( my $code = $c->components->{$class}->can($method) ) {
177             my $action = Catalyst::Action->new(
178                 {
179                     code      => $code,
180                     reverse   => "$class->$method",
181                     namespace => $class,
182                 }
183             );
184             $results = [ [$action] ];
185         }
186
187         else {
188             my $error =
189               qq/Couldn't forward to "$class". Does not implement "$method"/;
190             $c->error($error);
191             $c->log->debug($error)
192               if $c->debug;
193             return 0;
194         }
195
196     }
197
198     local $c->request->{arguments} = [ @{$arguments} ];
199
200     for my $result ( @{$results} ) {
201         $result->[0]->execute($c);
202         return if scalar @{ $c->error };
203         last unless $c->state;
204     }
205
206     return $c->state;
207 }
208
209 =item $self->prepare_action($c)
210
211 =cut
212
213 sub prepare_action {
214     my ( $self, $c ) = @_;
215     my $path = $c->req->path;
216     my @path = split /\//, $c->req->path;
217     $c->req->args( \my @args );
218
219     while (@path) {
220         $path = join '/', @path;
221         if ( my $result = ${ $c->get_action($path) }[0] ) {
222
223             # It's a regex
224             if ($#$result) {
225                 my $match    = $result->[1];
226                 my @snippets = @{ $result->[2] };
227                 $c->log->debug(
228                     qq/Requested action is "$path" and matched "$match"/)
229                   if $c->debug;
230                 $c->log->debug(
231                     'Snippets are "' . join( ' ', @snippets ) . '"' )
232                   if ( $c->debug && @snippets );
233                 $c->req->action($match);
234                 $c->req->snippets( \@snippets );
235             }
236
237             else {
238                 $c->req->action($path);
239                 $c->log->debug(qq/Requested action is "$path"/) if $c->debug;
240             }
241
242             $c->req->match($path);
243             last;
244         }
245         unshift @args, pop @path;
246     }
247
248     unless ( $c->req->action ) {
249         $c->req->action('default');
250         $c->req->match('');
251     }
252
253     $c->log->debug( 'Arguments are "' . join( '/', @args ) . '"' )
254       if ( $c->debug && @args );
255 }
256
257 =item $self->get_action( $c, $action, $namespace, $inherit )
258
259 =cut
260
261 sub get_action {
262     my ( $self, $c, $action, $namespace, $inherit ) = @_;
263     return [] unless $action;
264     $namespace ||= '';
265     $inherit   ||= 0;
266
267     if ($namespace) {
268
269         my $parent = $self->tree;
270         my @match;
271
272         if ($namespace ne '/') {
273
274             my $visitor = Tree::Simple::Visitor::FindByPath->new;
275             my @path = split('/', $namespace);
276             $visitor->setSearchPath( @path );
277             $parent->accept($visitor);
278
279             if ($inherit) {
280
281                 @match = $visitor->getResults;
282                 @match = ($parent) unless @match;
283
284                 if (!defined $visitor->getResult) {
285                     my $extra = $path[(scalar @match) - 1];
286                     last unless $extra;
287                     $visitor->setSearchPath($extra);
288                     $match[-1]->accept($visitor);
289                     push(@match, $visitor->getResult) if defined $visitor->getResult;
290                 }
291             } else {
292                 @match = ($visitor->getResult) if $visitor->getResult;
293             }
294
295         }
296
297         @match = ($parent) unless @match;
298
299         my @results;
300
301         foreach my $child (@match) {
302             my $node = $child->getNodeValue->actions;
303             push(@results, [ $node->{$action} ]) if defined $node->{$action};
304         }
305         return \@results;
306     }
307
308     elsif ( my $p = $self->actions->{plain}->{$action} ) { return [ [$p] ] }
309     elsif ( my $r = $self->actions->{regex}->{$action} ) { return [ [$r] ] }
310
311     else {
312
313         for my $i ( 0 .. $#{ $self->actions->{compiled} } ) {
314             my $name  = $self->actions->{compiled}->[$i]->[0];
315             my $regex = $self->actions->{compiled}->[$i]->[1];
316
317             if ( my @snippets = ( $action =~ $regex ) ) {
318                 return [
319                     [ $self->actions->{regex}->{$name}, $name, \@snippets ] ];
320             }
321
322         }
323     }
324     return [];
325 }
326
327 =item $self->set_action( $c, $action, $code, $namespace, $attrs )
328
329 =cut
330
331 sub set_action {
332     my ( $self, $c, $method, $code, $namespace, $attrs ) = @_;
333
334     my $prefix =
335       Catalyst::Utils::class2prefix( $namespace, $c->config->{case_sensitive} )
336       || '';
337     my %flags;
338
339     for my $attr ( @{$attrs} ) {
340         if    ( $attr =~ /^(Local|Relative)$/ )    { $flags{local}++ }
341         elsif ( $attr =~ /^(Global|Absolute)$/ )   { $flags{global}++ }
342         elsif ( $attr =~ /^Path\(\s*(.+)\s*\)$/i ) {
343             push @{ $flags{path} }, $1;
344         }
345         elsif ( $attr =~ /^Private$/i ) { $flags{private}++ }
346         elsif ( $attr =~ /^(Regex|Regexp)\(\s*(.+)\s*\)$/i ) {
347             push @{ $flags{regex} }, $2;
348         }
349     }
350
351     if ( $flags{private} && ( keys %flags > 1 ) ) {
352         $c->log->debug( 'Bad action definition "'
353               . join( ' ', @{$attrs} )
354               . qq/" for "$namespace->$method"/ )
355           if $c->debug;
356         return;
357     }
358     return unless keys %flags;
359
360     my $parent  = $self->tree;
361     my $visitor = Tree::Simple::Visitor::FindByPath->new;
362
363     if ($prefix) {
364         for my $part ( split '/', $prefix ) {
365             $visitor->setSearchPath($part);
366             $parent->accept($visitor);
367             my $child = $visitor->getResult;
368     
369             unless ($child) {
370                 my $container = Catalyst::ActionContainer->new(
371                                     { part => $part, actions => {} });
372                 $child = $parent->addChild( Tree::Simple->new($container) );
373                 $visitor->setSearchPath($part);
374                 $parent->accept($visitor);
375                 $child = $visitor->getResult;
376             }
377     
378             $parent = $child;
379         }
380     }
381
382     my $reverse = $prefix ? "$prefix/$method" : $method;
383
384     my $action = Catalyst::Action->new(
385         {
386             code      => $code,
387             reverse   => $reverse,
388             namespace => $namespace,
389         }
390     );
391
392     $parent->getNodeValue->actions->{$method} = $action;
393
394     my @path;
395     for my $path ( @{ $flags{path} } ) {
396         $path =~ s/^\w+//;
397         $path =~ s/\w+$//;
398         if ( $path =~ /^\s*'(.*)'\s*$/ ) { $path = $1 }
399         if ( $path =~ /^\s*"(.*)"\s*$/ ) { $path = $1 }
400         push @path, $path;
401     }
402     $flags{path} = \@path;
403
404     my @regex;
405     for my $regex ( @{ $flags{regex} } ) {
406         $regex =~ s/^\w+//;
407         $regex =~ s/\w+$//;
408         if ( $regex =~ /^\s*'(.*)'\s*$/ ) { $regex = $1 }
409         if ( $regex =~ /^\s*"(.*)"\s*$/ ) { $regex = $1 }
410         push @regex, $regex;
411     }
412     $flags{regex} = \@regex;
413
414     if ( $flags{local} || $flags{global} ) {
415         push( @{ $flags{path} }, $prefix ? "/$prefix/$method" : "/$method" )
416           if $flags{local};
417
418         push( @{ $flags{path} }, "/$method" ) if $flags{global};
419     }
420
421     for my $path ( @{ $flags{path} } ) {
422         if ( $path =~ /^\// ) { $path =~ s/^\/// }
423         else { $path = $prefix ? "$prefix/$path" : $path }
424         $self->actions->{plain}->{$path} = $action;
425     }
426
427     for my $regex ( @{ $flags{regex} } ) {
428         push @{ $self->actions->{compiled} }, [ $regex, qr#$regex# ];
429         $self->actions->{regex}->{$regex} = $action;
430     }
431 }
432
433 =item $self->setup_actions( $class, $component )
434
435 =cut
436
437 sub setup_actions {
438     my ( $self, $class ) = @_;
439
440     # These are the core structures
441     $self->actions(
442         {
443             plain    => {},
444             private  => {},
445             regex    => {},
446             compiled => []
447         }
448     );
449
450     # We use a tree
451     my $container = Catalyst::ActionContainer->new(
452                         { part => '/', actions => {} } );
453     $self->tree( Tree::Simple->new( $container, Tree::Simple->ROOT ) );
454
455     for my $comp ( keys %{ $class->components } ) {
456
457         # We only setup components that inherit from Catalyst::Base
458         next unless $comp->isa('Catalyst::Base');
459
460         for my $action ( @{ Catalyst::Utils::reflect_actions($comp) } ) {
461             my ( $code, $attrs ) = @{$action};
462             my $name = '';
463             no strict 'refs';
464             my @cache = ( $comp, @{"$comp\::ISA"} );
465             my %namespaces;
466
467             while ( my $namespace = shift @cache ) {
468                 $namespaces{$namespace}++;
469                 for my $isa ( @{"$comp\::ISA"} ) {
470                     next if $namespaces{$isa};
471                     push @cache, $isa;
472                     $namespaces{$isa}++;
473                 }
474             }
475
476             for my $namespace ( keys %namespaces ) {
477
478                 for my $sym ( values %{ $namespace . '::' } ) {
479
480                     if ( *{$sym}{CODE} && *{$sym}{CODE} == $code ) {
481
482                         $name = *{$sym}{NAME};
483                         $class->set_action( $name, $code, $comp, $attrs );
484                         last;
485                     }
486
487                 }
488
489             }
490
491         }
492
493     }
494
495     return unless $class->debug;
496
497     my $actions  = $self->actions;
498     my $privates = Text::ASCIITable->new;
499     $privates->setCols( 'Private', 'Class' );
500     $privates->setColWidth( 'Private', 36, 1 );
501     $privates->setColWidth( 'Class',   37, 1 );
502
503     my $walker = sub {
504         my ( $walker, $parent, $prefix ) = @_;
505         $prefix .= $parent->getNodeValue || '';
506         $prefix .= '/' unless $prefix =~ /\/$/;
507         my $node = $parent->getNodeValue->actions;
508
509         for my $action ( keys %{ $node } ) {
510             my $action_obj = $node->{$action};
511             $privates->addRow( "$prefix$action", $action_obj->namespace );
512         }
513
514         $walker->( $walker, $_, $prefix ) for $parent->getAllChildren;
515     };
516
517     $walker->( $walker, $self->tree, '' );
518     $class->log->debug( "Loaded private actions:\n" . $privates->draw )
519       if ( @{ $privates->{tbl_rows} } );
520
521     my $publics = Text::ASCIITable->new;
522     $publics->setCols( 'Public', 'Private' );
523     $publics->setColWidth( 'Public',  36, 1 );
524     $publics->setColWidth( 'Private', 37, 1 );
525
526     for my $plain ( sort keys %{ $actions->{plain} } ) {
527         my $action = $actions->{plain}->{$plain};
528         $publics->addRow( "/$plain", "/$action" );
529     }
530
531     $class->log->debug( "Loaded public actions:\n" . $publics->draw )
532       if ( @{ $publics->{tbl_rows} } );
533
534     my $regexes = Text::ASCIITable->new;
535     $regexes->setCols( 'Regex', 'Private' );
536     $regexes->setColWidth( 'Regex',   36, 1 );
537     $regexes->setColWidth( 'Private', 37, 1 );
538
539     for my $regex ( sort keys %{ $actions->{regex} } ) {
540         my $action = $actions->{regex}->{$regex};
541         $regexes->addRow( $regex, "/$action" );
542     }
543
544     $class->log->debug( "Loaded regex actions:\n" . $regexes->draw )
545       if ( @{ $regexes->{tbl_rows} } );
546 }
547
548 =back
549
550 =head1 AUTHOR
551
552 Sebastian Riedel, C<sri@cpan.org>
553
554 =head1 COPYRIGHT
555
556 This program is free software, you can redistribute it and/or modify it under
557 the same terms as Perl itself.
558
559 =cut
560
561 1;