47ec9f0c8db190b300590ded4f54b179979cc9e3
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Controller.pm
1 package Catalyst::Controller;
2
3 use Moose;
4 use Moose::Util qw/find_meta/;
5 use List::MoreUtils qw/uniq/;
6 use namespace::clean -except => 'meta';
7
8 BEGIN { extends qw/Catalyst::Component MooseX::MethodAttributes::Inheritable/; }
9
10 use MooseX::MethodAttributes;
11 use Catalyst::Exception;
12 use Catalyst::Utils;
13
14 with 'Catalyst::Component::ApplicationAttribute';
15
16 has path_prefix =>
17     (
18      is => 'rw',
19      isa => 'Str',
20      init_arg => 'path',
21      predicate => 'has_path_prefix',
22     );
23
24 has action_namespace =>
25     (
26      is => 'rw',
27      isa => 'Str',
28      init_arg => 'namespace',
29      predicate => 'has_action_namespace',
30     );
31
32 has actions =>
33     (
34      accessor => '_controller_actions',
35      isa => 'HashRef',
36      init_arg => undef,
37     );
38
39 sub BUILD {
40     my ($self, $args) = @_;
41     my $action  = delete $args->{action}  || {};
42     my $actions = delete $args->{actions} || {};
43     my $attr_value = $self->merge_config_hashes($actions, $action);
44     $self->_controller_actions($attr_value);
45 }
46
47
48
49 =head1 NAME
50
51 Catalyst::Controller - Catalyst Controller base class
52
53 =head1 SYNOPSIS
54
55   package MyApp::Controller::Search
56   use base qw/Catalyst::Controller/;
57
58   sub foo : Local {
59     my ($self,$c,@args) = @_;
60     ...
61   } # Dispatches to /search/foo
62
63 =head1 DESCRIPTION
64
65 Controllers are where the actions in the Catalyst framework
66 reside. Each action is represented by a function with an attribute to
67 identify what kind of action it is. See the L<Catalyst::Dispatcher>
68 for more info about how Catalyst dispatches to actions.
69
70 =cut
71
72 #I think both of these could be attributes. doesn't really seem like they need
73 #to ble class data. i think that attributes +default would work just fine
74 __PACKAGE__->mk_classdata($_) for qw/_dispatch_steps _action_class/;
75
76 __PACKAGE__->_dispatch_steps( [qw/_BEGIN _AUTO _ACTION/] );
77 __PACKAGE__->_action_class('Catalyst::Action');
78
79
80 sub _DISPATCH : Private {
81     my ( $self, $c ) = @_;
82
83     foreach my $disp ( @{ $self->_dispatch_steps } ) {
84         last unless $c->forward($disp);
85     }
86
87     $c->forward('_END');
88 }
89
90 sub _BEGIN : Private {
91     my ( $self, $c ) = @_;
92     my $begin = ( $c->get_actions( 'begin', $c->namespace ) )[-1];
93     return 1 unless $begin;
94     $begin->dispatch( $c );
95     return !@{ $c->error };
96 }
97
98 sub _AUTO : Private {
99     my ( $self, $c ) = @_;
100     my @auto = $c->get_actions( 'auto', $c->namespace );
101     foreach my $auto (@auto) {
102         $auto->dispatch( $c );
103         return 0 unless $c->state;
104     }
105     return 1;
106 }
107
108 sub _ACTION : Private {
109     my ( $self, $c ) = @_;
110     if (   ref $c->action
111         && $c->action->can('execute')
112         && defined $c->req->action )
113     {
114         $c->action->dispatch( $c );
115     }
116     return !@{ $c->error };
117 }
118
119 sub _END : Private {
120     my ( $self, $c ) = @_;
121     my $end = ( $c->get_actions( 'end', $c->namespace ) )[-1];
122     return 1 unless $end;
123     $end->dispatch( $c );
124     return !@{ $c->error };
125 }
126
127 sub action_for {
128     my ( $self, $name ) = @_;
129     my $app = ($self->isa('Catalyst') ? $self : $self->_application);
130     return $app->dispatcher->get_action($name, $self->action_namespace);
131 }
132
133 #my opinion is that this whole sub really should be a builder method, not
134 #something that happens on every call. Anyone else disagree?? -- groditi
135 ## -- apparently this is all just waiting for app/ctx split
136 around action_namespace => sub {
137     my $orig = shift;
138     my ( $self, $c ) = @_;
139
140     my $class = ref($self) || $self;
141     my $appclass = ref($c) || $c;
142     if( ref($self) ){
143         return $self->$orig if $self->has_action_namespace;
144     } else {
145         return $class->config->{namespace} if exists $class->config->{namespace};
146     }
147
148     my $case_s;
149     if( $c ){
150         $case_s = $appclass->config->{case_sensitive};
151     } else {
152         if ($self->isa('Catalyst')) {
153             $case_s = $class->config->{case_sensitive};
154         } else {
155             if (ref $self) {
156                 $case_s = ref($self->_application)->config->{case_sensitive};
157             } else {
158                 confess("Can't figure out case_sensitive setting");
159             }
160         }
161     }
162
163     my $namespace = Catalyst::Utils::class2prefix($self->catalyst_component_name, $case_s) || '';
164     $self->$orig($namespace) if ref($self);
165     return $namespace;
166 };
167
168 #Once again, this is probably better written as a builder method
169 around path_prefix => sub {
170     my $orig = shift;
171     my $self = shift;
172     if( ref($self) ){
173       return $self->$orig if $self->has_path_prefix;
174     } else {
175       return $self->config->{path} if exists $self->config->{path};
176     }
177     my $namespace = $self->action_namespace(@_);
178     $self->$orig($namespace) if ref($self);
179     return $namespace;
180 };
181
182 sub get_action_methods {
183     my $self = shift;
184     my $meta = find_meta($self) || confess("No metaclass setup for $self");
185     confess("Metaclass "
186           . ref($meta) . " for "
187           . $meta->name
188           . " cannot support register_actions." )
189       unless $meta->can('get_nearest_methods_with_attributes');
190     my @methods = $meta->get_nearest_methods_with_attributes;
191
192     # actions specified via config are also action_methods
193     push(
194         @methods,
195         map {
196             $meta->find_method_by_name($_)
197                 || confess( sprintf 'Action "%s" is not available from controller %s',
198                             $_, ref $self )
199           } keys %{ $self->_controller_actions }
200     ) if ( ref $self );
201     return uniq @methods;
202 }
203
204
205 sub register_actions {
206     my ( $self, $c ) = @_;
207     $self->register_action_methods( $c, $self->get_action_methods );
208 }
209
210 sub register_action_methods {
211     my ( $self, $c, @methods ) = @_;
212     my $class = $self->catalyst_component_name;
213     #this is still not correct for some reason.
214     my $namespace = $self->action_namespace($c);
215
216     # FIXME - fugly
217     if (!blessed($self) && $self eq $c && scalar(@methods)) {
218         my @really_bad_methods = grep { ! /^_(DISPATCH|BEGIN|AUTO|ACTION|END)$/ } map { $_->name } @methods;
219         if (scalar(@really_bad_methods)) {
220             $c->log->warn("Action methods (" . join(', ', @really_bad_methods) . ") found defined in your application class, $self. This is deprecated, please move them into a Root controller.");
221         }
222     }
223
224     foreach my $method (@methods) {
225         my $name = $method->name;
226         # Horrible hack! All method metaclasses should have an attributes
227         # method, core Moose bug - see r13354.
228         my $attributes = $method->can('attributes') ? $method->attributes : [];
229         my $attrs = $self->_parse_attrs( $c, $name, @{ $attributes } );
230         if ( $attrs->{Private} && ( keys %$attrs > 1 ) ) {
231             $c->log->debug( 'Bad action definition "'
232                   . join( ' ', @{ $attributes } )
233                   . qq/" for "$class->$name"/ )
234               if $c->debug;
235             next;
236         }
237         my $reverse = $namespace ? "${namespace}/${name}" : $name;
238         my $action = $self->create_action(
239             name       => $name,
240             code       => $method->body,
241             reverse    => $reverse,
242             namespace  => $namespace,
243             class      => $class,
244             attributes => $attrs,
245         );
246
247         $c->dispatcher->register( $c, $action );
248     }
249 }
250
251 sub action_class {
252     my $self = shift;
253     my %args = @_;
254
255     my $class = (exists $args{attributes}{ActionClass}
256         ? $args{attributes}{ActionClass}[0]
257         : $self->_action_class);
258
259     Class::MOP::load_class($class);
260     return $class;
261 }
262
263 sub create_action {
264     my $self = shift;
265     my %args = @_;
266
267     my $class = $self->action_class(%args);
268     my $action_args = $self->config->{action_args};
269
270     my %extra_args = (
271         %{ $action_args->{'*'}           || {} },
272         %{ $action_args->{ $args{name} } || {} },
273     );
274
275     return $class->new({ %extra_args, %args });
276 }
277
278 sub _parse_attrs {
279     my ( $self, $c, $name, @attrs ) = @_;
280
281     my %raw_attributes;
282
283     foreach my $attr (@attrs) {
284
285         # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
286
287         if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+?)\s*\))?$/ ) )
288         {
289
290             if ( defined $value ) {
291                 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
292             }
293             push( @{ $raw_attributes{$key} }, $value );
294         }
295     }
296
297     my $actions;
298     if( ref($self) ) {
299         $actions = $self->_controller_actions;
300     } else {
301         my $cfg = $self->config;
302         $actions = $self->merge_config_hashes($cfg->{actions}, $cfg->{action});
303     }
304
305     %raw_attributes = ((exists $actions->{'*'} ? %{$actions->{'*'}} : ()),
306                        %raw_attributes,
307                        (exists $actions->{$name} ? %{$actions->{$name}} : ()));
308
309
310     my %final_attributes;
311
312     foreach my $key (keys %raw_attributes) {
313
314         my $raw = $raw_attributes{$key};
315
316         foreach my $value (ref($raw) eq 'ARRAY' ? @$raw : $raw) {
317
318             my $meth = "_parse_${key}_attr";
319             if ( my $code = $self->can($meth) ) {
320                 ( $key, $value ) = $self->$code( $c, $name, $value );
321             }
322             push( @{ $final_attributes{$key} }, $value );
323         }
324     }
325
326     return \%final_attributes;
327 }
328
329 sub _parse_Global_attr {
330     my ( $self, $c, $name, $value ) = @_;
331     return $self->_parse_Path_attr( $c, $name, "/$name" );
332 }
333
334 sub _parse_Absolute_attr { shift->_parse_Global_attr(@_); }
335
336 sub _parse_Local_attr {
337     my ( $self, $c, $name, $value ) = @_;
338     return $self->_parse_Path_attr( $c, $name, $name );
339 }
340
341 sub _parse_Relative_attr { shift->_parse_Local_attr(@_); }
342
343 sub _parse_Path_attr {
344     my ( $self, $c, $name, $value ) = @_;
345     $value = '' if !defined $value;
346     if ( $value =~ m!^/! ) {
347         return ( 'Path', $value );
348     }
349     elsif ( length $value ) {
350         return ( 'Path', join( '/', $self->path_prefix($c), $value ) );
351     }
352     else {
353         return ( 'Path', $self->path_prefix($c) );
354     }
355 }
356
357 sub _parse_Regex_attr {
358     my ( $self, $c, $name, $value ) = @_;
359     return ( 'Regex', $value );
360 }
361
362 sub _parse_Regexp_attr { shift->_parse_Regex_attr(@_); }
363
364 sub _parse_LocalRegex_attr {
365     my ( $self, $c, $name, $value ) = @_;
366     unless ( $value =~ s/^\^// ) { $value = "(?:.*?)$value"; }
367
368     my $prefix = $self->path_prefix( $c );
369     $prefix .= '/' if length( $prefix );
370
371     return ( 'Regex', "^${prefix}${value}" );
372 }
373
374 sub _parse_LocalRegexp_attr { shift->_parse_LocalRegex_attr(@_); }
375
376 sub _parse_Chained_attr {
377     my ($self, $c, $name, $value) = @_;
378
379     if (defined($value) && length($value)) {
380         if ($value eq '.') {
381             $value = '/'.$self->action_namespace($c);
382         } elsif (my ($rel, $rest) = $value =~ /^((?:\.{2}\/)+)(.*)$/) {
383             my @parts = split '/', $self->action_namespace($c);
384             my @levels = split '/', $rel;
385
386             $value = '/'.join('/', @parts[0 .. $#parts - @levels], $rest);
387         } elsif ($value !~ m/^\//) {
388             my $action_ns = $self->action_namespace($c);
389
390             if ($action_ns) {
391                 $value = '/'.join('/', $action_ns, $value);
392             } else {
393                 $value = '/'.$value; # special case namespace '' (root)
394             }
395         }
396     } else {
397         $value = '/'
398     }
399
400     return Chained => $value;
401 }
402
403 sub _parse_ChainedParent_attr {
404     my ($self, $c, $name, $value) = @_;
405     return $self->_parse_Chained_attr($c, $name, '../'.$name);
406 }
407
408 sub _parse_PathPrefix_attr {
409     my ( $self, $c ) = @_;
410     return PathPart => $self->path_prefix($c);
411 }
412
413 sub _parse_ActionClass_attr {
414     my ( $self, $c, $name, $value ) = @_;
415     my $appname = $self->_application;
416     $value = Catalyst::Utils::resolve_namespace($appname . '::Action', $self->_action_class, $value);
417     return ( 'ActionClass', $value );
418 }
419
420 sub _parse_MyAction_attr {
421     my ( $self, $c, $name, $value ) = @_;
422
423     my $appclass = Catalyst::Utils::class2appclass($self);
424     $value = "${appclass}::Action::${value}";
425
426     return ( 'ActionClass', $value );
427 }
428
429 __PACKAGE__->meta->make_immutable;
430
431 1;
432
433 __END__
434
435 =head1 CONFIGURATION
436
437 Like any other L<Catalyst::Component>, controllers have a config hash,
438 accessible through $self->config from the controller actions.  Some
439 settings are in use by the Catalyst framework:
440
441 =head2 namespace
442
443 This specifies the internal namespace the controller should be bound
444 to. By default the controller is bound to the URI version of the
445 controller name. For instance controller 'MyApp::Controller::Foo::Bar'
446 will be bound to 'foo/bar'. The default Root controller is an example
447 of setting namespace to '' (the null string).
448
449 =head2 path
450
451 Sets 'path_prefix', as described below.
452
453 =head2 action
454
455 Allows you to set the attributes that the dispatcher creates actions out of.
456 This allows you to do 'rails style routes', or override some of the
457 attribute defintions of actions composed from Roles.
458 You can set arguments globally (for all actions of the controller) and
459 specifically (for a single action).
460
461     __PACKAGE__->config(
462         action => {
463             '*' => { Chained => 'base', Args => 0  },
464             base => { Chained => '/', PathPart => '', CaptureArgs => 0 },
465         },
466      );
467
468 In the case above every sub in the package would be made into a Chain
469 endpoint with a URI the same as the sub name for each sub, chained
470 to the sub named C<base>. Ergo dispatch to C</example> would call the
471 C<base> method, then the C<example> method.
472
473 =head2 action_args
474
475 Allows you to set constructor arguments on your actions. You can set arguments
476 globally and specifically (as above).
477 This is particularly useful when using C<ActionRole>s
478 (L<Catalyst::Controller::ActionRole>) and custom C<ActionClass>es.
479
480     __PACKAGE__->config(
481         action_args => {
482             '*' => { globalarg1 => 'hello', globalarg2 => 'goodbye' },
483             'specific_action' => { customarg => 'arg1' },
484         },
485      );
486
487 In the case above the action class associated with C<specific_action> would get
488 passed the following arguments, in addition to the normal action constructor
489 arguments, when it is instantiated:
490
491   (globalarg1 => 'hello', globalarg2 => 'goodbye', customarg => 'arg1')
492
493 =head1 METHODS
494
495 =head2 BUILDARGS ($app, @args)
496
497 From L<Catalyst::Component::ApplicationAttribute>, stashes the application
498 instance as $self->_application.
499
500 =head2 $self->action_for('name')
501
502 Returns the Catalyst::Action object (if any) for a given method name
503 in this component.
504
505 =head2 $self->action_namespace($c)
506
507 Returns the private namespace for actions in this component. Defaults
508 to a value from the controller name (for
509 e.g. MyApp::Controller::Foo::Bar becomes "foo/bar") or can be
510 overridden from the "namespace" config key.
511
512
513 =head2 $self->path_prefix($c)
514
515 Returns the default path prefix for :PathPrefix, :Local, :LocalRegex and
516 relative :Path actions in this component. Defaults to the action_namespace or
517 can be overridden from the "path" config key.
518
519 =head2 $self->register_actions($c)
520
521 Finds all applicable actions for this component, creates
522 Catalyst::Action objects (using $self->create_action) for them and
523 registers them with $c->dispatcher.
524
525 =head2 $self->get_action_methods()
526
527 Returns a list of L<Moose::Meta::Method> objects, doing the
528 L<MooseX::MethodAttributes::Role::Meta::Method> role, which are the set of
529 action methods for this package.
530
531 =head2 $self->register_action_methods($c, @methods)
532
533 Creates action objects for a set of action methods using C< create_action >,
534 and registers them with the dispatcher.
535
536 =head2 $self->action_class(%args)
537
538 Used when a controller is creating an action to determine the correct base
539 action class to use.
540
541 =head2 $self->create_action(%args)
542
543 Called with a hash of data to be use for construction of a new
544 Catalyst::Action (or appropriate sub/alternative class) object.
545
546 =head2 $self->_application
547
548 =head2 $self->_app
549
550 Returns the application instance stored by C<new()>
551
552 =head1 AUTHORS
553
554 Catalyst Contributors, see Catalyst.pm
555
556 =head1 COPYRIGHT
557
558 This library is free software. You can redistribute it and/or modify
559 it under the same terms as Perl itself.
560
561 =cut