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