calling config on app object instead of class (t/aggregate/live_component_view_single...
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Context.pm
CommitLineData
c20db8ca 1package Catalyst::Context;
2
3use Moose;
4use bytes;
5use B::Hooks::EndOfScope ();
48603b30 6use Catalyst;
c20db8ca 7use Catalyst::Exception::Detach;
8use Catalyst::Exception::Go;
9use Catalyst::Request;
10use Catalyst::Request::Upload;
11use Catalyst::Response;
12use Catalyst::Utils;
13use File::stat;
14use Text::SimpleTable ();
15use URI ();
16use URI::http;
17use URI::https;
18use utf8;
19use Carp qw/croak carp shortmess/;
20
21has stack => (is => 'ro', default => sub { [] });
22has stash => (is => 'rw', default => sub { {} });
23has state => (is => 'rw', default => 0);
24has stats => (is => 'rw');
25has action => (is => 'rw');
26has counter => (is => 'rw', default => sub { {} });
27has request => (is => 'rw', default => sub { $_[0]->request_class->new({}) }, required => 1, lazy => 1);
28has response => (is => 'rw', default => sub { $_[0]->response_class->new({}) }, required => 1, lazy => 1);
29has namespace => (is => 'rw');
30
31
32has 'application' => (
33 isa => 'Catalyst',
34 is => 'ro',
35 handles => [
36 qw/
37 controllers
38 models
39 views
40 component
41 config
42 log
43 debug
44 dispatcher_class
45 request_class
48603b30 46 response_class
c20db8ca 47 dispatcher
48 prepare
49 engine_class
50 engine
51 path_to
52 plugin
53 setup_finalize
54 welcome_message
55 components
48603b30 56 context_class
57 setup_actions
c20db8ca 58 search_extra
59 root
60 parse_on_demand
61 name
62 ignore_frontend_proxy
63 home
64 default_model
65 default_view
66 version
67 use_stats
68 stats_class
69 set_action
a07fc0d9 70 registered_plugins
c20db8ca 71
72 ran_setup
73 _comp_search_prefixes
74 _filter_component
75 /
76 ],
77);
78
79sub depth { scalar @{ shift->stack || [] }; }
80
81sub req {
82 my $self = shift; return $self->request(@_);
83}
84sub res {
85 my $self = shift; return $self->response(@_);
86}
87
88# For backwards compatibility
89sub finalize_output { shift->finalize_body(@_) };
90
91# For statistics
92our $RECURSION = 1000;
c20db8ca 93
94=head1 METHODS
95
96=head2 INFORMATION ABOUT THE CURRENT REQUEST
97
98=head2 $c->action
99
100Returns a L<Catalyst::Action> object for the current action, which
101stringifies to the action name. See L<Catalyst::Action>.
102
103=head2 $c->namespace
104
105Returns the namespace of the current action, i.e., the URI prefix
106corresponding to the controller of the current action. For example:
107
108 # in Controller::Foo::Bar
109 $c->namespace; # returns 'foo/bar';
110
111=head2 $c->request
112
113=head2 $c->req
114
115Returns the current L<Catalyst::Request> object, giving access to
116information about the current client request (including parameters,
117cookies, HTTP headers, etc.). See L<Catalyst::Request>.
118
119=head2 REQUEST FLOW HANDLING
120
121=head2 $c->forward( $action [, \@arguments ] )
122
123=head2 $c->forward( $class, $method, [, \@arguments ] )
124
125Forwards processing to another action, by its private name. If you give a
126class name but no method, C<process()> is called. You may also optionally
127pass arguments in an arrayref. The action will receive the arguments in
128C<@_> and C<< $c->req->args >>. Upon returning from the function,
129C<< $c->req->args >> will be restored to the previous values.
130
131Any data C<return>ed from the action forwarded to, will be returned by the
132call to forward.
133
134 my $foodata = $c->forward('/foo');
135 $c->forward('index');
136 $c->forward(qw/MyApp::Model::DBIC::Foo do_stuff/);
137 $c->forward('MyApp::View::TT');
138
139Note that L<< forward|/"$c->forward( $action [, \@arguments ] )" >> implies
140an C<< eval { } >> around the call (actually
141L<< execute|/"$c->execute( $class, $coderef )" >> does), thus de-fatalizing
142all 'dies' within the called action. If you want C<die> to propagate you
143need to do something like:
144
145 $c->forward('foo');
146 die $c->error if $c->error;
147
148Or make sure to always return true values from your actions and write
149your code like this:
150
151 $c->forward('foo') || return;
152
153Another note is that C<< $c->forward >> always returns a scalar because it
154actually returns $c->state which operates in a scalar context.
155Thus, something like:
156
157 return @array;
158
159in an action that is forwarded to is going to return a scalar,
160i.e. how many items are in that array, which is probably not what you want.
161If you need to return an array then return a reference to it,
162or stash it like so:
163
164 $c->stash->{array} = \@array;
165
166and access it from the stash.
167
168=cut
169
170sub forward { my $c = shift; no warnings 'recursion'; $c->dispatcher->forward( $c, @_ ) }
171
172=head2 $c->detach( $action [, \@arguments ] )
173
174=head2 $c->detach( $class, $method, [, \@arguments ] )
175
176=head2 $c->detach()
177
178The same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, but
179doesn't return to the previous action when processing is finished.
180
181When called with no arguments it escapes the processing chain entirely.
182
183=cut
184
185sub detach { my $c = shift; $c->dispatcher->detach( $c, @_ ) }
186
187=head2 $c->visit( $action [, \@captures, \@arguments ] )
188
189=head2 $c->visit( $class, $method, [, \@captures, \@arguments ] )
190
191Almost the same as L<< forward|/"$c->forward( $action [, \@arguments ] )" >>,
192but does a full dispatch, instead of just calling the new C<$action> /
193C<< $class->$method >>. This means that C<begin>, C<auto> and the method
194you go to are called, just like a new request.
195
196In addition both C<< $c->action >> and C<< $c->namespace >> are localized.
197This means, for example, that C<< $c->action >> methods such as
198L<name|Catalyst::Action/name>, L<class|Catalyst::Action/class> and
199L<reverse|Catalyst::Action/reverse> return information for the visited action
200when they are invoked within the visited action. This is different from the
201behavior of L<< forward|/"$c->forward( $action [, \@arguments ] )" >>, which
202continues to use the $c->action object from the caller action even when
203invoked from the callee.
204
205C<< $c->stash >> is kept unchanged.
206
207In effect, L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >>
208allows you to "wrap" another action, just as it would have been called by
209dispatching from a URL, while the analogous
210L<< go|/"$c->go( $action [, \@captures, \@arguments ] )" >> allows you to
211transfer control to another action as if it had been reached directly from a URL.
212
213=cut
214
215sub visit { my $c = shift; $c->dispatcher->visit( $c, @_ ) }
216
217=head2 $c->go( $action [, \@captures, \@arguments ] )
218
219=head2 $c->go( $class, $method, [, \@captures, \@arguments ] )
220
221The relationship between C<go> and
222L<< visit|/"$c->visit( $action [, \@captures, \@arguments ] )" >> is the same as
223the relationship between
224L<< forward|/"$c->forward( $class, $method, [, \@arguments ] )" >> and
225L<< detach|/"$c->detach( $action [, \@arguments ] )" >>. Like C<< $c->visit >>,
226C<< $c->go >> will perform a full dispatch on the specified action or method,
227with localized C<< $c->action >> and C<< $c->namespace >>. Like C<detach>,
228C<go> escapes the processing of the current request chain on completion, and
229does not return to its caller.
230
231=cut
232
233sub go { my $c = shift; $c->dispatcher->go( $c, @_ ) }
234
235=head2 $c->response
236
237=head2 $c->res
238
239Returns the current L<Catalyst::Response> object, see there for details.
240
241=head2 $c->stash
242
243Returns a hashref to the stash, which may be used to store data and pass
244it between components during a request. You can also set hash keys by
245passing arguments. The stash is automatically sent to the view. The
246stash is cleared at the end of a request; it cannot be used for
247persistent storage (for this you must use a session; see
248L<Catalyst::Plugin::Session> for a complete system integrated with
249Catalyst).
250
251 $c->stash->{foo} = $bar;
252 $c->stash( { moose => 'majestic', qux => 0 } );
253 $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref
254
255 # stash is automatically passed to the view for use in a template
256 $c->forward( 'MyApp::View::TT' );
257
258=cut
259
260around stash => sub {
261 my $orig = shift;
262 my $c = shift;
263 my $stash = $orig->($c);
264 if (@_) {
265 my $new_stash = @_ > 1 ? {@_} : $_[0];
266 croak('stash takes a hash or hashref') unless ref $new_stash;
267 foreach my $key ( keys %$new_stash ) {
268 $stash->{$key} = $new_stash->{$key};
269 }
270 }
271
272 return $stash;
273};
274
275
276=head2 $c->error
277
278=head2 $c->error($error, ...)
279
280=head2 $c->error($arrayref)
281
282Returns an arrayref containing error messages. If Catalyst encounters an
283error while processing a request, it stores the error in $c->error. This
284method should only be used to store fatal error messages.
285
286 my @error = @{ $c->error };
287
288Add a new error.
289
290 $c->error('Something bad happened');
291
292=cut
293
294sub error {
295 my $c = shift;
296 if ( $_[0] ) {
297 my $error = ref $_[0] eq 'ARRAY' ? $_[0] : [@_];
298 croak @$error unless ref $c;
299 push @{ $c->{error} }, @$error;
300 }
301 elsif ( defined $_[0] ) { $c->{error} = undef }
302 return $c->{error} || [];
303}
304
305
306=head2 $c->state
307
308Contains the return value of the last executed action.
309Note that << $c->state >> operates in a scalar context which means that all
310values it returns are scalar.
311
312=head2 $c->clear_errors
313
314Clear errors. You probably don't want to clear the errors unless you are
315implementing a custom error screen.
316
317This is equivalent to running
318
319 $c->error(0);
320
321=cut
322
323sub clear_errors {
324 my $c = shift;
325 $c->error(0);
326}
327
328
329=head2 COMPONENT ACCESSORS
330
331=head2 $c->controller($name)
332
333Gets a L<Catalyst::Controller> instance by name.
334
335 $c->controller('Foo')->do_stuff;
336
337If the name is omitted, will return the controller for the dispatched
338action.
339
340If you want to search for controllers, pass in a regexp as the argument.
341
342 # find all controllers that start with Foo
343 my @foo_controllers = $c->controller(qr{^Foo});
344
345
346=cut
347
348sub controller {
349 my ( $c, $name, @args ) = @_;
350
351 if( $name ) {
352 my @result = $c->_comp_search_prefixes( $name, qw/Controller C/ );
353 return map { $c->_filter_component( $_, @args ) } @result if ref $name;
354 return $c->_filter_component( $result[ 0 ], @args );
355 }
356
357 return $c->component( $c->action->class );
358}
359
360=head2 $c->model($name)
361
362Gets a L<Catalyst::Model> instance by name.
363
364 $c->model('Foo')->do_stuff;
365
366Any extra arguments are directly passed to ACCEPT_CONTEXT.
367
368If the name is omitted, it will look for
369 - a model object in $c->stash->{current_model_instance}, then
370 - a model name in $c->stash->{current_model}, then
371 - a config setting 'default_model', or
372 - check if there is only one model, and return it if that's the case.
373
374If you want to search for models, pass in a regexp as the argument.
375
376 # find all models that start with Foo
377 my @foo_models = $c->model(qr{^Foo});
378
379=cut
380
381sub model {
382 my ( $c, $name, @args ) = @_;
383 my $appclass = ref($c) || $c;
384 if( $name ) {
385 my @result = $c->_comp_search_prefixes( $name, qw/Model M/ );
386 return map { $c->_filter_component( $_, @args ) } @result if ref $name;
387 return $c->_filter_component( $result[ 0 ], @args );
388 }
389
390 if (ref $c) {
391 return $c->stash->{current_model_instance}
392 if $c->stash->{current_model_instance};
393 return $c->model( $c->stash->{current_model} )
394 if $c->stash->{current_model};
395 }
396 return $c->model( $appclass->config->{default_model} )
397 if $appclass->config->{default_model};
398
399 my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/Model M/);
400
401 if( $rest ) {
402 $c->log->warn( Carp::shortmess('Calling $c->model() will return a random model unless you specify one of:') );
403 $c->log->warn( '* $c->config(default_model => "the name of the default model to use")' );
404 $c->log->warn( '* $c->stash->{current_model} # the name of the model to use for this request' );
405 $c->log->warn( '* $c->stash->{current_model_instance} # the instance of the model to use for this request' );
406 $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
407 }
408
409 return $c->_filter_component( $comp );
410}
411
412
413=head2 $c->view($name)
414
415Gets a L<Catalyst::View> instance by name.
416
417 $c->view('Foo')->do_stuff;
418
419Any extra arguments are directly passed to ACCEPT_CONTEXT.
420
421If the name is omitted, it will look for
422 - a view object in $c->stash->{current_view_instance}, then
423 - a view name in $c->stash->{current_view}, then
424 - a config setting 'default_view', or
425 - check if there is only one view, and return it if that's the case.
426
427If you want to search for views, pass in a regexp as the argument.
428
429 # find all views that start with Foo
430 my @foo_views = $c->view(qr{^Foo});
431
432=cut
433
434sub view {
435 my ( $c, $name, @args ) = @_;
436
c20db8ca 437 if( $name ) {
438 my @result = $c->_comp_search_prefixes( $name, qw/View V/ );
439 return map { $c->_filter_component( $_, @args ) } @result if ref $name;
440 return $c->_filter_component( $result[ 0 ], @args );
441 }
442
443 if (ref $c) {
444 return $c->stash->{current_view_instance}
445 if $c->stash->{current_view_instance};
446 return $c->view( $c->stash->{current_view} )
447 if $c->stash->{current_view};
448 }
a07fc0d9 449 return $c->view( $c->config->{default_view} )
450 if $c->config->{default_view};
c20db8ca 451 my( $comp, $rest ) = $c->_comp_search_prefixes( undef, qw/View V/);
452
453 if( $rest ) {
454 $c->log->warn( 'Calling $c->view() will return a random view unless you specify one of:' );
455 $c->log->warn( '* $c->config(default_view => "the name of the default view to use")' );
456 $c->log->warn( '* $c->stash->{current_view} # the name of the view to use for this request' );
457 $c->log->warn( '* $c->stash->{current_view_instance} # the instance of the view to use for this request' );
458 $c->log->warn( 'NB: in version 5.81, the "random" behavior will not work at all.' );
459 }
460
461 return $c->_filter_component( $comp );
462}
463
464=head2 UTILITY METHODS
465
466=head2 $c->uri_for( $path?, @args?, \%query_values? )
467
468=head2 $c->uri_for( $action, \@captures?, @args?, \%query_values? )
469
470Constructs an absolute L<URI> object based on the application root, the
471provided path, and the additional arguments and query parameters provided.
472When used as a string, provides a textual URI.
473
474If no arguments are provided, the URI for the current action is returned.
475To return the current action and also provide @args, use
476C<< $c->uri_for( $c->action, @args ) >>.
477
478If the first argument is a string, it is taken as a public URI path relative
479to C<< $c->namespace >> (if it doesn't begin with a forward slash) or
480relative to the application root (if it does). It is then merged with
481C<< $c->request->base >>; any C<@args> are appended as additional path
482components; and any C<%query_values> are appended as C<?foo=bar> parameters.
483
484If the first argument is a L<Catalyst::Action> it represents an action which
485will have its path resolved using C<< $c->dispatcher->uri_for_action >>. The
486optional C<\@captures> argument (an arrayref) allows passing the captured
487variables that are needed to fill in the paths of Chained and Regex actions;
488once the path is resolved, C<uri_for> continues as though a path was
489provided, appending any arguments or parameters and creating an absolute
490URI.
491
492The captures for the current request can be found in
493C<< $c->request->captures >>, and actions can be resolved using
494C<< Catalyst::Controller->action_for($name) >>. If you have a private action
495path, use C<< $c->uri_for_action >> instead.
496
497 # Equivalent to $c->req->uri
498 $c->uri_for($c->action, $c->req->captures,
499 @{ $c->req->args }, $c->req->params);
500
501 # For the Foo action in the Bar controller
502 $c->uri_for($c->controller('Bar')->action_for('Foo'));
503
504 # Path to a static resource
505 $c->uri_for('/static/images/logo.png');
506
507=cut
508
509sub uri_for {
510 my ( $c, $path, @args ) = @_;
511
512 if (blessed($path) && $path->isa('Catalyst::Controller')) {
513 $path = $path->path_prefix;
514 $path =~ s{/+\z}{};
515 $path .= '/';
516 }
517
518 if ( blessed($path) ) { # action object
519 my $captures = [ map { s|/|%2F|; $_; }
520 ( scalar @args && ref $args[0] eq 'ARRAY'
521 ? @{ shift(@args) }
522 : ()) ];
523 my $action = $path;
524 $path = $c->dispatcher->uri_for_action($action, $captures);
525 if (not defined $path) {
526 $c->log->debug(qq/Can't find uri_for action '$action' @$captures/)
527 if $c->debug;
528 return undef;
529 }
530 $path = '/' if $path eq '';
531 }
532
533 undef($path) if (defined $path && $path eq '');
534
535 my $params =
536 ( scalar @args && ref $args[$#args] eq 'HASH' ? pop @args : {} );
537
538 carp "uri_for called with undef argument" if grep { ! defined $_ } @args;
539 s/([^$URI::uric])/$URI::Escape::escapes{$1}/go for @args;
540 s|/|%2F| for @args;
541
542 unshift(@args, $path);
543
544 unless (defined $path && $path =~ s!^/!!) { # in-place strip
545 my $namespace = $c->namespace;
546 if (defined $path) { # cheesy hack to handle path '../foo'
547 $namespace =~ s{(?:^|/)[^/]+$}{} while $args[0] =~ s{^\.\./}{};
548 }
549 unshift(@args, $namespace || '');
550 }
551
552 # join args with '/', or a blank string
553 my $args = join('/', grep { defined($_) } @args);
554 $args =~ s/\?/%3F/g; # STUPID STUPID SPECIAL CASE
555 $args =~ s!^/+!!;
556 my $base = $c->req->base;
557 my $class = ref($base);
558 $base =~ s{(?<!/)$}{/};
559
560 my $query = '';
561
562 if (my @keys = keys %$params) {
563 # somewhat lifted from URI::_query's query_form
564 $query = '?'.join('&', map {
565 my $val = $params->{$_};
566 s/([;\/?:@&=+,\$\[\]%])/$URI::Escape::escapes{$1}/go;
567 s/ /+/g;
568 my $key = $_;
569 $val = '' unless defined $val;
570 (map {
571 my $param = "$_";
572 utf8::encode( $param ) if utf8::is_utf8($param);
573 # using the URI::Escape pattern here so utf8 chars survive
574 $param =~ s/([^A-Za-z0-9\-_.!~*'() ])/$URI::Escape::escapes{$1}/go;
575 $param =~ s/ /+/g;
576 "${key}=$param"; } ( ref $val eq 'ARRAY' ? @$val : $val ));
577 } @keys);
578 }
579
580 my $res = bless(\"${base}${args}${query}", $class);
581 $res;
582}
583
584=head2 $c->uri_for_action( $path, \@captures?, @args?, \%query_values? )
585
586=head2 $c->uri_for_action( $action, \@captures?, @args?, \%query_values? )
587
588=over
589
590=item $path
591
592A private path to the Catalyst action you want to create a URI for.
593
594This is a shortcut for calling C<< $c->dispatcher->get_action_by_path($path)
595>> and passing the resulting C<$action> and the remaining arguments to C<<
596$c->uri_for >>.
597
598You can also pass in a Catalyst::Action object, in which case it is passed to
599C<< $c->uri_for >>.
600
601=back
602
603=cut
604
605sub uri_for_action {
606 my ( $c, $path, @args ) = @_;
607 my $action = blessed($path)
608 ? $path
609 : $c->dispatcher->get_action_by_path($path);
610 unless (defined $action) {
611 croak "Can't find action for path '$path'";
612 }
613 return $c->uri_for( $action, @args );
614}
615
616=head1 INTERNAL METHODS
617
618=head2 $c->counter
619
620Returns a hashref containing coderefs and execution counts (needed for
621deep recursion detection).
622
623=head2 $c->depth
624
625Returns the number of actions on the current internal execution stack.
626
627=head2 $c->dispatch
628
629Dispatches a request to actions.
630
631=cut
632
633sub dispatch { my $c = shift; $c->dispatcher->dispatch( $c, @_ ) }
634
635=head2 $c->dump_these
636
637Returns a list of 2-element array references (name, structure) pairs
638that will be dumped on the error page in debug mode.
639
640=cut
641
642sub dump_these {
643 my $c = shift;
644 [ Request => $c->req ],
645 [ Response => $c->res ],
646 [ Stash => $c->stash ],
647 [ Config => $c->config ];
648}
649
650=head2 $c->execute( $class, $coderef )
651
652Execute a coderef in given class and catch exceptions. Errors are available
653via $c->error.
654
655=cut
656
657sub execute {
658 my ( $c, $class, $code ) = @_;
659 $class = $c->component($class) || $class;
660 $c->state(0);
661
662 if ( $c->depth >= $RECURSION ) {
663 my $action = $code->reverse();
664 $action = "/$action" unless $action =~ /->/;
665 my $error = qq/Deep recursion detected calling "${action}"/;
666 $c->log->error($error);
667 $c->error($error);
668 $c->state(0);
669 return $c->state;
670 }
671
672 my $stats_info = $c->_stats_start_execute( $code ) if $c->use_stats;
673
674 push( @{ $c->stack }, $code );
675
676 no warnings 'recursion';
677 eval { $c->state( $code->execute( $class, $c, @{ $c->req->args } ) || 0 ) };
678
679 $c->_stats_finish_execute( $stats_info ) if $c->use_stats and $stats_info;
680
681 my $last = pop( @{ $c->stack } );
682
683 if ( my $error = $@ ) {
684 if ( blessed($error) and $error->isa('Catalyst::Exception::Detach') ) {
685 $error->rethrow if $c->depth > 1;
686 }
687 elsif ( blessed($error) and $error->isa('Catalyst::Exception::Go') ) {
688 $error->rethrow if $c->depth > 0;
689 }
690 else {
691 unless ( ref $error ) {
692 no warnings 'uninitialized';
693 chomp $error;
694 my $class = $last->class;
695 my $name = $last->name;
696 $error = qq/Caught exception in $class->$name "$error"/;
697 }
698 $c->error($error);
699 $c->state(0);
700 }
701 }
702 return $c->state;
703}
704
705sub _stats_start_execute {
706 my ( $c, $code ) = @_;
c20db8ca 707 return if ( ( $code->name =~ /^_.*/ )
1a4f82a0 708 && ( !$c->config->{show_internal_actions} ) );
c20db8ca 709
710 my $action_name = $code->reverse();
711 $c->counter->{$action_name}++;
712
713 my $action = $action_name;
714 $action = "/$action" unless $action =~ /->/;
715
716 # determine if the call was the result of a forward
717 # this is done by walking up the call stack and looking for a calling
718 # sub of Catalyst::forward before the eval
719 my $callsub = q{};
720 for my $index ( 2 .. 11 ) {
721 last
722 if ( ( caller($index) )[0] eq 'Catalyst'
723 && ( caller($index) )[3] eq '(eval)' );
724
725 if ( ( caller($index) )[3] =~ /forward$/ ) {
726 $callsub = ( caller($index) )[3];
727 $action = "-> $action";
728 last;
729 }
730 }
731
732 my $uid = $action_name . $c->counter->{$action_name};
733
734 # is this a root-level call or a forwarded call?
735 if ( $callsub =~ /forward$/ ) {
736 my $parent = $c->stack->[-1];
737
738 # forward, locate the caller
739 if ( exists $c->counter->{"$parent"} ) {
740 $c->stats->profile(
741 begin => $action,
742 parent => "$parent" . $c->counter->{"$parent"},
743 uid => $uid,
744 );
745 }
746 else {
747
748 # forward with no caller may come from a plugin
749 $c->stats->profile(
750 begin => $action,
751 uid => $uid,
752 );
753 }
754 }
755 else {
756
757 # root-level call
758 $c->stats->profile(
759 begin => $action,
760 uid => $uid,
761 );
762 }
763 return $action;
764
765}
766
767sub _stats_finish_execute {
768 my ( $c, $info ) = @_;
769 $c->stats->profile( end => $info );
770}
771
772=head2 $c->finalize
773
774Finalizes the request.
775
776=cut
777
778sub finalize {
779 my $c = shift;
780
781 for my $error ( @{ $c->error } ) {
782 $c->log->error($error);
783 }
784
785 # Allow engine to handle finalize flow (for POE)
786 my $engine = $c->engine;
787 if ( my $code = $engine->can('finalize') ) {
788 $engine->$code($c);
789 }
790 else {
791
792 $c->finalize_uploads;
793
794 # Error
795 if ( $#{ $c->error } >= 0 ) {
796 $c->finalize_error;
797 }
798
799 $c->finalize_headers;
800
801 # HEAD request
802 if ( $c->request->method eq 'HEAD' ) {
803 $c->response->body('');
804 }
805
806 $c->finalize_body;
807 }
808
809 if ($c->use_stats) {
810 my $elapsed = sprintf '%f', $c->stats->elapsed;
811 my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
812 $c->log->info(
813 "Request took ${elapsed}s ($av/s)\n" . $c->stats->report . "\n" );
814 }
815
816 return $c->response->status;
817}
818
819=head2 $c->finalize_body
820
821Finalizes body.
822
823=cut
824
825sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
826
827=head2 $c->finalize_cookies
828
829Finalizes cookies.
830
831=cut
832
833sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
834
835=head2 $c->finalize_error
836
837Finalizes error.
838
839=cut
840
841sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
842
843=head2 $c->finalize_headers
844
845Finalizes headers.
846
847=cut
848
849sub finalize_headers {
850 my $c = shift;
851
852 my $response = $c->response; #accessor calls can add up?
853
854 # Check if we already finalized headers
855 return if $response->finalized_headers;
856
857 # Handle redirects
858 if ( my $location = $response->redirect ) {
859 $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
860 $response->header( Location => $location );
861
862 if ( !$response->has_body ) {
863 # Add a default body if none is already present
864 $response->body(
865 qq{<html><body><p>This item has moved <a href="$location">here</a>.</p></body></html>}
866 );
867 }
868 }
869
870 # Content-Length
871 if ( $response->body && !$response->content_length ) {
872
873 # get the length from a filehandle
874 if ( blessed( $response->body ) && $response->body->can('read') )
875 {
876 my $stat = stat $response->body;
877 if ( $stat && $stat->size > 0 ) {
878 $response->content_length( $stat->size );
879 }
880 else {
881 $c->log->warn('Serving filehandle without a content-length');
882 }
883 }
884 else {
885 # everything should be bytes at this point, but just in case
886 $response->content_length( bytes::length( $response->body ) );
887 }
888 }
889
890 # Errors
891 if ( $response->status =~ /^(1\d\d|[23]04)$/ ) {
892 $response->headers->remove_header("Content-Length");
893 $response->body('');
894 }
895
896 $c->finalize_cookies;
897
898 $c->engine->finalize_headers( $c, @_ );
899
900 # Done
901 $response->finalized_headers(1);
902}
903
904=head2 $c->finalize_output
905
906An alias for finalize_body.
907
908=head2 $c->finalize_read
909
910Finalizes the input after reading is complete.
911
912=cut
913
914sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
915
916=head2 $c->finalize_uploads
917
918Finalizes uploads. Cleans up any temporary files.
919
920=cut
921
922sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
923
924=head2 $c->get_action( $action, $namespace )
925
926Gets an action in a given namespace.
927
928=cut
929
930sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
931
932=head2 $c->get_actions( $action, $namespace )
933
934Gets all actions of a given name in a namespace and all parent
935namespaces.
936
937=cut
938
939sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
940
941=head2 $c->prepare_action
942
943Prepares action. See L<Catalyst::Dispatcher>.
944
945=cut
946
947sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
948
949=head2 $c->prepare_body
950
951Prepares message body.
952
953=cut
954
955sub prepare_body {
956 my $c = shift;
957
958 return if $c->request->_has_body;
959
960 # Initialize on-demand data
961 $c->engine->prepare_body( $c, @_ );
962 $c->prepare_parameters;
963 $c->prepare_uploads;
964
965 if ( $c->debug && keys %{ $c->req->body_parameters } ) {
966 my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
967 for my $key ( sort keys %{ $c->req->body_parameters } ) {
968 my $param = $c->req->body_parameters->{$key};
969 my $value = defined($param) ? $param : '';
970 $t->row( $key,
971 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
972 }
973 $c->log->debug( "Body Parameters are:\n" . $t->draw );
974 }
975}
976
977=head2 $c->prepare_body_chunk( $chunk )
978
979Prepares a chunk of data before sending it to L<HTTP::Body>.
980
981See L<Catalyst::Engine>.
982
983=cut
984
985sub prepare_body_chunk {
986 my $c = shift;
987 $c->engine->prepare_body_chunk( $c, @_ );
988}
989
990=head2 $c->prepare_body_parameters
991
992Prepares body parameters.
993
994=cut
995
996sub prepare_body_parameters {
997 my $c = shift;
998 $c->engine->prepare_body_parameters( $c, @_ );
999}
1000
1001=head2 $c->prepare_connection
1002
1003Prepares connection.
1004
1005=cut
1006
1007sub prepare_connection {
1008 my $c = shift;
1009 $c->engine->prepare_connection( $c, @_ );
1010}
1011
1012=head2 $c->prepare_cookies
1013
1014Prepares cookies.
1015
1016=cut
1017
1018sub prepare_cookies { my $c = shift; $c->engine->prepare_cookies( $c, @_ ) }
1019
1020=head2 $c->prepare_headers
1021
1022Prepares headers.
1023
1024=cut
1025
1026sub prepare_headers { my $c = shift; $c->engine->prepare_headers( $c, @_ ) }
1027
1028=head2 $c->prepare_parameters
1029
1030Prepares parameters.
1031
1032=cut
1033
1034sub prepare_parameters {
1035 my $c = shift;
1036 $c->prepare_body_parameters;
1037 $c->engine->prepare_parameters( $c, @_ );
1038}
1039
1040=head2 $c->prepare_path
1041
1042Prepares path and base.
1043
1044=cut
1045
1046sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
1047
1048=head2 $c->prepare_query_parameters
1049
1050Prepares query parameters.
1051
1052=cut
1053
1054sub prepare_query_parameters {
1055 my $c = shift;
1056
1057 $c->engine->prepare_query_parameters( $c, @_ );
1058
1059 if ( $c->debug && keys %{ $c->request->query_parameters } ) {
1060 my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1061 for my $key ( sort keys %{ $c->req->query_parameters } ) {
1062 my $param = $c->req->query_parameters->{$key};
1063 my $value = defined($param) ? $param : '';
1064 $t->row( $key,
1065 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1066 }
1067 $c->log->debug( "Query Parameters are:\n" . $t->draw );
1068 }
1069}
1070
1071=head2 $c->prepare_read
1072
1073Prepares the input for reading.
1074
1075=cut
1076
1077sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
1078
1079=head2 $c->prepare_request
1080
1081Prepares the engine request.
1082
1083=cut
1084
1085sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
1086
1087=head2 $c->prepare_uploads
1088
1089Prepares uploads.
1090
1091=cut
1092
1093sub prepare_uploads {
1094 my $c = shift;
1095
1096 $c->engine->prepare_uploads( $c, @_ );
1097
1098 if ( $c->debug && keys %{ $c->request->uploads } ) {
1099 my $t = Text::SimpleTable->new(
1100 [ 12, 'Parameter' ],
1101 [ 26, 'Filename' ],
1102 [ 18, 'Type' ],
1103 [ 9, 'Size' ]
1104 );
1105 for my $key ( sort keys %{ $c->request->uploads } ) {
1106 my $upload = $c->request->uploads->{$key};
1107 for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
1108 $t->row( $key, $u->filename, $u->type, $u->size );
1109 }
1110 }
1111 $c->log->debug( "File Uploads are:\n" . $t->draw );
1112 }
1113}
1114
1115=head2 $c->prepare_write
1116
1117Prepares the output for writing.
1118
1119=cut
1120
1121sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
1122
1123=head2 $c->read( [$maxlength] )
1124
1125Reads a chunk of data from the request body. This method is designed to
1126be used in a while loop, reading C<$maxlength> bytes on every call.
1127C<$maxlength> defaults to the size of the request if not specified.
1128
1129You have to set C<< MyApp->config(parse_on_demand => 1) >> to use this
1130directly.
1131
1132Warning: If you use read(), Catalyst will not process the body,
1133so you will not be able to access POST parameters or file uploads via
1134$c->request. You must handle all body parsing yourself.
1135
1136=cut
1137
1138sub read { my $c = shift; return $c->engine->read( $c, @_ ) }
1139
1140=head2 $c->stack
1141
1142Returns an arrayref of the internal execution stack (actions that are
1143currently executing).
1144
1145
1146=head2 $c->write( $data )
1147
1148Writes $data to the output stream. When using this method directly, you
1149will need to manually set the C<Content-Length> header to the length of
1150your output data, if known.
1151
1152=cut
1153
1154sub write {
1155 my $c = shift;
1156
1157 # Finalize headers if someone manually writes output
1158 $c->finalize_headers;
1159
1160 return $c->engine->write( $c, @_ );
1161}
1162
1163no Moose;
1164__PACKAGE__->meta->make_immutable;
1165
11661;
1167
1168__END__
1169
1170=head1 NAME
1171
1172Catalyst::Context - object for keeping request related state
1173
1174=head1 ATTRIBUTES
1175
1176=head3 action
1177
1178=head3 counter
1179
1180=head3 namespace
1181
1182=head3 request_class
1183
1184=head3 request
1185
1186=head3 response_class
1187
1188=head3 response
1189
1190=head3 stack
1191
1192=head3 stash
1193
1194=head3 state
1195
1196=head3 stats
1197
1198=head1 SEE ALSO
1199
1200L<Catalyst>, L<Catalyst::Model>, L<Catalyst::View>, L<Catalyst::Controller>.
1201
1202=head1 AUTHORS
1203
1204Catalyst Contributors, see Catalyst.pm
1205
1206=head1 COPYRIGHT
1207
1208This library is free software. You can redistribute it and/or modify it under
1209the same terms as Perl itself.
1210
1211=cut
1212