File Coverage

lib/Mojolicious/Plugin/SessionCompress.pm
Criterion Covered Total %
statement 42 42 100.0
branch 10 10 100.0
condition 7 11 63.6
subroutine 9 9 100.0
pod 1 1 100.0
total 69 73 94.5


line stmt bran cond sub pod time code
1             package Mojolicious::Plugin::SessionCompress;
2 2     2   2068 use Mojo::Base 'Mojolicious::Plugin';
  2         5  
  2         16  
3 2     2   464 use Mojo::Util ();
  2         5  
  2         32  
4 2     2   136 use Mojo::JSON ();
  2         4  
  2         39  
5 2     2   1238 use Compress::Zlib ();
  2         58698  
  2         1156  
6              
7             our $VERSION = '0.03';
8              
9             sub register {
10 2     2 1 106 my ($self, $app, $conf) = @_;
11 2   50     11 $conf ||= {};
12 2         4 my ($compress, $decompress, $serialize, $deserialize);
13              
14 2 100       11 my $min_size = exists $conf->{min_size} ? delete $conf->{min_size} : 250;
15 2 100 66     14 if (exists $conf->{compress} && exists $conf->{decompress}) {
16 1         3 $compress = delete $conf->{compress};
17 1         3 $decompress = delete $conf->{decompress};
18             } else {
19             $compress = sub {
20 2     2   7 my $string = shift;
21              
22 2         18 my $d = Compress::Zlib::deflateInit(-Level => 1, -memLevel => 5, -WindowBits => -15);
23 2         656 return $d->deflate($string) . $d->flush;
24 1         5 };
25              
26             $decompress = sub {
27 2     2   6 my $string = $_[0];
28              
29 2         24 my $d = Compress::Zlib::inflateInit(-WindowBits => -15);
30 2         497 my ($inflated, $status) = $d->inflate($string);
31             # Check to see if it's actually compressed
32 2 100 66     105 return $_[0] if $status != Compress::Zlib::Z_STREAM_END || length($inflated) <= 1;
33 1         21 return $inflated;
34 1         6 };
35             }
36              
37 2 100 66     19 if (exists $conf->{serialize} && exists $conf->{deserialize}) {
38 1         2 $serialize = delete $conf->{serialize};
39 1         2 $deserialize = delete $conf->{deserialize};
40             } else {
41 1         3 $serialize = \&Mojo::JSON::encode_json;
42 1         2 $deserialize = \&Mojo::JSON::j;
43             }
44              
45             $app->sessions->serialize(sub {
46 8     8   150822 my $hashref = shift;
47              
48 8         38 my $serialized = $serialize->($hashref);
49 8 100       3670 return $serialized if (length $serialized < $min_size);
50 4         16 return $compress->($serialized);
51 2         62 });
52              
53             $app->sessions->deserialize(sub {
54 4     4   79592 my $string = shift;
55              
56 4         23 return $deserialize->($decompress->($string));
57 2         166 });
58             }
59              
60             1;
61             __END__