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