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