File Coverage

blib/lib/Dancer2/Plugin/WebSocket/Connection.pm
Criterion Covered Total %
statement 12 25 48.0
branch 0 2 0.0
condition 0 3 0.0
subroutine 4 8 50.0
pod 4 4 100.0
total 20 42 47.6


line stmt bran cond sub pod time code
1             package Dancer2::Plugin::WebSocket::Connection;
2             our $AUTHORITY = 'cpan:YANICK';
3             # ABSTRACT: Role tying Plack::App::WebSocket::Connection with the Dancer serializer
4             $Dancer2::Plugin::WebSocket::Connection::VERSION = '0.1.3';
5              
6              
7 1     1   779 use Scalar::Util qw/ refaddr /;
  1         2  
  1         68  
8 1     1   493 use Set::Tiny;
  1         1274  
  1         50  
9              
10 1     1   458 use Dancer2::Plugin::WebSocket::Group;
  1         3  
  1         36  
11              
12 1     1   8 use Moo::Role;
  1         3  
  1         7  
13              
14             has manager => (
15             is => 'rw',
16             );
17              
18             has serializer => (
19             is => 'rw',
20             );
21              
22             has id => (
23             is => 'ro',
24             lazy => 1,
25             default => sub { refaddr shift },
26             );
27              
28             has channels => (
29             is => 'rw',
30             lazy => 1,
31             clearer => 1,
32             default => sub { Set::Tiny->new( '*', $_[0]->id ) },
33             );
34              
35              
36             sub set_channels {
37 0     0 1   my ( $self, @channels ) = @_;
38 0           $self->clear_channels;
39 0           $self->add_channels(@channels);
40             }
41              
42              
43             sub add_channels {
44 0     0 1   my ( $self, @channels ) = @_;
45 0           $self->channels->insert(@channels);
46             }
47              
48             around send => sub {
49             my( $orig, $self, $message ) = @_;
50             if( my $s = $self->serializer and ref $message ne 'AnyEvent::WebSocket::Message' ) {
51             $message = $s->encode($message);
52             }
53             $orig->($self,$message);
54             };
55              
56              
57             sub in_channel {
58 0     0 1   my ( $self, @channels ) = @_;
59 0           my $target_set;
60 0 0 0       if ( @channels == 1 and ref $channels[0] eq 'Set::Tiny' ) {
61 0           $target_set = shift @channels;
62             }
63             else {
64 0           $target_set = Set::Tiny->new(@channels);
65             }
66 0           return not $self->channels->is_disjoint($target_set);
67             }
68              
69              
70             sub to {
71 0     0 1   my ( $self, @channels ) = @_;
72 0           return Dancer2::Plugin::WebSocket::Group->new(
73             source => $self,
74             channels => \@channels,
75             );
76             }
77              
78             1;
79              
80             __END__