File Coverage

blib/lib/SockJS/Session.pm
Criterion Covered Total %
statement 32 52 61.5
branch 2 8 25.0
condition n/a
subroutine 8 12 66.6
pod 0 8 0.0
total 42 80 52.5


line stmt bran cond sub pod time code
1             package SockJS::Session;
2              
3 1     1   72725 use strict;
  1         11  
  1         40  
4 1     1   7 use warnings;
  1         2  
  1         24  
5              
6 1     1   680 use JSON ();
  1         12457  
  1         26  
7 1     1   613 use Encode ();
  1         9778  
  1         441  
8              
9             sub new {
10 2     2 0 4220 my $class = shift;
11 2         5 my (%params) = @_;
12              
13 2         3 my $self = {};
14 2         4 bless $self, $class;
15              
16 2         6 $self->{id} = $params{id};
17 2         5 $self->{type} = $params{type};
18 2         4 $self->{conn} = $params{connection};
19              
20 2         5 return $self;
21             }
22              
23             sub set {
24 1     1 0 6 my $self = shift;
25 1         3 my ($key, $value) = @_;
26              
27 1         3 $self->{custom}->{$key} = $value;
28              
29 1         3 return $self;
30             }
31              
32             sub get {
33 1     1 0 4 my $self = shift;
34 1         2 my ($key) = @_;
35              
36 1         5 return $self->{custom}->{$key};
37             }
38              
39 0     0 0 0 sub type { $_[0]->{type} }
40              
41             sub on {
42 0     0 0 0 my $self = shift;
43 0         0 my ($event, $cb) = @_;
44              
45 0         0 push @{$self->{"on_$event"}}, $cb;
  0         0  
46              
47 0         0 return $self;
48             }
49              
50             sub write {
51 1     1 0 6 my $self = shift;
52              
53 1         1 my $message;
54 1 50       4 if (ref $_[0] eq 'SCALAR') {
55 0         0 $message = ${$_[0]};
  0         0  
56 0 0       0 $message = Encode::encode('UTF-8', $message) if Encode::is_utf8($message);
57             }
58             else {
59 1 50       33 $message = 'a' . JSON->new->ascii(1)->encode([@_]) if @_;
60             }
61              
62 1         15 return $self->{conn}->write($message);
63             }
64              
65             sub close {
66 0     0 0   my $self = shift;
67 0           my ($code, $message) = @_;
68              
69 0           $self->{conn}->close($code, $message);
70              
71 0           return $self;
72             }
73              
74             sub fire_event {
75 0     0 0   my $self = shift;
76 0           my $event = shift;
77              
78 0 0         if (exists $self->{"on_$event"}) {
79 0           foreach my $ev (@{$self->{"on_$event"}}) {
  0            
80 0           $ev->($self, @_);
81             }
82             }
83              
84 0           return $self;
85             }
86              
87             1;