fix side effects of messing with catalyst_component_name
[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;
b527cc7d 157
158 # FIXME - catalyst_component_name is no longer a class accessor, because
159 # 'MyApp as a controller' behavior is removed. But is this call to
160 # catalyst_component_name necessary, or is it always the same as $class?
161 my $component_name = ref($self) ? $self->catalyst_component_name : $self;
162
ae29b412 163 if( ref($self) ){
164 return $self->$orig if $self->has_action_namespace;
165 } else {
df960201 166 return $class->config->{namespace} if exists $class->config->{namespace};
234763d4 167 }
234763d4 168
ae29b412 169 my $case_s;
170 if( $c ){
df960201 171 $case_s = $appclass->config->{case_sensitive};
ae29b412 172 } else {
173 if ($self->isa('Catalyst')) {
df960201 174 $case_s = $class->config->{case_sensitive};
ae29b412 175 } else {
176 if (ref $self) {
df960201 177 $case_s = ref($self->_application)->config->{case_sensitive};
ae29b412 178 } else {
179 confess("Can't figure out case_sensitive setting");
180 }
181 }
234763d4 182 }
ae29b412 183
b527cc7d 184 my $namespace = Catalyst::Utils::class2prefix($component_name, $case_s) || '';
ae29b412 185 $self->$orig($namespace) if ref($self);
186 return $namespace;
187};
188
189#Once again, this is probably better written as a builder method
190around path_prefix => sub {
191 my $orig = shift;
192 my $self = shift;
193 if( ref($self) ){
194 return $self->$orig if $self->has_path_prefix;
195 } else {
196 return $self->config->{path} if exists $self->config->{path};
197 }
198 my $namespace = $self->action_namespace(@_);
199 $self->$orig($namespace) if ref($self);
200 return $namespace;
201};
234763d4 202
9ab7d83d 203sub get_action_methods {
204 my $self = shift;
2bf074ab 205 my $meta = find_meta($self) || confess("No metaclass setup for $self");
69048792 206 confess(
207 sprintf "Metaclass %s for %s cannot support register_actions.",
208 ref $meta, $meta->name,
209 ) unless $meta->can('get_nearest_methods_with_attributes');
cf37d21a 210 my @methods = $meta->get_nearest_methods_with_attributes;
fa649eb7 211
212 # actions specified via config are also action_methods
213 push(
214 @methods,
215 map {
d0e78355 216 $meta->find_method_by_name($_)
e87273a4 217 || confess( sprintf 'Action "%s" is not available from controller %s',
218 $_, ref $self )
bdd6684e 219 } keys %{ $self->_controller_actions }
fa649eb7 220 ) if ( ref $self );
4f4ab5b4 221 return uniq @methods;
9ab7d83d 222}
234763d4 223
fa649eb7 224
234763d4 225sub register_actions {
226 my ( $self, $c ) = @_;
9ab7d83d 227 $self->register_action_methods( $c, $self->get_action_methods );
228}
229
230sub register_action_methods {
231 my ( $self, $c, @methods ) = @_;
8f6cebb2 232 my $class = $self->catalyst_component_name;
ae29b412 233 #this is still not correct for some reason.
234763d4 234 my $namespace = $self->action_namespace($c);
234763d4 235
f3c5b1c9 236 # FIXME - fugly
a202886b 237 if (!blessed($self) && $self eq $c && scalar(@methods)) {
f3c5b1c9 238 my @really_bad_methods = grep { ! /^_(DISPATCH|BEGIN|AUTO|ACTION|END)$/ } map { $_->name } @methods;
239 if (scalar(@really_bad_methods)) {
240 $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.");
241 }
a202886b 242 }
d2598ac8 243
ba545c13 244 foreach my $method (@methods) {
245 my $name = $method->name;
d0f30dbc 246 # Horrible hack! All method metaclasses should have an attributes
247 # method, core Moose bug - see r13354.
10e970e4 248 my $attributes = $method->can('attributes') ? $method->attributes : [];
ba545c13 249 my $attrs = $self->_parse_attrs( $c, $name, @{ $attributes } );
234763d4 250 if ( $attrs->{Private} && ( keys %$attrs > 1 ) ) {
251 $c->log->debug( 'Bad action definition "'
ba545c13 252 . join( ' ', @{ $attributes } )
253 . qq/" for "$class->$name"/ )
234763d4 254 if $c->debug;
255 next;
256 }
bc677969 257 my $reverse = $namespace ? "${namespace}/${name}" : $name;
234763d4 258 my $action = $self->create_action(
ba545c13 259 name => $name,
260 code => $method->body,
234763d4 261 reverse => $reverse,
262 namespace => $namespace,
263 class => $class,
264 attributes => $attrs,
265 );
266
267 $c->dispatcher->register( $c, $action );
268 }
269}
270
f0a9b791 271sub action_class {
7b41db70 272 my $self = shift;
273 my %args = @_;
234763d4 274
275 my $class = (exists $args{attributes}{ActionClass}
f0a9b791 276 ? $args{attributes}{ActionClass}[0]
277 : $self->_action_class);
278
ae29b412 279 Class::MOP::load_class($class);
f0a9b791 280 return $class;
281}
282
283sub create_action {
284 my $self = shift;
285 my %args = @_;
a7e955ae 286
f0a9b791 287 my $class = $self->action_class(%args);
a7e955ae 288 my $action_args = $self->config->{action_args};
f0a9b791 289
a7e955ae 290 my %extra_args = (
291 %{ $action_args->{'*'} || {} },
292 %{ $action_args->{ $args{name} } || {} },
293 );
294
295 return $class->new({ %extra_args, %args });
234763d4 296}
297
298sub _parse_attrs {
299 my ( $self, $c, $name, @attrs ) = @_;
300
301 my %raw_attributes;
302
303 foreach my $attr (@attrs) {
304
305 # Parse out :Foo(bar) into Foo => bar etc (and arrayify)
306
307 if ( my ( $key, $value ) = ( $attr =~ /^(.*?)(?:\(\s*(.+?)\s*\))?$/ ) )
308 {
309
310 if ( defined $value ) {
311 ( $value =~ s/^'(.*)'$/$1/ ) || ( $value =~ s/^"(.*)"/$1/ );
312 }
313 push( @{ $raw_attributes{$key} }, $value );
314 }
315 }
316
bdd6684e 317 my ($actions_config, $all_actions_config);
ae29b412 318 if( ref($self) ) {
bdd6684e 319 $actions_config = $self->_controller_actions;
320 # No, you're not getting actions => { '*' => ... } with actions in MyApp.
321 $all_actions_config = $self->_all_actions_attributes;
ae29b412 322 } else {
323 my $cfg = $self->config;
bdd6684e 324 $actions_config = $self->merge_config_hashes($cfg->{actions}, $cfg->{action});
325 $all_actions_config = {};
234763d4 326 }
327
ed9d06b6 328 %raw_attributes = (
329 %raw_attributes,
bdd6684e 330 exists $actions_config->{$name} ? %{ $actions_config->{$name } } : (),
ed9d06b6 331 );
ae29b412 332
ed9d06b6 333 # Private actions with additional attributes will raise a warning and then
334 # be ignored. Adding '*' arguments to the default _DISPATCH / etc. methods,
335 # which are Private, will prevent those from being registered. They should
336 # probably be turned into :Actions instead, or we might want to otherwise
337 # disambiguate between those built-in internal actions and user-level
338 # Private ones.
bdd6684e 339 %raw_attributes = (%{ $all_actions_config }, %raw_attributes)
340 unless $raw_attributes{Private};
ae29b412 341
234763d4 342 my %final_attributes;
343
344 foreach my $key (keys %raw_attributes) {
345
346 my $raw = $raw_attributes{$key};
347
348 foreach my $value (ref($raw) eq 'ARRAY' ? @$raw : $raw) {
349
350 my $meth = "_parse_${key}_attr";
ae29b412 351 if ( my $code = $self->can($meth) ) {
352 ( $key, $value ) = $self->$code( $c, $name, $value );
234763d4 353 }
354 push( @{ $final_attributes{$key} }, $value );
355 }
356 }
357
358 return \%final_attributes;
359}
360
361sub _parse_Global_attr {
362 my ( $self, $c, $name, $value ) = @_;
363 return $self->_parse_Path_attr( $c, $name, "/$name" );
364}
365
366sub _parse_Absolute_attr { shift->_parse_Global_attr(@_); }
367
368sub _parse_Local_attr {
369 my ( $self, $c, $name, $value ) = @_;
370 return $self->_parse_Path_attr( $c, $name, $name );
371}
372
373sub _parse_Relative_attr { shift->_parse_Local_attr(@_); }
374
375sub _parse_Path_attr {
376 my ( $self, $c, $name, $value ) = @_;
53119b78 377 $value = '' if !defined $value;
234763d4 378 if ( $value =~ m!^/! ) {
379 return ( 'Path', $value );
380 }
381 elsif ( length $value ) {
382 return ( 'Path', join( '/', $self->path_prefix($c), $value ) );
383 }
384 else {
385 return ( 'Path', $self->path_prefix($c) );
386 }
387}
388
389sub _parse_Regex_attr {
390 my ( $self, $c, $name, $value ) = @_;
391 return ( 'Regex', $value );
392}
393
394sub _parse_Regexp_attr { shift->_parse_Regex_attr(@_); }
395
396sub _parse_LocalRegex_attr {
397 my ( $self, $c, $name, $value ) = @_;
398 unless ( $value =~ s/^\^// ) { $value = "(?:.*?)$value"; }
19c01ee1 399
400 my $prefix = $self->path_prefix( $c );
401 $prefix .= '/' if length( $prefix );
27ae4114 402
19c01ee1 403 return ( 'Regex', "^${prefix}${value}" );
234763d4 404}
405
406sub _parse_LocalRegexp_attr { shift->_parse_LocalRegex_attr(@_); }
407
f3107403 408sub _parse_Chained_attr {
409 my ($self, $c, $name, $value) = @_;
410
411 if (defined($value) && length($value)) {
412 if ($value eq '.') {
413 $value = '/'.$self->action_namespace($c);
fb56008f 414 } elsif (my ($rel, $rest) = $value =~ /^((?:\.{2}\/)+)(.*)$/) {
eb270c30 415 my @parts = split '/', $self->action_namespace($c);
fb56008f 416 my @levels = split '/', $rel;
417
418 $value = '/'.join('/', @parts[0 .. $#parts - @levels], $rest);
f3107403 419 } elsif ($value !~ m/^\//) {
420 my $action_ns = $self->action_namespace($c);
421
422 if ($action_ns) {
423 $value = '/'.join('/', $action_ns, $value);
424 } else {
425 $value = '/'.$value; # special case namespace '' (root)
426 }
427 }
428 } else {
429 $value = '/'
430 }
431
432 return Chained => $value;
433}
434
9356b981 435sub _parse_ChainedParent_attr {
436 my ($self, $c, $name, $value) = @_;
437 return $self->_parse_Chained_attr($c, $name, '../'.$name);
438}
439
e5d2cfdb 440sub _parse_PathPrefix_attr {
02825551 441 my ( $self, $c ) = @_;
442 return PathPart => $self->path_prefix($c);
e5d2cfdb 443}
444
234763d4 445sub _parse_ActionClass_attr {
446 my ( $self, $c, $name, $value ) = @_;
5d8129e9 447 my $appname = $self->_application;
448 $value = Catalyst::Utils::resolve_namespace($appname . '::Action', $self->_action_class, $value);
234763d4 449 return ( 'ActionClass', $value );
450}
451
9287719b 452sub _parse_MyAction_attr {
453 my ( $self, $c, $name, $value ) = @_;
454
455 my $appclass = Catalyst::Utils::class2appclass($self);
456 $value = "${appclass}::Action::${value}";
234763d4 457
9287719b 458 return ( 'ActionClass', $value );
459}
234763d4 460
ae29b412 461__PACKAGE__->meta->make_immutable;
462
234763d4 4631;
464
465__END__
466
467=head1 CONFIGURATION
468
a269e0c2 469Like any other L<Catalyst::Component>, controllers have a config hash,
470accessible through $self->config from the controller actions. Some
471settings are in use by the Catalyst framework:
234763d4 472
473=head2 namespace
474
a269e0c2 475This specifies the internal namespace the controller should be bound
476to. By default the controller is bound to the URI version of the
477controller name. For instance controller 'MyApp::Controller::Foo::Bar'
478will be bound to 'foo/bar'. The default Root controller is an example
479of setting namespace to '' (the null string).
234763d4 480
27ae4114 481=head2 path
234763d4 482
483Sets 'path_prefix', as described below.
484
0a2577a8 485=head2 action
486
487Allows you to set the attributes that the dispatcher creates actions out of.
488This allows you to do 'rails style routes', or override some of the
489attribute defintions of actions composed from Roles.
490You can set arguments globally (for all actions of the controller) and
491specifically (for a single action).
492
493 __PACKAGE__->config(
494 action => {
495 '*' => { Chained => 'base', Args => 0 },
496 base => { Chained => '/', PathPart => '', CaptureArgs => 0 },
497 },
498 );
499
500In the case above every sub in the package would be made into a Chain
501endpoint with a URI the same as the sub name for each sub, chained
502to the sub named C<base>. Ergo dispatch to C</example> would call the
503C<base> method, then the C<example> method.
504
c8136648 505=head2 action_args
506
4d4e5de8 507Allows you to set constructor arguments on your actions. You can set arguments
0a2577a8 508globally and specifically (as above).
509This is particularly useful when using C<ActionRole>s
b939ae6b 510(L<Catalyst::Controller::ActionRole>) and custom C<ActionClass>es.
c8136648 511
b939ae6b 512 __PACKAGE__->config(
c8136648 513 action_args => {
b939ae6b 514 '*' => { globalarg1 => 'hello', globalarg2 => 'goodbye' },
515 'specific_action' => { customarg => 'arg1' },
cea3f28a 516 },
b939ae6b 517 );
cea3f28a 518
b939ae6b 519In the case above the action class associated with C<specific_action> would get
520passed the following arguments, in addition to the normal action constructor
521arguments, when it is instantiated:
522
523 (globalarg1 => 'hello', globalarg2 => 'goodbye', customarg => 'arg1')
c8136648 524
234763d4 525=head1 METHODS
526
c4d02967 527=head2 BUILDARGS ($app, @args)
234763d4 528
c4d02967 529From L<Catalyst::Component::ApplicationAttribute>, stashes the application
530instance as $self->_application.
234763d4 531
532=head2 $self->action_for('name')
533
a269e0c2 534Returns the Catalyst::Action object (if any) for a given method name
535in this component.
234763d4 536
234763d4 537=head2 $self->action_namespace($c)
538
a269e0c2 539Returns the private namespace for actions in this component. Defaults
540to a value from the controller name (for
541e.g. MyApp::Controller::Foo::Bar becomes "foo/bar") or can be
542overridden from the "namespace" config key.
234763d4 543
544
545=head2 $self->path_prefix($c)
546
e5d2cfdb 547Returns the default path prefix for :PathPrefix, :Local, :LocalRegex and
548relative :Path actions in this component. Defaults to the action_namespace or
a269e0c2 549can be overridden from the "path" config key.
234763d4 550
c4d02967 551=head2 $self->register_actions($c)
552
553Finds all applicable actions for this component, creates
554Catalyst::Action objects (using $self->create_action) for them and
555registers them with $c->dispatcher.
556
557=head2 $self->get_action_methods()
558
559Returns a list of L<Moose::Meta::Method> objects, doing the
560L<MooseX::MethodAttributes::Role::Meta::Method> role, which are the set of
561action methods for this package.
562
563=head2 $self->register_action_methods($c, @methods)
564
565Creates action objects for a set of action methods using C< create_action >,
566and registers them with the dispatcher.
567
f0a9b791 568=head2 $self->action_class(%args)
569
570Used when a controller is creating an action to determine the correct base
24d2dfaf 571action class to use.
f0a9b791 572
234763d4 573=head2 $self->create_action(%args)
574
a269e0c2 575Called with a hash of data to be use for construction of a new
576Catalyst::Action (or appropriate sub/alternative class) object.
234763d4 577
a269e0c2 578=head2 $self->_application
234763d4 579
580=head2 $self->_app
581
582Returns the application instance stored by C<new()>
5ee249f2 583
0bf7ab71 584=head1 AUTHORS
5ee249f2 585
0bf7ab71 586Catalyst Contributors, see Catalyst.pm
5ee249f2 587
588=head1 COPYRIGHT
589
536bee89 590This library is free software. You can redistribute it and/or modify
a269e0c2 591it under the same terms as Perl itself.
5ee249f2 592
593=cut