a76337e11523d64e2433ffcf0e3bb93a79b9b3ff
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Controller.pm
1 package Catalyst::Controller;
2
3 #switch to BEGIN { extends qw/ ... /; } ?
4 use Class::C3;
5 use base qw/Catalyst::Component Catalyst::AttrContainer/;
6 use Moose;
7
8 use Scalar::Util qw/blessed/;
9 use Catalyst::Exception;
10 use Catalyst::Utils;
11 use Class::Inspector;
12
13 has path_prefix =>
14     (
15      is => 'rw',
16      isa => 'Str',
17      init_arg => 'path',
18      predicate => 'has_path_prefix',
19     );
20
21 has action_namespace =>
22     (
23      is => 'rw',
24      isa => 'Str',
25      init_arg => 'namespace',
26      predicate => 'has_action_namespace',
27     );
28
29 has actions =>
30     (
31      is => 'rw',
32      isa => 'HashRef',
33      init_arg => undef,
34     );
35
36 # isa => 'ClassName|Catalyst' ?
37 has _application => (is => 'rw');
38 sub _app{ shift->_application(@_) } 
39
40 sub BUILD {
41     my ($self, $args) = @_;
42     my $action  = delete $args->{action}  || {};
43     my $actions = delete $args->{actions} || {};
44     my $attr_value = $self->merge_config_hashes($actions, $action);
45     $self->actions($attr_value);
46 }
47
48 =head1 NAME
49
50 Catalyst::Controller - Catalyst Controller base class
51
52 =head1 SYNOPSIS
53
54   package MyApp::Controller::Search
55   use base qw/Catalyst::Controller/;
56
57   sub foo : Local { 
58     my ($self,$c,@args) = @_;
59     ... 
60   } # Dispatches to /search/foo
61
62 =head1 DESCRIPTION
63
64 Controllers are where the actions in the Catalyst framework
65 reside. Each action is represented by a function with an attribute to
66 identify what kind of action it is. See the L<Catalyst::Dispatcher>
67 for more info about how Catalyst dispatches to actions.
68
69 =cut
70
71 #I think both of these could be attributes. doesn't really seem like they need
72 #to ble class data. i think that attributes +default would work just fine
73 __PACKAGE__->mk_classdata($_) for qw/_dispatch_steps _action_class/;
74
75 __PACKAGE__->_dispatch_steps( [qw/_BEGIN _AUTO _ACTION/] );
76 __PACKAGE__->_action_class('Catalyst::Action');
77
78
79 sub _DISPATCH : Private {
80     my ( $self, $c ) = @_;
81
82     foreach my $disp ( @{ $self->_dispatch_steps } ) {
83         last unless $c->forward($disp);
84     }
85
86     $c->forward('_END');
87 }
88
89 sub _BEGIN : Private {
90     my ( $self, $c ) = @_;
91     my $begin = ( $c->get_actions( 'begin', $c->namespace ) )[-1];
92     return 1 unless $begin;
93     $begin->dispatch( $c );
94     return !@{ $c->error };
95 }
96
97 sub _AUTO : Private {
98     my ( $self, $c ) = @_;
99     my @auto = $c->get_actions( 'auto', $c->namespace );
100     foreach my $auto (@auto) {
101         $auto->dispatch( $c );
102         return 0 unless $c->state;
103     }
104     return 1;
105 }
106
107 sub _ACTION : Private {
108     my ( $self, $c ) = @_;
109     if (   ref $c->action
110         && $c->action->can('execute')
111         && $c->req->action )
112     {
113         $c->action->dispatch( $c );
114     }
115     return !@{ $c->error };
116 }
117
118 sub _END : Private {
119     my ( $self, $c ) = @_;
120     my $end = ( $c->get_actions( 'end', $c->namespace ) )[-1];
121     return 1 unless $end;
122     $end->dispatch( $c );
123     return !@{ $c->error };
124 }
125
126 sub new {
127     my $self = shift;
128     my $app = $_[0];
129     my $new = $self->next::method(@_);
130     $new->_application( $app );
131     return $new;
132 }
133
134 sub action_for {
135     my ( $self, $name ) = @_;
136     my $app = ($self->isa('Catalyst') ? $self : $self->_application);
137     return $app->dispatcher->get_action($name, $self->action_namespace);
138 }
139
140 #my opinion is that this whole sub really should be a builder method, not 
141 #something that happens on every call. Anyone else disagree?? -- groditi
142
143 #we are wrapping the accessor, so just uyse a modifier since a normal sub would
144 #just be overridden by the generated moose method 
145 around action_namespace => sub {
146     my $orig = shift;
147     my ( $self, $c ) = @_;
148
149     if( ref($self) ){
150         return $self->$orig if $self->has_action_namespace;
151     } else { 
152        warn "action_namespace called as class method";
153        # if the following won't change at runtime it should be lazy_building thing
154         return $self->config->{namespace} if exists $self->config->{namespace};
155     }
156
157     #the following looks like a possible target for a default setting. i am not
158     #making the below the builder because i don't know if $c will vary from
159     #call to call, which would affect case sensitivity settings -- groditi
160     my $case_s;
161     if( $c ){
162         $case_s = $c->config->{case_sensitive};
163     } else {
164         if ($self->isa('Catalyst')) {
165             $case_s = $self->config->{case_sensitive};
166         } else {
167             if (ref $self) {
168                 $case_s = $self->_application->config->{case_sensitive};
169             } else {
170                 confess("Can't figure out case_sensitive setting");
171             }
172         }
173     }
174
175     my $namespace = Catalyst::Utils::class2prefix(ref($self) || $self, $case_s) || '';
176     $self->$orig($namespace) if ref($self);
177     return $namespace;
178 };
179
180 #Once again, this is probably better written as a builder method
181 around path_prefix => sub {
182     my $orig = shift;
183     my $self = shift;
184     if( ref($self) ){
185       return $self->$orig if $self->has_path_prefix;
186     } else {
187       return $self->config->{path} if exists $self->config->{path};
188     }
189     my $namespace = $self->action_namespace(@_);
190     $self->$orig($namespace) if ref($self);
191     return $namespace;
192 };
193
194
195 sub register_actions {
196     my ( $self, $c ) = @_;
197     my $class = ref $self || $self;
198     #this is still not correct for some reason.
199     my $namespace = $self->action_namespace($c);
200     my $meta = $self->meta;
201     my %methods = map{ $_->{code}->body => $_->{name} }
202         grep {$_->{class} ne 'Moose::Object'} #ignore Moose::Object methods
203             $meta->compute_all_applicable_methods;
204
205
206     # Advanced inheritance support for plugins and the like
207     #moose todo: migrate to eliminate CDI compat
208     my @action_cache;
209     for my $isa ( $meta->superclasses, $class ) {
210         if(my $coderef = $isa->can('_action_cache')){
211             push(@action_cache, @{ $isa->$coderef });
212         }
213     }
214
215     foreach my $cache (@action_cache) {
216         my $code   = $cache->[0];
217         my $method = delete $methods{$code}; # avoid dupe registers
218         next unless $method;
219         my $attrs = $self->_parse_attrs( $c, $method, @{ $cache->[1] } );
220         if ( $attrs->{Private} && ( keys %$attrs > 1 ) ) {
221             $c->log->debug( 'Bad action definition "'
222                   . join( ' ', @{ $cache->[1] } )
223                   . qq/" for "$class->$method"/ )
224               if $c->debug;
225             next;
226         }
227         my $reverse = $namespace ? "${namespace}/${method}" : $method;
228         my $action = $self->create_action(
229             name       => $method,
230             code       => $code,
231             reverse    => $reverse,
232             namespace  => $namespace,
233             class      => $class,
234             attributes => $attrs,
235         );
236
237         $c->dispatcher->register( $c, $action );
238     }
239 }
240
241 sub create_action {
242     my $self = shift;
243     my %args = @_;
244
245     my $class = (exists $args{attributes}{ActionClass}
246                     ? $args{attributes}{ActionClass}[0]
247                     : $self->_action_class);
248
249     Class::MOP::load_class($class);
250     return $class->new( \%args );
251 }
252
253 sub _parse_attrs {
254     my ( $self, $c, $name, @attrs ) = @_;
255
256     my %raw_attributes;
257
258     foreach my $attr (@attrs) {
259
260         # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
261
262         if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+?)\s*\))?$/ ) )
263         {
264
265             if ( defined $value ) {
266                 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
267             }
268             push( @{ $raw_attributes{$key} }, $value );
269         }
270     }
271
272     #I know that the original behavior was to ignore action if actions was set
273     # but i actually think this may be a little more sane? we can always remove
274     # the merge behavior quite easily and go back to having actions have
275     # presedence over action by modifying the keys. i honestly think this is
276     # superior while mantaining really high degree of compat
277     my $actions;
278     if( ref($self) ) {
279         $actions = $self->actions;
280     } else {
281         my $cfg = $self->config;
282         $actions = $self->merge_config_hashes($cfg->{actions}, $cfg->{action});
283     }
284
285     %raw_attributes = ((exists $actions->{'*'} ? %{$actions->{'*'}} : ()),
286                        %raw_attributes,
287                        (exists $actions->{$name} ? %{$actions->{$name}} : ()));
288
289
290     my %final_attributes;
291
292     foreach my $key (keys %raw_attributes) {
293
294         my $raw = $raw_attributes{$key};
295
296         foreach my $value (ref($raw) eq 'ARRAY' ? @$raw : $raw) {
297
298             my $meth = "_parse_${key}_attr";
299             if ( my $code = $self->can($meth) ) {
300                 ( $key, $value ) = $self->$code( $c, $name, $value );
301             }
302             push( @{ $final_attributes{$key} }, $value );
303         }
304     }
305
306     return \%final_attributes;
307 }
308
309 sub _parse_Global_attr {
310     my ( $self, $c, $name, $value ) = @_;
311     return $self->_parse_Path_attr( $c, $name, "/$name" );
312 }
313
314 sub _parse_Absolute_attr { shift->_parse_Global_attr(@_); }
315
316 sub _parse_Local_attr {
317     my ( $self, $c, $name, $value ) = @_;
318     return $self->_parse_Path_attr( $c, $name, $name );
319 }
320
321 sub _parse_Relative_attr { shift->_parse_Local_attr(@_); }
322
323 sub _parse_Path_attr {
324     my ( $self, $c, $name, $value ) = @_;
325     $value ||= '';
326     if ( $value =~ m!^/! ) {
327         return ( 'Path', $value );
328     }
329     elsif ( length $value ) {
330         return ( 'Path', join( '/', $self->path_prefix($c), $value ) );
331     }
332     else {
333         return ( 'Path', $self->path_prefix($c) );
334     }
335 }
336
337 sub _parse_Regex_attr {
338     my ( $self, $c, $name, $value ) = @_;
339     return ( 'Regex', $value );
340 }
341
342 sub _parse_Regexp_attr { shift->_parse_Regex_attr(@_); }
343
344 sub _parse_LocalRegex_attr {
345     my ( $self, $c, $name, $value ) = @_;
346     unless ( $value =~ s/^\^// ) { $value = "(?:.*?)$value"; }
347     return ( 'Regex', '^' . $self->path_prefix($c) . "/${value}" );
348 }
349
350 sub _parse_LocalRegexp_attr { shift->_parse_LocalRegex_attr(@_); }
351
352 sub _parse_ActionClass_attr {
353     my ( $self, $c, $name, $value ) = @_;
354     unless ( $value =~ s/^\+// ) {
355       $value = join('::', $self->_action_class, $value );
356     }
357     return ( 'ActionClass', $value );
358 }
359
360 sub _parse_MyAction_attr {
361     my ( $self, $c, $name, $value ) = @_;
362
363     my $appclass = Catalyst::Utils::class2appclass($self);
364     $value = "${appclass}::Action::${value}";
365
366     return ( 'ActionClass', $value );
367 }
368
369 no Moose;
370
371 1;
372
373 __END__
374
375 =head1 CONFIGURATION
376
377 Like any other L<Catalyst::Component>, controllers have a config hash,
378 accessible through $self->config from the controller actions.  Some
379 settings are in use by the Catalyst framework:
380
381 =head2 namespace
382
383 This specifies the internal namespace the controller should be bound
384 to. By default the controller is bound to the URI version of the
385 controller name. For instance controller 'MyApp::Controller::Foo::Bar'
386 will be bound to 'foo/bar'. The default Root controller is an example
387 of setting namespace to '' (the null string).
388
389 =head2 path 
390
391 Sets 'path_prefix', as described below.
392
393 =head1 METHODS
394
395 =head2 $class->new($app, @args)
396
397 Proxies through to NEXT::new and stashes the application instance as
398 $self->_application.
399
400 =head2 $self->action_for('name')
401
402 Returns the Catalyst::Action object (if any) for a given method name
403 in this component.
404
405 =head2 $self->register_actions($c)
406
407 Finds all applicable actions for this component, creates
408 Catalyst::Action objects (using $self->create_action) for them and
409 registers them with $c->dispatcher.
410
411 =head2 $self->action_namespace($c)
412
413 Returns the private namespace for actions in this component. Defaults
414 to a value from the controller name (for
415 e.g. MyApp::Controller::Foo::Bar becomes "foo/bar") or can be
416 overridden from the "namespace" config key.
417
418
419 =head2 $self->path_prefix($c)
420
421 Returns the default path prefix for :Local, :LocalRegex and relative
422 :Path actions in this component. Defaults to the action_namespace or
423 can be overridden from the "path" config key.
424
425 =head2 $self->create_action(%args)
426
427 Called with a hash of data to be use for construction of a new
428 Catalyst::Action (or appropriate sub/alternative class) object.
429
430 Primarily designed for the use of register_actions.
431
432 =head2 $self->_application
433
434 =head2 $self->_app
435
436 Returns the application instance stored by C<new()>
437
438 =head1 AUTHOR
439
440 Sebastian Riedel, C<sri@oook.de>
441 Marcus Ramberg C<mramberg@cpan.org>
442
443 =head1 COPYRIGHT
444
445 This program is free software, you can redistribute it and/or modify
446 it under the same terms as Perl itself.
447
448 =cut