Merge branch 'master' of github.com:bobtfish/catalyst-action-rest
[catagits/Catalyst-Action-REST.git] / lib / Catalyst / TraitFor / Request / REST.pm
CommitLineData
e623bdf2 1package Catalyst::TraitFor::Request::REST;
2use Moose::Role;
3use HTTP::Headers::Util qw(split_header_words);
4use namespace::autoclean;
5
6has [qw/ data accept_only /] => ( is => 'rw' );
7
8sub accepted_content_types {
9 my $self = shift;
10
11 return $self->{content_types} if $self->{content_types};
12
13 my %types;
14
15 # First, we use the content type in the HTTP Request. It wins all.
16 $types{ $self->content_type } = 3
17 if $self->content_type;
18
19 if ($self->method eq "GET" && $self->param('content-type')) {
20 $types{ $self->param('content-type') } = 2;
21 }
22
23 # Third, we parse the Accept header, and see if the client
24 # takes a format we understand.
25 #
26 # This is taken from chansen's Apache2::UploadProgress.
27 if ( $self->header('Accept') ) {
28 $self->accept_only(1) unless keys %types;
29
30 my $accept_header = $self->header('Accept');
31 my $counter = 0;
32
33 foreach my $pair ( split_header_words($accept_header) ) {
34 my ( $type, $qvalue ) = @{$pair}[ 0, 3 ];
35 next if $types{$type};
36
37 # cope with invalid (missing required q parameter) header like:
38 # application/json; charset="utf-8"
39 # http://tools.ietf.org/html/rfc2616#section-14.1
40 unless ( defined $pair->[2] && lc $pair->[2] eq 'q' ) {
41 $qvalue = undef;
42 }
43
44 unless ( defined $qvalue ) {
45 $qvalue = 1 - ( ++$counter / 1000 );
46 }
47
48 $types{$type} = sprintf( '%.3f', $qvalue );
49 }
50 }
51
52 return $self->{content_types} =
53 [ sort { $types{$b} <=> $types{$a} } keys %types ];
54}
55
56sub preferred_content_type { $_[0]->accepted_content_types->[0] }
57
58sub accepts {
59 my $self = shift;
60 my $type = shift;
61
62 return grep { $_ eq $type } @{ $self->accepted_content_types };
63}
64
651;