Add option to break a chain if error occurs
[catagits/Catalyst-Runtime.git] / lib / Catalyst / ActionChain.pm
1 package Catalyst::ActionChain;
2
3 use Moose;
4 extends qw(Catalyst::Action);
5
6 has chain => (is => 'rw');
7 no Moose;
8
9 =head1 NAME
10
11 Catalyst::ActionChain - Chain of Catalyst Actions
12
13 =head1 SYNOPSIS
14
15 See L<Catalyst::Manual::Intro> for more info about Chained actions.
16
17 =head1 DESCRIPTION
18
19 This class represents a chain of Catalyst Actions. It behaves exactly like
20 the action at the *end* of the chain except on dispatch it will execute all
21 the actions in the chain in order.
22
23 =cut
24
25 sub dispatch {
26     my ( $self, $c ) = @_;
27     my @captures = @{$c->req->captures||[]};
28     my @chain = @{ $self->chain };
29     my $last = pop(@chain);
30     foreach my $action ( @chain ) {
31         my @args;
32         if (my $cap = $action->number_of_captures) {
33           @args = splice(@captures, 0, $cap);
34         }
35         local $c->request->{arguments} = \@args;
36         $action->dispatch( $c );
37
38         # break the chain if exception occurs in the middle of chain
39         return if (@{$c->error} && $c->config->{detach_on_die});
40     }
41     $last->dispatch( $c );
42 }
43
44 sub from_chain {
45     my ( $self, $actions ) = @_;
46     my $final = $actions->[-1];
47     return $self->new({ %$final, chain => $actions });
48 }
49
50 sub number_of_captures {
51     my ( $self ) = @_;
52     my $chain = $self->chain;
53     my $captures = 0;
54
55     $captures += $_->number_of_captures for @$chain;
56     return $captures;
57 }
58
59 __PACKAGE__->meta->make_immutable;
60 1;
61
62 __END__
63
64 =head1 METHODS
65
66 =head2 chain
67
68 Accessor for the action chain; will be an arrayref of the Catalyst::Action
69 objects encapsulated by this chain.
70
71 =head2 dispatch( $c )
72
73 Dispatch this action chain against a context; will dispatch the encapsulated
74 actions in order.
75
76 =head2 from_chain( \@actions )
77
78 Takes a list of Catalyst::Action objects and constructs and returns a
79 Catalyst::ActionChain object representing a chain of these actions
80
81 =head2 number_of_captures
82
83 Returns the total number of captures for the entire chain of actions.
84
85 =head2 meta
86
87 Provided by Moose
88
89 =head1 AUTHORS
90
91 Catalyst Contributors, see Catalyst.pm
92
93 =head1 COPYRIGHT
94
95 This library is free software. You can redistribute it and/or modify it under
96 the same terms as Perl itself.
97
98 =cut