File Coverage

blib/lib/Web/Machine/Util/BodyEncoding.pm
Criterion Covered Total %
statement 41 41 100.0
branch 13 14 92.8
condition 7 10 70.0
subroutine 12 12 100.0
pod 2 2 100.0
total 75 79 94.9


line stmt bran cond sub pod time code
1             package Web::Machine::Util::BodyEncoding;
2             # ABSTRACT: Module to handle body encoding
3              
4 13     13   54 use strict;
  13         17  
  13         393  
5 13     13   49 use warnings;
  13         14  
  13         459  
6              
7             our $VERSION = '0.16';
8              
9 13     13   58 use Scalar::Util qw/ weaken isweak /;
  13         15  
  13         621  
10 13     13   6915 use Encode ();
  13         95969  
  13         384  
11 13     13   83 use Web::Machine::Util qw[ first pair_key pair_value ];
  13         18  
  13         160  
12              
13 13         100 use Sub::Exporter -setup => {
14             exports => [qw[
15             encode_body_if_set
16             encode_body
17             ]]
18 13     13   4722 };
  13         19  
19              
20             sub encode_body_if_set {
21 7     7 1 11 my ($resource, $response) = @_;
22 7 100       16 encode_body( $resource, $response ) if $response->body;
23             }
24              
25             sub encode_body {
26 36     36 1 79 my ($resource, $response) = @_;
27              
28 36         106 my $metadata = $resource->request->env->{'web.machine.context'};
29 36         115 my $chosen_encoding = $metadata->{'Content-Encoding'};
30 36         79 my $encoder = $resource->encodings_provided->{ $chosen_encoding };
31              
32 36         123 my $chosen_charset = $metadata->{'Charset'};
33 36         43 my $charsetter;
34 36 100 66     99 if ( $chosen_charset && $resource->charsets_provided ) {
35             my $match = first {
36 18 100 66 18   116 my $name = $_ && ref $_ ? pair_key($_) : $_;
37 18 50       61 $name && $name eq $chosen_charset;
38             }
39 14         99 @{ $resource->charsets_provided };
  14         22  
40              
41             $charsetter
42             = ref $match
43             ? pair_value($match)
44 14 100   6   70 : sub { Encode::encode( $match, $_[1] ) };
  6         16  
45             }
46              
47 36   100 125   181 $charsetter ||= sub { $_[1] };
  125         232  
48              
49 36   50     95 push @{ $resource->request->env->{'web.machine.content_filters'} ||= [] },
50             sub {
51 145     145   1202 my $chunk = shift;
52 145 100       431 weaken $resource unless isweak $resource;
53 145 100       223 return unless defined $chunk;
54 139         169 return $resource->$encoder($resource->$charsetter($chunk));
55 36         35 };
56             }
57              
58              
59             1;
60              
61             __END__