blib/lib/Catalyst/ActionRole/MatchRequestAccepts.pm

filter: Statementstmt 86.0% 43 / 50 Branchbran 50.0% 6 / 12 Conditioncond 28.5% 2 / 7 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 90.9% 10 / 11 Podpod n/a totaltotal 73.8% 62 / 84 CC 11 SCAR 17.8
CC
11
Cov
74%
_query_accept
20.0
_resolve_http_accept
5.3
_split_accept_header
3.0
CRAP 5.9
↑ Summary
1 package Catalyst::ActionRole::MatchRequestAccepts;
2  
3 2 our $VERSION = '0.06';
4  
5 2 ▶use 5.008008;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Perl6::Junction 'all', 'any';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use HTTP::Headers::Util 'split_header_words';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 2 requires 'attributes';
12  
13 2 has http_accept => (is=>'ro', required=>1, default=>'http-accept');
14  
15 29 ▶sub _http_accept {
Subroutine _http_accept: called CC=1 SCAR=0.0
16 29 my ($self, $request) = @_;
17 return map {
18 29 $self->_split_accept_header($_);
19 } $request->headers->header('Accept');
20 }
21  
22 24 ▶sub _split_accept_header {
Subroutine _split_accept_header: called CC=3 SCAR=11.0
23 24 my ($self, $accept_header) = @_;
24 24 my %types;
25 24 foreach my $pair (split_header_words $accept_header) {
26 26 my ($type) = @{$pair}[0];
27 26 ▶ next if $types{$type};
Branch: 1 branch
BranchTrueFalseTotal
if $types{$type} 0 26 26
28 26 $types{$type}=1;
29 }
30 24 return keys %types;
31 }
32  
33 0 ▶sub _query_accept {
Subroutine _query_accept: not called CC=4 SCAR=30.0
34 0 my ($self, $request) = @_;
35 0 ▶ my $accept = $request->query_parameters->{$self->http_accept} || undef;
Condition0%0/2
$request->query_parameters->{$self->http_accept} || undef
l!l
00
MC/DC0%0/1
$request->query_parameters->{$self->http_accept} || undef
$request->query_parameters->{$self->http_accept}
Truth table0%0/2
A
A= $request->query_parameters->{$self->http_accept}
Aresult
11
00
36 0 ▶ (defined($accept) && ref($accept)) ? @$accept : $accept;
Branch: 1 branch
BranchTrueFalseTotal
defined $accept && ref $accept ? : 0 0 0
Condition0%0/3
defined $accept and ref $accept
!ll&&!rl&&r
000
MC/DC0%0/2
defined $accept and ref $accept
defined $accept ref $accept
Truth table0%0/3
A and B
A= defined $acceptB= ref $accept
ABresult
0X0
100
111
37 }
38  
39 29 ▶sub _resolve_http_accept {
Subroutine _resolve_http_accept: called CC=3 SCAR=16.7
40 29 my ($self, $ctx) = @_;
41 29 ▶ if($ctx->debug) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ctx->debug) { } 0 29 29
42 0 my @hdr_accepts = $self->_query_accept($ctx->req);
43 0 ▶ if($hdr_accepts[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hdr_accepts[0]) { } 0 0 0
44 0 return @hdr_accepts;
45 } else {
46 0 return $self->_http_accept($ctx->req);
47 }
48 } else {
49 29 return $self->_http_accept($ctx->req);
50 }
51 }
52  
53 29 ▶sub _resolve_accept_attr {
Subroutine _resolve_accept_attr: called CC=2 SCAR=6.9
54 29 ▶ @{shift->attributes->{Accept} || []};
Condition100%2/2
+(shift())->attributes->{'Accept'} || []
l!l
218
MC/DC100%1/1
+(shift())->attributes->{'Accept'} || []
+(shift())->attributes->{'Accept'}
Truth table100%2/2
A
A= +(shift())->attributes->{'Accept'}
Aresult
11
00
55 }
56  
57 29 ▶around 'match', sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
58 29 my ($orig, $self, $ctx) = @_;
59 29 my @attr_accepts = $self->_resolve_accept_attr;
60 29 my @hdr_accepts = $self->_resolve_http_accept($ctx);
61  
62 29 ▶ if(@attr_accepts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@attr_accepts) { } 21 8 29
63 21 ▶ if(any(@attr_accepts) eq any(@hdr_accepts)) {
Branch: 1 branch
BranchTrueFalseTotal
if (any(@attr_accepts) eq any(@hdr_accepts)) { } 9 12 21
64 9 return $self->$orig($ctx);
65 } else {
66 12 return 0;
67 }
68 } else {
69 8 return $self->$orig($ctx);
70 }
71 2 };
72  
73 2 1;
74  
75 =head1 NAME
76  
77 Catalyst::ActionRole::MatchRequestAccepts - Dispatch actions based on HTTP Accept Header
78  
79 =head1 SYNOPSIS
80  
81 package MyApp::Controller::Foo;
82  
83 use Moose;
84 use namespace::autoclean;
85  
86 BEGIN {
87 extends 'Catalyst::Controller::ActionRole';
88 }
89  
90 ## Add the ActionRole to all the Controller's actions. You can also
91 ## selectively add the ActionRole with the :Does action attribute or in
92 ## controller configuration. See Catalyst::Controller::ActionRole for
93 ## more information.
94  
95 __PACKAGE__->config(
96 action_roles => ['MatchRequestAccepts'],
97 );
98  
99 ## Match for incoming requests with HTTP Accepts: plain/html
100 sub for_html : Path('foo') Accept('plain/html') { ... }
101  
102 ## Match for incoming requests with HTTP Accepts: application/json
103 sub for_json : Path('foo') Accept('application/json') { ... }
104  
105 =head1 DESCRIPTION
106  
107 Lets you specify a match for the HTTP C<Accept> Header, which is provided by
108 the L<Catalyst> C<< $ctx->request->headers >> object. You might wish to instead
109 look at L<Catalyst::Action::REST> if you are doing complex applications that
110 match different incoming request types, but if you are very fussy about how
111 your actions match, or if you are doing some simple ajaxy bits you might like
112 to use this instead of a full on package (like L<Catalyst::Action::REST> is.)
113  
114 Currently the match performed is a pure equalty, no attempt to guess or infer
115 matches based on similarity are done. If you need to match several variations
116 you can specify all the variations with multiple attribute declarations. Right
117 now we don't support expression based matching, such as C<text/*>, although
118 adding such would probably not be very hard (although I don't want to make the
119 logic here slow down our dispatch matching too much).
120  
121 Please note that if you specify multiple C<Accept> attributes on a single
122 action, those will be matched via an OR condition and not an AND condition. In
123 other words we short circuit match the first action with at least one of the
124 C<Accept> values appearing in the requested HTTP headers. I think this is
125 correct since I imagine the purpose of multiple C<Accept> attributes would be
126 to match several acceptable variations of a given type, not to match any of
127 several unrelated types. However if you have a use case for this please let
128 me know.
129  
130 If an action consumes this role, but no C<Accept> attributes are found, the
131 action will simple accept all types.
132  
133 For debugging purposes, if the L<Catalyst> debug flag is enabled, you can
134 override the HTTP Accept header with the C<http-accept> query parameter. This
135 makes it easy to force detect in testing or in your browser. This feature is
136 NOT available when the debug flag is off.
137  
138 Also, as usual you can specify attributes and information in th configuration
139 of your L<Catalyst::Controller> subclass:
140  
141 ## Set the 'our_action_json' action to consume this ActionRole. In this
142 ## example GET '/json' would only match if the client request HTTP included
143 ## an Accept: application/json.
144  
145 __PACKAGE__->config(
146 action_roles => ['MatchRequestAccepts'],
147 action => {
148 our_action_json => { Path => 'json', Accept => 'application/json' },
149 });
150  
151 ## GET '/foo' will dispatch to either action 'our_action_json' or action
152 ## 'our_action_html' depending on the incoming HTTP Accept.
153  
154 __PACKAGE__->config(
155 action => {
156 our_action_json => {
157 Does => 'MatchRequestAccepts',
158 Path => 'foo',
159 Accept => 'application/json',
160 },
161 our_action_html => {
162 Does => 'MatchRequestAccepts',
163 Path => 'foo',
164 Accept => 'text/html',
165 },
166 });
167  
168 There's a functioning L<Catalyst> example application in the test directory for
169 your review as well.
170  
171 =head1 EXAMPLE WITH CHAINED ACTIONS
172  
173 The following example uses L<Catalyst> chaining to match one of two different
174 types of C<Accept> headers, and to return the correct HTTP error message if
175 nothing is matched. This is probably my most common use pattern.
176  
177 package MyApp::Web::Controller::Chained;
178  
179 use Moose;
180 use namespace::autoclean;
181  
182 BEGIN {
183 extends 'Catalyst::Controller::ActionRole';
184 }
185  
186 __PACKAGE__->config(
187 action_roles => ['MatchRequestAccepts'],
188 );
189  
190 sub root : Chained('/') PathPrefix CaptureArgs(0) {}
191  
192 sub text_html
193 : Chained('root') PathPart('') Accept('text/html') Args(0)
194 {
195 my ($self, $ctx) = @_;
196 $ctx->response->body('text_html');
197 }
198  
199 sub json
200 : Chained('root') PathPart('') Accept('application/json') Args(0)
201 {
202 my ($self, $ctx) = @_;
203 $ctx->response->body('json');
204 }
205  
206 sub not_accepted
207 : Chained('root') PathPart('') Args
208 {
209 my ($self, $ctx) = @_;
210 $ctx->response->status(406);
211 $ctx->response->body('error_not_accepted');
212 }
213  
214 __PACKAGE__->meta->make_immutable;
215  
216 In the given example, a C<GET> request to C<http://www.myapp.com/chained> will
217 match for C<Accept> values of HTML and JSON, and will return a status 406 error
218 to all other requests.
219  
220 =head1 AUTHOR
221  
222 John Napiorkowski L<email:jjnapiork@cpan.org>
223  
224 =head1 THANKS
225  
226 Shout out to Florian Ragwitz <rafl@debian.org> for providing such a great
227 example in L<Catalyst::ActionRole::MatchRequestMethod>. Source code and tests
228 are pretty much copied from his stuff.
229  
230 I also cargo culted a chuck of code from L<Catalyst::TraitFor::Request::REST>
231 which let me parse HTTP Accept lines.
232  
233 =head1 SEE ALSO
234  
235 L<Catalyst::ActionRole::MatchRequestMethod>, L<Catalyst::Action::REST>,
236 L<Catalyst>, L<Catalyst::Controller::ActionRole>, L<Moose>.
237  
238 =head1 COPYRIGHT & LICENSE
239  
240 Copyright 2011, John Napiorkowski L<email:jjnapiork@cpan.org>
241  
242 This library is free software; you can redistribute it and/or modify it under
243 the same terms as Perl itself.
244  
245 =cut
↑ Summary