File Coverage

blib/lib/Trickster/Session.pm
Criterion Covered Total %
statement 26 26 100.0
branch 2 4 50.0
condition 6 12 50.0
subroutine 9 9 100.0
pod 4 4 100.0
total 47 55 85.4


line stmt bran cond sub pod time code
1             package Trickster::Session;
2              
3 1     1   906 use strict;
  1         1  
  1         27  
4 1     1   4 use warnings;
  1         1  
  1         44  
5 1     1   8 use v5.14;
  1         2  
6              
7 1     1   4 use JSON::PP qw(encode_json decode_json);
  1         1  
  1         68  
8 1     1   4 use Carp qw(croak);
  1         1  
  1         290  
9              
10             sub new {
11 1     1 1 8 my ($class, %opts) = @_;
12            
13 1 50       4 croak "cookie => Trickster::Cookie required" unless $opts{cookie};
14            
15             return bless {
16             cookie => $opts{cookie},
17             name => $opts{name} || 'trick_session',
18             max_age => $opts{max_age},
19             secure => $opts{secure} // 1,
20             httponly => $opts{httponly} // 1,
21 1   50     11 samesite => $opts{samesite} // 'Lax',
      50        
      50        
      50        
22             }, $class;
23             }
24              
25             sub get {
26 1     1 1 6 my ($self, $req) = @_;
27            
28 1         3 my $raw = $self->{cookie}->get($req, $self->{name});
29 1 50       31 return {} unless $raw;
30            
31 1   50     1 return eval { decode_json($raw) } || {};
32             }
33              
34             sub set {
35 1     1 1 6 my ($self, $res, $data) = @_;
36            
37 1   50     5 my $json = encode_json($data // {});
38            
39             $self->{cookie}->set(
40             $res,
41             $self->{name},
42             $json,
43             max_age => $self->{max_age},
44             secure => $self->{secure},
45             httponly => $self->{httponly},
46             samesite => $self->{samesite},
47 1         94 );
48             }
49              
50             sub clear {
51 1     1 1 7 my ($self, $res) = @_;
52            
53 1         4 $self->{cookie}->delete($res, $self->{name});
54             }
55              
56             1;
57              
58             __END__