File Coverage

blib/lib/WWW/FCM/HTTP.pm
Criterion Covered Total %
statement 46 47 97.8
branch 6 8 75.0
condition 4 6 66.6
subroutine 13 13 100.0
pod 2 3 66.6
total 71 77 92.2


line stmt bran cond sub pod time code
1             package WWW::FCM::HTTP;
2 3     3   236963 use 5.008001;
  3         25  
3 3     3   11 use strict;
  3         5  
  3         42  
4 3     3   10 use warnings;
  3         4  
  3         108  
5              
6             our $VERSION = "0.02";
7              
8 3     3   1412 use LWP::UserAgent;
  3         78450  
  3         95  
9 3     3   1223 use LWP::Protocol::https;
  3         210178  
  3         135  
10 3     3   1066 use LWP::ConnCache;
  3         2759  
  3         80  
11 3     3   872 use JSON qw(encode_json);
  3         12473  
  3         14  
12             use Class::Accessor::Lite (
13 3         16 new => 0,
14             rw => [qw/ua api_url api_key json/],
15 3     3   1402 );
  3         2284  
16 3     3   221 use Carp qw(croak);
  3         5  
  3         111  
17              
18 3     3   920 use WWW::FCM::HTTP::Response;
  3         6  
  3         1704  
19              
20             our $API_URL = 'https://fcm.googleapis.com/fcm/send';
21              
22             sub new {
23 13     13 1 58055 my $class = shift;
24 13 50       64 my %args = ref @_ eq 'HASH' ? %{ @_ } : @_;
  0         0  
25 13 100       186 croak 'Usage: WWW::FCM::HTTP->new(api_key => $api_key)' unless exists $args{api_key};
26              
27 12   66     70 $args{api_url} ||= $API_URL;
28 12   66     187 $args{ua} ||= LWP::UserAgent->new(
29             agent => __PACKAGE__.'/'.$VERSION,
30             conn_cache => LWP::ConnCache->new,
31             );
32              
33 12         7477 bless { %args }, $class;
34             }
35              
36             sub send {
37 10     10 1 40377 my ($self, $payload) = @_;
38 10 100       406 croak 'Usage: $fcm->send(\%payload)' unless ref $payload eq 'HASH';
39              
40 6         76 my $res = $self->ua->request($self->build_request($payload));
41 6         154286 WWW::FCM::HTTP::Response->new($res, $payload->{registration_ids});
42             }
43              
44             sub build_request {
45 6     6 0 134 my ($self, $payload) = @_;
46 6 50       33 croak 'Usage: $gcm->build_request(\%payload)' unless ref $payload eq 'HASH';
47              
48 6         53 my $req = HTTP::Request->new(POST => $self->api_url);
49 6         1467 $req->header(Authorization => 'key='.$self->api_key);
50 6         1051 $req->header('Content-Type' => 'application/json; charset=UTF-8');
51 6         498 $req->content(encode_json $payload);
52              
53 6         347 return $req;
54             }
55              
56             1;
57             __END__