File Coverage

blib/lib/SockJS/Transport/JSONPSend.pm
Criterion Covered Total %
statement 42 43 97.6
branch 14 16 87.5
condition 7 11 63.6
subroutine 7 7 100.0
pod 0 2 0.0
total 70 79 88.6


line stmt bran cond sub pod time code
1             package SockJS::Transport::JSONPSend;
2              
3 1     1   417 use strict;
  1         3  
  1         27  
4 1     1   5 use warnings;
  1         2  
  1         25  
5              
6 1     1   5 use base 'SockJS::Transport::Base';
  1         2  
  1         434  
7              
8 1     1   616 use JSON ();
  1         11914  
  1         379  
9              
10             sub new {
11 7     7 0 18096 my $self = shift->SUPER::new(@_);
12              
13 7         16 push @{$self->{allowed_methods}}, 'POST';
  7         18  
14              
15 7         17 return $self;
16             }
17              
18             sub dispatch_POST {
19 7     7 0 14 my $self = shift;
20 7         13 my ($env, $conn) = @_;
21              
22 7 100       33 return [404, [], ['Not found']] unless $conn->is_connected;
23              
24 6         15 my $data = $self->_get_content($env);
25 6 100 66     28 return $data if $data && ref $data eq 'ARRAY';
26              
27 4         43 my $json = JSON->new->utf8->allow_nonref(0);
28              
29 4         7 my $message;
30 4 100       9 eval { $message = $json->decode($data) } || do {
  4         36  
31 1         4 return $self->_return_error('Broken JSON encoding.');
32             };
33              
34 3 50 33     15 if ($message && ref $message eq 'ARRAY') {
35 3         8 $conn->fire_event('data', @$message);
36             }
37              
38             return [
39 3         21 200,
40             [
41             'Content-Type' => 'text/plain; charset=UTF-8',
42             'Content-Length' => 2,
43             ],
44             ['ok']
45             ];
46             }
47              
48             sub _get_content {
49 6     6   10 my $self = shift;
50 6         9 my ($env) = @_;
51              
52 6   100     18 my $content_length = $env->{CONTENT_LENGTH} || 0;
53 6         17 my $rcount = $env->{'psgi.input'}->read(my $chunk, $content_length);
54              
55 6 100       119 return $self->_return_error('System error')
56             unless $rcount == $content_length;
57              
58 5         8 my $d;
59              
60 5 100 66     18 if ( $env->{CONTENT_TYPE}
61             && $env->{CONTENT_TYPE} eq 'application/x-www-form-urlencoded')
62             {
63 1         3 $chunk =~ s{\+}{ }g;
64 1         7 ($d) = $chunk =~ m/(?:^|&|;)d=([^&;]*)/;
65 1 50       5 $d =~ s/%(..)/chr(hex($1))/eg if defined $d;
  0         0  
66             }
67             else {
68 4         8 $d = $chunk;
69             }
70              
71 5 100       13 return $self->_return_error('Payload expected.') unless length $d;
72              
73 4         10 return $d;
74             }
75              
76             1;