live serving page in minimal app, plus a new test for that
[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 ) = @_;
710 my $appclass = ref($c) || $c;
711 return if ( ( $code->name =~ /^_.*/ )
712 && ( !$appclass->config->{show_internal_actions} ) );
713
714 my $action_name = $code->reverse();
715 $c->counter->{$action_name}++;
716
717 my $action = $action_name;
718 $action = "/$action" unless $action =~ /->/;
719
720 # determine if the call was the result of a forward
721 # this is done by walking up the call stack and looking for a calling
722 # sub of Catalyst::forward before the eval
723 my $callsub = q{};
724 for my $index ( 2 .. 11 ) {
725 last
726 if ( ( caller($index) )[0] eq 'Catalyst'
727 && ( caller($index) )[3] eq '(eval)' );
728
729 if ( ( caller($index) )[3] =~ /forward$/ ) {
730 $callsub = ( caller($index) )[3];
731 $action = "-> $action";
732 last;
733 }
734 }
735
736 my $uid = $action_name . $c->counter->{$action_name};
737
738 # is this a root-level call or a forwarded call?
739 if ( $callsub =~ /forward$/ ) {
740 my $parent = $c->stack->[-1];
741
742 # forward, locate the caller
743 if ( exists $c->counter->{"$parent"} ) {
744 $c->stats->profile(
745 begin => $action,
746 parent => "$parent" . $c->counter->{"$parent"},
747 uid => $uid,
748 );
749 }
750 else {
751
752 # forward with no caller may come from a plugin
753 $c->stats->profile(
754 begin => $action,
755 uid => $uid,
756 );
757 }
758 }
759 else {
760
761 # root-level call
762 $c->stats->profile(
763 begin => $action,
764 uid => $uid,
765 );
766 }
767 return $action;
768
769}
770
771sub _stats_finish_execute {
772 my ( $c, $info ) = @_;
773 $c->stats->profile( end => $info );
774}
775
776=head2 $c->finalize
777
778Finalizes the request.
779
780=cut
781
782sub finalize {
783 my $c = shift;
784
785 for my $error ( @{ $c->error } ) {
786 $c->log->error($error);
787 }
788
789 # Allow engine to handle finalize flow (for POE)
790 my $engine = $c->engine;
791 if ( my $code = $engine->can('finalize') ) {
792 $engine->$code($c);
793 }
794 else {
795
796 $c->finalize_uploads;
797
798 # Error
799 if ( $#{ $c->error } >= 0 ) {
800 $c->finalize_error;
801 }
802
803 $c->finalize_headers;
804
805 # HEAD request
806 if ( $c->request->method eq 'HEAD' ) {
807 $c->response->body('');
808 }
809
810 $c->finalize_body;
811 }
812
813 if ($c->use_stats) {
814 my $elapsed = sprintf '%f', $c->stats->elapsed;
815 my $av = $elapsed == 0 ? '??' : sprintf '%.3f', 1 / $elapsed;
816 $c->log->info(
817 "Request took ${elapsed}s ($av/s)\n" . $c->stats->report . "\n" );
818 }
819
820 return $c->response->status;
821}
822
823=head2 $c->finalize_body
824
825Finalizes body.
826
827=cut
828
829sub finalize_body { my $c = shift; $c->engine->finalize_body( $c, @_ ) }
830
831=head2 $c->finalize_cookies
832
833Finalizes cookies.
834
835=cut
836
837sub finalize_cookies { my $c = shift; $c->engine->finalize_cookies( $c, @_ ) }
838
839=head2 $c->finalize_error
840
841Finalizes error.
842
843=cut
844
845sub finalize_error { my $c = shift; $c->engine->finalize_error( $c, @_ ) }
846
847=head2 $c->finalize_headers
848
849Finalizes headers.
850
851=cut
852
853sub finalize_headers {
854 my $c = shift;
855
856 my $response = $c->response; #accessor calls can add up?
857
858 # Check if we already finalized headers
859 return if $response->finalized_headers;
860
861 # Handle redirects
862 if ( my $location = $response->redirect ) {
863 $c->log->debug(qq/Redirecting to "$location"/) if $c->debug;
864 $response->header( Location => $location );
865
866 if ( !$response->has_body ) {
867 # Add a default body if none is already present
868 $response->body(
869 qq{<html><body><p>This item has moved <a href="$location">here</a>.</p></body></html>}
870 );
871 }
872 }
873
874 # Content-Length
875 if ( $response->body && !$response->content_length ) {
876
877 # get the length from a filehandle
878 if ( blessed( $response->body ) && $response->body->can('read') )
879 {
880 my $stat = stat $response->body;
881 if ( $stat && $stat->size > 0 ) {
882 $response->content_length( $stat->size );
883 }
884 else {
885 $c->log->warn('Serving filehandle without a content-length');
886 }
887 }
888 else {
889 # everything should be bytes at this point, but just in case
890 $response->content_length( bytes::length( $response->body ) );
891 }
892 }
893
894 # Errors
895 if ( $response->status =~ /^(1\d\d|[23]04)$/ ) {
896 $response->headers->remove_header("Content-Length");
897 $response->body('');
898 }
899
900 $c->finalize_cookies;
901
902 $c->engine->finalize_headers( $c, @_ );
903
904 # Done
905 $response->finalized_headers(1);
906}
907
908=head2 $c->finalize_output
909
910An alias for finalize_body.
911
912=head2 $c->finalize_read
913
914Finalizes the input after reading is complete.
915
916=cut
917
918sub finalize_read { my $c = shift; $c->engine->finalize_read( $c, @_ ) }
919
920=head2 $c->finalize_uploads
921
922Finalizes uploads. Cleans up any temporary files.
923
924=cut
925
926sub finalize_uploads { my $c = shift; $c->engine->finalize_uploads( $c, @_ ) }
927
928=head2 $c->get_action( $action, $namespace )
929
930Gets an action in a given namespace.
931
932=cut
933
934sub get_action { my $c = shift; $c->dispatcher->get_action(@_) }
935
936=head2 $c->get_actions( $action, $namespace )
937
938Gets all actions of a given name in a namespace and all parent
939namespaces.
940
941=cut
942
943sub get_actions { my $c = shift; $c->dispatcher->get_actions( $c, @_ ) }
944
945=head2 $c->prepare_action
946
947Prepares action. See L<Catalyst::Dispatcher>.
948
949=cut
950
951sub prepare_action { my $c = shift; $c->dispatcher->prepare_action( $c, @_ ) }
952
953=head2 $c->prepare_body
954
955Prepares message body.
956
957=cut
958
959sub prepare_body {
960 my $c = shift;
961
962 return if $c->request->_has_body;
963
964 # Initialize on-demand data
965 $c->engine->prepare_body( $c, @_ );
966 $c->prepare_parameters;
967 $c->prepare_uploads;
968
969 if ( $c->debug && keys %{ $c->req->body_parameters } ) {
970 my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
971 for my $key ( sort keys %{ $c->req->body_parameters } ) {
972 my $param = $c->req->body_parameters->{$key};
973 my $value = defined($param) ? $param : '';
974 $t->row( $key,
975 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
976 }
977 $c->log->debug( "Body Parameters are:\n" . $t->draw );
978 }
979}
980
981=head2 $c->prepare_body_chunk( $chunk )
982
983Prepares a chunk of data before sending it to L<HTTP::Body>.
984
985See L<Catalyst::Engine>.
986
987=cut
988
989sub prepare_body_chunk {
990 my $c = shift;
991 $c->engine->prepare_body_chunk( $c, @_ );
992}
993
994=head2 $c->prepare_body_parameters
995
996Prepares body parameters.
997
998=cut
999
1000sub prepare_body_parameters {
1001 my $c = shift;
1002 $c->engine->prepare_body_parameters( $c, @_ );
1003}
1004
1005=head2 $c->prepare_connection
1006
1007Prepares connection.
1008
1009=cut
1010
1011sub prepare_connection {
1012 my $c = shift;
1013 $c->engine->prepare_connection( $c, @_ );
1014}
1015
1016=head2 $c->prepare_cookies
1017
1018Prepares cookies.
1019
1020=cut
1021
1022sub prepare_cookies { my $c = shift; $c->engine->prepare_cookies( $c, @_ ) }
1023
1024=head2 $c->prepare_headers
1025
1026Prepares headers.
1027
1028=cut
1029
1030sub prepare_headers { my $c = shift; $c->engine->prepare_headers( $c, @_ ) }
1031
1032=head2 $c->prepare_parameters
1033
1034Prepares parameters.
1035
1036=cut
1037
1038sub prepare_parameters {
1039 my $c = shift;
1040 $c->prepare_body_parameters;
1041 $c->engine->prepare_parameters( $c, @_ );
1042}
1043
1044=head2 $c->prepare_path
1045
1046Prepares path and base.
1047
1048=cut
1049
1050sub prepare_path { my $c = shift; $c->engine->prepare_path( $c, @_ ) }
1051
1052=head2 $c->prepare_query_parameters
1053
1054Prepares query parameters.
1055
1056=cut
1057
1058sub prepare_query_parameters {
1059 my $c = shift;
1060
1061 $c->engine->prepare_query_parameters( $c, @_ );
1062
1063 if ( $c->debug && keys %{ $c->request->query_parameters } ) {
1064 my $t = Text::SimpleTable->new( [ 35, 'Parameter' ], [ 36, 'Value' ] );
1065 for my $key ( sort keys %{ $c->req->query_parameters } ) {
1066 my $param = $c->req->query_parameters->{$key};
1067 my $value = defined($param) ? $param : '';
1068 $t->row( $key,
1069 ref $value eq 'ARRAY' ? ( join ', ', @$value ) : $value );
1070 }
1071 $c->log->debug( "Query Parameters are:\n" . $t->draw );
1072 }
1073}
1074
1075=head2 $c->prepare_read
1076
1077Prepares the input for reading.
1078
1079=cut
1080
1081sub prepare_read { my $c = shift; $c->engine->prepare_read( $c, @_ ) }
1082
1083=head2 $c->prepare_request
1084
1085Prepares the engine request.
1086
1087=cut
1088
1089sub prepare_request { my $c = shift; $c->engine->prepare_request( $c, @_ ) }
1090
1091=head2 $c->prepare_uploads
1092
1093Prepares uploads.
1094
1095=cut
1096
1097sub prepare_uploads {
1098 my $c = shift;
1099
1100 $c->engine->prepare_uploads( $c, @_ );
1101
1102 if ( $c->debug && keys %{ $c->request->uploads } ) {
1103 my $t = Text::SimpleTable->new(
1104 [ 12, 'Parameter' ],
1105 [ 26, 'Filename' ],
1106 [ 18, 'Type' ],
1107 [ 9, 'Size' ]
1108 );
1109 for my $key ( sort keys %{ $c->request->uploads } ) {
1110 my $upload = $c->request->uploads->{$key};
1111 for my $u ( ref $upload eq 'ARRAY' ? @{$upload} : ($upload) ) {
1112 $t->row( $key, $u->filename, $u->type, $u->size );
1113 }
1114 }
1115 $c->log->debug( "File Uploads are:\n" . $t->draw );
1116 }
1117}
1118
1119=head2 $c->prepare_write
1120
1121Prepares the output for writing.
1122
1123=cut
1124
1125sub prepare_write { my $c = shift; $c->engine->prepare_write( $c, @_ ) }
1126
1127=head2 $c->read( [$maxlength] )
1128
1129Reads a chunk of data from the request body. This method is designed to
1130be used in a while loop, reading C<$maxlength> bytes on every call.
1131C<$maxlength> defaults to the size of the request if not specified.
1132
1133You have to set C<< MyApp->config(parse_on_demand => 1) >> to use this
1134directly.
1135
1136Warning: If you use read(), Catalyst will not process the body,
1137so you will not be able to access POST parameters or file uploads via
1138$c->request. You must handle all body parsing yourself.
1139
1140=cut
1141
1142sub read { my $c = shift; return $c->engine->read( $c, @_ ) }
1143
1144=head2 $c->stack
1145
1146Returns an arrayref of the internal execution stack (actions that are
1147currently executing).
1148
1149
1150=head2 $c->write( $data )
1151
1152Writes $data to the output stream. When using this method directly, you
1153will need to manually set the C<Content-Length> header to the length of
1154your output data, if known.
1155
1156=cut
1157
1158sub write {
1159 my $c = shift;
1160
1161 # Finalize headers if someone manually writes output
1162 $c->finalize_headers;
1163
1164 return $c->engine->write( $c, @_ );
1165}
1166
1167no Moose;
1168__PACKAGE__->meta->make_immutable;
1169
11701;
1171
1172__END__
1173
1174=head1 NAME
1175
1176Catalyst::Context - object for keeping request related state
1177
1178=head1 ATTRIBUTES
1179
1180=head3 action
1181
1182=head3 counter
1183
1184=head3 namespace
1185
1186=head3 request_class
1187
1188=head3 request
1189
1190=head3 response_class
1191
1192=head3 response
1193
1194=head3 stack
1195
1196=head3 stash
1197
1198=head3 state
1199
1200=head3 stats
1201
1202=head1 SEE ALSO
1203
1204L<Catalyst>, L<Catalyst::Model>, L<Catalyst::View>, L<Catalyst::Controller>.
1205
1206=head1 AUTHORS
1207
1208Catalyst Contributors, see Catalyst.pm
1209
1210=head1 COPYRIGHT
1211
1212This library is free software. You can redistribute it and/or modify it under
1213the same terms as Perl itself.
1214
1215=cut
1216