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   439 use strict;
  1         2  
  1         28  
4 1     1   5 use warnings;
  1         2  
  1         27  
5              
6 1     1   5 use base 'SockJS::Transport::Base';
  1         2  
  1         499  
7              
8 1     1   679 use JSON ();
  1         12275  
  1         395  
9              
10             sub new {
11 7     7 0 17945 my $self = shift->SUPER::new(@_);
12              
13 7         11 push @{$self->{allowed_methods}}, 'POST';
  7         16  
14              
15 7         18 return $self;
16             }
17              
18             sub dispatch_POST {
19 7     7 0 10 my $self = shift;
20 7         13 my ($env, $conn) = @_;
21              
22 7 100       18 return [404, [], ['Not found']] unless $conn->is_connected;
23              
24 6         17 my $data = $self->_get_content($env);
25 6 100 66     30 return $data if $data && ref $data eq 'ARRAY';
26              
27 4         50 my $json = JSON->new->utf8->allow_nonref(0);
28              
29 4         7 my $message;
30 4 100       7 eval { $message = $json->decode($data) } || do {
  4         36  
31 1         5 return $self->_return_error('Broken JSON encoding.');
32             };
33              
34 3 50 33     16 if ($message && ref $message eq 'ARRAY') {
35 3         9 $conn->fire_event('data', @$message);
36             }
37              
38             return [
39 3         25 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   21 my $self = shift;
50 6         19 my ($env) = @_;
51              
52 6   100     17 my $content_length = $env->{CONTENT_LENGTH} || 0;
53 6         20 my $rcount = $env->{'psgi.input'}->read(my $chunk, $content_length);
54              
55 6 100       125 return $self->_return_error('System error')
56             unless $rcount == $content_length;
57              
58 5         6 my $d;
59              
60 5 100 66     31 if ( $env->{CONTENT_TYPE}
61             && $env->{CONTENT_TYPE} eq 'application/x-www-form-urlencoded')
62             {
63 1         4 $chunk =~ s{\+}{ }g;
64 1         7 ($d) = $chunk =~ m/(?:^|&|;)d=([^&;]*)/;
65 1 50       6 $d =~ s/%(..)/chr(hex($1))/eg if defined $d;
  0         0  
66             }
67             else {
68 4         7 $d = $chunk;
69             }
70              
71 5 100       14 return $self->_return_error('Payload expected.') unless length $d;
72              
73 4         9 return $d;
74             }
75              
76             1;