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