1use warnings;
2use strict;
3
4package Jifty::Response;
5
6=head1 NAME
7
8Jifty::Response - Canonical internal representation of the result of a L<Jifty::Action>
9
10=head1 DESCRIPTION
11
12The answer to a L<Jifty::Request> is a C<Jifty::Response> object.
13Currently, the response object exists merely to collect the
14L<Jifty::Result> objects of each L<Jifty::Action> that ran.
15
16=cut
17
18use Any::Moose;
19
20# Monkeypatch Mouse to silence misleading warnings.  See rt.cpan.org #63675.
21{
22    no warnings 'redefine';
23    *Mouse::Meta::Class::inherit_from_foreign_class = sub { return };
24}
25
26extends 'Plack::Response';
27
28has 'error'   => (is => 'rw');
29
30=head2 new
31
32Default the status to 200.
33
34=cut
35
36sub new {
37    my $class = shift;
38    my $self = $class->SUPER::new(@_);
39    $self->status(200) unless $self->status;
40    return $self;
41}
42
43=head2 add_header NAME VALUE
44
45Deprecated.  Use header(NAME, VALUE)
46
47=cut
48
49sub add_header {
50    my $self = shift;
51    $self->header(@_);
52}
53
54=head2 result MONIKER [RESULT]
55
56Gets or sets the L<Jifty::Result> of the L<Jifty::Action> with the given
57I<MONIKER>.
58
59=cut
60
61sub result {
62    my $self = shift;
63    my $moniker = shift;
64    $self->{results}{$moniker} = shift if @_;
65    return $self->{results}{$moniker};
66}
67
68=head2 results
69
70Returns a hash which maps moniker to its L<Jifty::Result>
71
72=cut
73
74sub results {
75    my $self = shift;
76    return %{$self->{results} || {}};
77}
78
79=head2 messages
80
81Returns the aggregate messages of all of the L<Jifty::Result>s.
82
83=cut
84
85sub messages {
86    my $self = shift;
87    my %results = $self->results;
88    return map {$_, $results{$_}->message} grep {defined $results{$_}->message and length $results{$_}->message} sort keys %results;
89}
90
91=head2 error [MESSAGE]
92
93Gets or sets a generalized error response.  Setting an error also
94makes the response a L</failure>.
95
96=head2 success
97
98Returns true if none of the results are failures and there is no
99L</error> set.
100
101=cut
102
103sub success {
104    my $self = shift;
105    return 0 if grep {$_->failure} values %{$self->{results} || {}};
106    return 1;
107}
108
109=head2 failure
110
111Returns true if any of the results failed or there was an L</error>
112set.
113
114=cut
115
116sub failure {
117    my $self = shift;
118    return not $self->success;
119}
120
121no Any::Moose;
122__PACKAGE__->meta->make_immutable(inline_constructor => 0);
1231;
124