GoogleAnalytics.pm

filter: Statementstmt 90.7% 156 / 172 Branchbran 73.3% 44 / 60 Conditioncond 55.8% 38 / 68 MC/DCmcdc 26.3% 10 / 38 Subroutinesub 77.1% 27 / 35 Podpod 100% 9 / 9 totaltotal 74.3% 284 / 382 CC 63 SCAR 21.2
CC
63
Cov
79%
_query_translator
19.8
_process_batch_get_response
12.4
from_file
12.0
CRAP 8.3
« GoogleAnalytics/Report.pm ↑ Summary
1 package Mojo::GoogleAnalytics;
2 5 ▶use Mojo::Base -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 5 ▶use Mojo::Collection;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use Mojo::File 'path';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use Mojo::GoogleAnalytics::Report;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use Mojo::JSON qw(decode_json false true);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Mojo::JWT;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Mojo::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 5 ▶use constant DEBUG => $ENV{MOJO_GA_DEBUG} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'MOJO_GA_DEBUG'} || 0
l!l
05
MC/DC0%0/1
$ENV{'MOJO_GA_DEBUG'} || 0
$ENV{'MOJO_GA_DEBUG'}
Truth table50%1/2
A
A= $ENV{'MOJO_GA_DEBUG'}
Aresult
11
00
13  
14 5 our $VERSION = '0.04';
15  
16 5 our %QUERY_SORT_ORDER = (asc => 'ASCENDING', desc => 'DESCENDING', x => 'SORT_ORDER_UNSPECIFIED');
17  
18 5 our %QUERY_TRANSLATOR = (
19 'eq' => [qw(dimension EXACT)],
20 '^' => [qw(dimension BEGINS_WITH)],
21 '$' => [qw(dimension ENDS_WITH)],
22 '=~' => [qw(dimension REGEXP)],
23 'substr' => [qw(dimension PARTIAL)],
24 '==' => [qw(metric EQUAL)],
25 '>' => [qw(metric GREATER_THAN)],
26 '<' => [qw(metric LESS_THAN)],
27 );
28  
29 1 ▶has authorization => sub { +{} };
Subroutine __ANON__: called CC=1 SCAR=0.0
30 0 ▶has client_email => sub { Carp::confess('client_email is required') };
Subroutine __ANON__: not called CC=1 SCAR=1.2
31 0 ▶has client_id => sub { Carp::confess('client_id is required') };
Subroutine __ANON__: not called CC=1 SCAR=1.2
32 0 ▶has private_key => sub { Carp::confess('private_key is required') };
Subroutine __ANON__: not called CC=1 SCAR=1.2
33 1 ▶has ua => sub { Mojo::UserAgent->new(max_redirects => 3) };
Subroutine __ANON__: called CC=1 SCAR=0.0
34 5 has view_id => '';
35  
36 2 ▶sub authorize {
Subroutine authorize: called CC=4 SCAR=14.8
Pod documented
37 2 my ($self, $cb) = @_;
38 2 ▶ my @ua_args = $self->_authorize_ua_args or return $self;
Branch: 1 branch
BranchTrueFalseTotal
my(@ua_args) = $self->_authorize_ua_args or return $self 1 1 2
39  
40 1 ▶ if ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 0 1 1
41 0 ▶ $self->ua->post(@ua_args, sub { $self->$cb($self->_process_authorize_response($_[1])) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
42 }
43 else {
44 1 my ($err, $res) = $self->_process_authorize_response($self->ua->post(@ua_args));
45 1 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 1 1
46 }
47  
48 1 return $self;
49 }
50  
51 2 ▶sub authorize_p {
Subroutine authorize_p: called CC=2 SCAR=7.0
Pod documented
52 2 my $self = shift;
53  
54 2 ▶ return Mojo::Promise->new->resolve unless my @ua_args = $self->_authorize_ua_args;
Branch: 1 branch
BranchTrueFalseTotal
unless my(@ua_args) = $self->_authorize_ua_args 1 1 2
55 1 ▶ return $self->ua->post_p(@ua_args)->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
56 1 my $err = $self->_process_authorize_response($_[0]);
57 1 ▶ return $err ? Mojo::Promise->new->reject($err) : ();
Branch: 1 branch
BranchTrueFalseTotal
$err ? : 1 0 1
58 1 });
59 }
60  
61 3 ▶sub batch_get {
Subroutine batch_get: called CC=5 SCAR=16.5
Pod documented
62 3 my ($self, $query, $cb) = @_;
63 3 my @ua_args;
64  
65 3 ▶ @ua_args = (Mojo::URL->new($self->{batch_get_uri}), {},
Branch: 1 branch
BranchTrueFalseTotal
ref $query eq 'ARRAY' ? : 0 3 3
66 json => {reportRequests => ref $query eq 'ARRAY' ? $query : [$query]});
67  
68 3 ▶ if ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 1 2 3
69 1 ▶ my $p = $self->authorize_p->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
70 1 warn "[GoogleAnalytics] Getting analytics data from $ua_args[0] ...\n", if DEBUG;
71 1 $ua_args[1] = {Authorization => $self->authorization->{header}};
72 1 return $self->ua->post_p(@ua_args);
73 1 ▶ })->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
74 1 my $res = $self->_process_batch_get_response($query, shift);
75 1 ▶ return ref $cb ? $self->$cb('', $res) : $res;
Branch: 1 branch
BranchTrueFalseTotal
ref $cb ? : 0 1 1
76 0 ▶ })->catch(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
77 0 ▶ return ref $cb ? $self->$cb(shift, {}) : shift;
Branch: 1 branch
BranchTrueFalseTotal
ref $cb ? : 0 0 0
78 1 });
79  
80 1 ▶ return ref $cb ? $self : $p;
Branch: 1 branch
BranchTrueFalseTotal
ref $cb ? : 0 1 1
81 }
82 else {
83 2 $ua_args[1] = {Authorization => $self->authorize->authorization->{header}};
84 2 warn "[GoogleAnalytics] Getting analytics data from $ua_args[0] ...\n", if DEBUG;
85 2 my ($err, $res) = $self->_process_batch_get_response($query, $self->ua->post(@ua_args));
86 2 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 1 1 2
87 1 return $res;
88 }
89 }
90  
91 1 ▶sub batch_get_p {
Subroutine batch_get_p: called CC=1 SCAR=0.0
Pod documented
92 1 shift->batch_get(shift, 1);
93 }
94  
95 0 ▶sub from_file {
Subroutine from_file: not called CC=3 SCAR=24.8
Pod documented
96 0 my ($self, $file) = @_;
97 0 my $attrs = decode_json(path($file)->slurp);
98  
99 0 for my $attr (keys %$attrs) {
100 0 ▶ $self->{$attr} ||= $attrs->{$attr};
Condition0%0/3
$self->{$attr} ||= $attrs->{$attr}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{$attr} ||= $attrs->{$attr}
$self->{$attr} $attrs->{$attr}
Truth table0%0/3
A ||= B
A= $self->{$attr}B= $attrs->{$attr}
ABresult
1X1
011
000
101 0 warn qq([Mojo::GoogleAnalytics] Read "$attr" from $file\n) if DEBUG;
102 }
103  
104 0 return $self;
105 }
106  
107 0 ▶sub get_report {
Subroutine get_report: not called CC=1 SCAR=6.9
Pod documented
108 0 my ($self, $query, $cb) = @_;
109 0 return $self->batch_get($self->_query_translator(%$query), $cb);
110 }
111  
112 0 ▶sub get_report_p {
Subroutine get_report_p: not called CC=1 SCAR=6.9
Pod documented
113 0 my ($self, $query) = @_;
114 0 $self->batch_get_p($self->_query_translator(%$query));
115 }
116  
117 2 ▶sub new {
Subroutine new: called CC=7 SCAR=20.4
Pod documented
118 2 my $class = shift;
119 2 ▶ my $file = @_ % 2 ? shift : undef;
Branch: 1 branch
BranchTrueFalseTotal
@_ % 2 ? : 0 2 2
120 2 my $self = $class->SUPER::new(@_);
121  
122 2 ▶ $self->from_file($file) if $file;
Branch: 1 branch
BranchTrueFalseTotal
if $file 0 2 2
123 2 ▶ $self->{token_uri} ||= 'https://accounts.google.com/o/oauth2/token';
Condition50%1/2
$self->{"token_uri"} ||= "https://accounts.google.com/o/oauth2/token"
l!l
02
MC/DC0%0/1
$self->{"token_uri"} ||= "https://accounts.google.com/o/oauth2/token"
$self->{"token_uri"}
Truth table50%1/2
A
A= $self->{"token_uri"}
Aresult
11
00
124 2 ▶ $self->{auth_scope} ||= 'https://www.googleapis.com/auth/analytics.readonly';
Condition50%1/2
$self->{"auth_scope"} ||= "https://www.googleapis.com/auth/analytics.readonly"
l!l
02
MC/DC0%0/1
$self->{"auth_scope"} ||= "https://www.googleapis.com/auth/analytics.readonly"
$self->{"auth_scope"}
Truth table50%1/2
A
A= $self->{"auth_scope"}
Aresult
11
00
125 2 ▶ $self->{batch_get_uri} ||= 'https://analyticsreporting.googleapis.com/v4/reports:batchGet';
Condition50%1/2
$self->{"batch_get_uri"} ||= "https://analyticsreporting.googleapis.com/v4/reports:batchGet"
l!l
02
MC/DC0%0/1
$self->{"batch_get_uri"} ||= "https://analyticsreporting.googleapis.com/v4/reports:batchGet"
$self->{"batch_get_uri"}
Truth table50%1/2
A
A= $self->{"batch_get_uri"}
Aresult
11
00
126 2 ▶ $self->mock if $ENV{TEST_MOJO_GA_BATCH_GET_DIR};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"TEST_MOJO_GA_BATCH_GET_DIR"} 1 1 2
127  
128 2 return $self;
129 }
130  
131 1 ▶sub mock {
Subroutine mock: called CC=7 SCAR=21.3
Pod documented
132 1 my ($self, $args) = @_;
133 1 ▶ $self->{batch_get_dir} = $args->{batch_get_dir} // $ENV{TEST_MOJO_GA_BATCH_GET_DIR} // File::Spec->tmpdir;
Condition33%2/6
($args->{"batch_get_dir"} // $ENV{"TEST_MOJO_GA_BATCH_GET_DIR"}) // "File::Spec"->tmpdir
l!l&&r!l&&!r
100
$args->{"batch_get_dir"} // $ENV{"TEST_MOJO_GA_BATCH_GET_DIR"}
l!l&&r!l&&!r
010
MC/DC0%0/3
($args->{"batch_get_dir"} // $ENV{"TEST_MOJO_GA_BATCH_GET_DIR"}) // "File::Spec"->tmpdir
$args->{"batch_get_dir"} $ENV{"TEST_MOJO_GA_BATCH_GET_DIR"} "File::Spec"->tmpdir
Truth table25%1/4
A // B // C
A= $args->{"batch_get_dir"}B= $ENV{"TEST_MOJO_GA_BATCH_GET_DIR"}C= "File::Spec"->tmpdir
ABCresult
1XX1
01X1
0011
0000
134  
135 1 require Mojolicious;
136 1 my $server = $self->ua->server;
137 1 ▶ $server->app(Mojolicious->new) unless $server->app;
Branch: 1 branch
BranchTrueFalseTotal
unless $server->app 1 0 1
138  
139 1 my $mock_r = $server->app->routes;
140 1 Scalar::Util::weaken($self);
141 1 for my $name (qw(batch_get_uri token_uri)) {
142 2 my $cb = $self->can("_mocked_action_$name");
143 2 $self->{$name} = sprintf '/mocked/ga%s', Mojo::URL->new($self->{$name})->path;
144 2 ▶ $mock_r->any($self->{$name} => $args->{$name} || sub { $self->$cb(@_) })->name($name) unless $mock_r->lookup($name);
Subroutine __ANON__: called CC=1 SCAR=0.8
Branch: 1 branch
BranchTrueFalseTotal
unless $mock_r->lookup($name) 2 0 2
Condition33%1/3
$args->{$name} || sub { $self->$cb(@_); }
l!l&&r!l&&!r
020
MC/DC0%0/2
$args->{$name} || sub { $self->$cb(@_); }
$args->{$name} sub { $self->$cb(@_); }
Truth table33%1/3
A || B
A= $args->{$name}B= sub { $self->$cb(@_); }
ABresult
1X1
011
000
145 }
146  
147 1 return $self;
148 }
149  
150 4 ▶sub _authorize_ua_args {
Subroutine _authorize_ua_args: called CC=3 SCAR=11.0
151 4 my $self = shift;
152 4 my $time = time;
153 4 my $prev = $self->authorization;
154 4 my ($jwt, @ua_args);
155  
156 4 warn "[GoogleAnalytics] Authorization exp: @{[$prev->{exp} ? $prev->{exp} : -1]} < $time\n" if DEBUG;
157 4 ▶ return if $prev->{exp} and $time < $prev->{exp};
Branch: 1 branch
BranchTrueFalseTotal
if $prev->{"exp"} and $time < $prev->{"exp"} 2 2 4
Condition66%2/3
$prev->{"exp"} and $time < $prev->{"exp"}
!ll&&!rl&&r
202
MC/DC50%1/2
$prev->{"exp"} and $time < $prev->{"exp"}
$prev->{"exp"} $time < $prev->{"exp"}
Truth table66%2/3
A and B
A= $prev->{"exp"}B= $time < $prev->{"exp"}
ABresult
0X0
100
111
158  
159 2 $ua_args[0] = Mojo::URL->new($self->{token_uri});
160 2 $jwt = Mojo::JWT->new->algorithm('RS256')->secret($self->private_key);
161  
162 $jwt->claims({
163 aud => $ua_args[0]->to_string,
164 exp => $time + 3600,
165 iat => $time,
166 iss => $self->client_email,
167 scope => $self->{auth_scope},
168 2 });
169  
170 2 push @ua_args, (form => {grant_type => 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion => $jwt->encode});
171 2 warn "[GoogleAnalytics] Authenticating with $ua_args[0] ...\n", if DEBUG;
172  
173 2 return @ua_args;
174 }
175  
176 3 ▶sub _mocked_action_batch_get_uri {
Subroutine _mocked_action_batch_get_uri: called CC=2 SCAR=6.9
177 3 my ($self, $c) = @_;
178 3 my $file = Mojo::File::path($self->{batch_get_dir}, sprintf '%s.json', Mojo::Util::md5_sum($c->req->text));
179  
180 3 warn "[GoogleAnalytics] Reading dummy response file $file (@{[-r $file ? 1 : 0]})\n" if DEBUG;
181 3 ▶ return $c->render(data => $file->slurp) if -r $file;
Branch: 1 branch
BranchTrueFalseTotal
if -r $file 2 1 3
182 1 return $c->render(json => {error => {message => qq(Could not read dummy response file "$file".)}}, status => 500);
183 }
184  
185 1 ▶sub _mocked_action_token_uri {
Subroutine _mocked_action_token_uri: called CC=1 SCAR=0.0
186 1 my ($self, $c) = @_;
187 1 $c->render(json => {access_token => 'some-dummy-token', expires_in => 3600, token_type => 'Bearer'});
188 }
189  
190 2 ▶sub _process_authorize_response {
Subroutine _process_authorize_response: called CC=6 SCAR=18.3
191 2 my ($self, $tx) = @_;
192 2 my $err = $tx->error;
193 2 my $res = $tx->res->json;
194 2 my $url = $tx->req->url;
195  
196 2 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) { } 1 1 2
197 $err = sprintf '%s >>> %s (%s)', $url, $res->{error_description} || $err->{message} || 'Unknown error',
198 1 ▶ $err->{code} || 0;
Condition42%3/7
$res->{'error_description'} || $err->{'message'} || 'Unknown error'
l!l
10
$res->{"error_description"} or $err->{"message"}
l!l&&r!l&&!r
010
$err->{'code'} || 0
l!l
10
MC/DC0%0/2
$res->{'error_description'} || $err->{'message'} || 'Unknown error'
$res->{"error_description"} $err->{"message"}
MC/DC0%0/1
$err->{'code'} || 0
$err->{'code'}
Truth table33%1/3
A or B
A= $res->{"error_description"}B= $err->{"message"}
ABresult
1X1
011
000
Truth table50%1/2
A
A= $err->{'code'}
Aresult
11
00
199 1 warn "[GoogleAnalytics] $err\n", if DEBUG;
200 }
201 else {
202 1 warn "[GoogleAnalytics] Authenticated with $url\n", if DEBUG;
203 $self->authorization(
204 1 {exp => time + ($res->{expires_in} - 600), header => "$res->{token_type} $res->{access_token}"});
205 }
206  
207 2 ▶ return $err // '';
Condition100%2/2
$err // ""
l!l
11
MC/DC100%1/1
$err // ""
$err
Truth table100%2/2
A
A= $err
Aresult
11
00
208 }
209  
210 3 ▶sub _process_batch_get_response {
Subroutine _process_batch_get_response: called CC=11 SCAR=25.2
211 3 my ($self, $query, $tx) = @_;
212 3 my $as_list = ref $query eq 'ARRAY';
213 3 my $url = $tx->req->url;
214 3 ▶ my $res = $tx->res->json || {};
Condition50%1/2
$tx->res->json || {}
l!l
30
MC/DC0%0/1
$tx->res->json || {}
$tx->res->json
Truth table50%1/2
A
A= $tx->res->json
Aresult
11
00
215 3 ▶ my $err = $res->{error} || $tx->error;
Condition66%2/3
$res->{'error'} || $tx->error
l!l&&r!l&&!r
102
MC/DC50%1/2
$res->{'error'} || $tx->error
$res->{'error'} $tx->error
Truth table66%2/3
A || B
A= $res->{'error'}B= $tx->error
ABresult
1X1
011
000
216 3 ▶ my $reports = $res->{reports} || ($as_list ? $query : [{}]);
Branch: 1 branch
BranchTrueFalseTotal
$as_list ? : 0 1 1
Condition66%2/3
$res->{'reports'} || ($as_list ? $query : [{}])
l!l&&r!l&&!r
210
MC/DC0%0/2
$res->{'reports'} || ($as_list ? $query : [{}])
$res->{'reports'} ($as_list ? $query : [{}])
Truth table66%2/3
A || B
A= $res->{'reports'}B= ($as_list ? $query : [{}])
ABresult
1X1
011
000
217  
218 @$reports = map {
219 3 $_->{error} = $err;
220 3 ▶ $_->{query} = $as_list ? shift @$query : $query, $_->{tx} = $tx;
Branch: 1 branch
BranchTrueFalseTotal
$as_list ? : 0 3 3
221 3 Mojo::GoogleAnalytics::Report->new($_);
222 } @$reports;
223  
224 3 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 1 2 3
225 1 ▶ $err = sprintf '%s >>> %s (%s)', $url, $err->{message} || 'Unknown error', $err->{code} || 0;
Condition50%2/4
$err->{'message'} || 'Unknown error'
l!l
10
$err->{'code'} || 0
l!l
01
MC/DC0%0/1
$err->{'message'} || 'Unknown error'
$err->{'message'}
MC/DC0%0/1
$err->{'code'} || 0
$err->{'code'}
Truth table50%1/2
A
A= $err->{'message'}
Aresult
11
00
Truth table50%1/2
A
A= $err->{'code'}
Aresult
11
00
226 }
227  
228 3 ▶ return $err || '', $as_list ? Mojo::Collection->new(@$reports) : $reports->[0];
Branch: 1 branch
BranchTrueFalseTotal
$as_list ? : 0 3 3
Condition100%2/2
$err || ''
l!l
12
MC/DC100%1/1
$err || ''
$err
Truth table100%2/2
A
A= $err
Aresult
11
00
229 }
230  
231 6 ▶sub _query_translator {
Subroutine _query_translator: called CC=19 SCAR=29.9
232 6 my ($self, %query) = @_;
233  
234 6 ▶ for my $filter (@{delete($query{filters}) || []}) {
Condition100%2/2
delete $query{'filters'} || []
l!l
15
MC/DC100%1/1
delete $query{'filters'} || []
delete $query{'filters'}
Truth table100%2/2
A
A= delete $query{'filters'}
Aresult
11
00
235 8 my ($not, $op) = $filter->[1] =~ /^(\!)?(.*)$/;
236 8 ▶ my $group_op = $QUERY_TRANSLATOR{$op} || [dimension => $op];
Condition50%1/2
$Mojo::GoogleAnalytics::QUERY_TRANSLATOR{$op} || ['dimension', $op]
l!l
80
MC/DC0%0/1
$Mojo::GoogleAnalytics::QUERY_TRANSLATOR{$op} || ['dimension', $op]
$Mojo::GoogleAnalytics::QUERY_TRANSLATOR{$op}
Truth table50%1/2
A
A= $Mojo::GoogleAnalytics::QUERY_TRANSLATOR{$op}
Aresult
11
00
237  
238 8 ▶ if ($group_op->[0] eq 'metric') {
Branch: 1 branch
BranchTrueFalseTotal
if ($group_op->[0] eq 'metric') { } 3 5 8
239 3 ▶ push @{$query{metricFilterClauses}[0]{filters}},
Branch: 1 branch
BranchTrueFalseTotal
$not ? : 0 3 3
240 {
241 metricName => $filter->[0],
242 not => $not ? true : false,
243 operator => $group_op->[1],
244 comparisonValue => "$filter->[2]",
245 };
246 }
247 else {
248 5 ▶ push @{$query{dimensionFilterClauses}[0]{filters}},
Branch: 1 branch
BranchTrueFalseTotal
$not ? : 1 4 5
249 {
250 dimensionName => $filter->[0],
251 not => $not ? true : false,
252 operator => $group_op->[1],
253 expressions => $filter->[2],
254 };
255 }
256 }
257  
258 6 ▶ for my $order_by (@{delete($query{order_by}) || []}) {
Condition100%2/2
delete $query{'order_by'} || []
l!l
15
MC/DC100%1/1
delete $query{'order_by'} || []
delete $query{'order_by'}
Truth table100%2/2
A
A= delete $query{'order_by'}
Aresult
11
00
259 3 my ($field, $order) = $order_by =~ /^(\S+)\s*(asc|desc)?$/;
260 3 ▶ $order = $QUERY_SORT_ORDER{$order || 'x'} || $QUERY_SORT_ORDER{x};
Condition60%3/5
$Mojo::GoogleAnalytics::QUERY_SORT_ORDER{$order or 'x'} || $Mojo::GoogleAnalytics::QUERY_SORT_ORDER{'x'}
l!l&&r!l&&!r
300
$order || 'x'
l!l
21
MC/DC0%0/2
$Mojo::GoogleAnalytics::QUERY_SORT_ORDER{$order or 'x'} || $Mojo::GoogleAnalytics::QUERY_SORT_ORDER{'x'}
$Mojo::GoogleAnalytics::QUERY_SORT_ORDER{$order or 'x'} $Mojo::GoogleAnalytics::QUERY_SORT_ORDER{'x'}
MC/DC100%1/1
$order || 'x'
$order
Truth table33%1/3
A || B
A= $Mojo::GoogleAnalytics::QUERY_SORT_ORDER{$order or 'x'}B= $Mojo::GoogleAnalytics::QUERY_SORT_ORDER{'x'}
ABresult
1X1
011
000
Truth table100%2/2
A
A= $order
Aresult
11
00
261 3 push @{$query{orderBys}}, {fieldName => $1, sortOrder => $order};
262 }
263  
264 6 ▶ if (my $d = delete $query{interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $d = delete $query{"interval"}) 2 4 6
265 2 ▶ $query{dateRanges} = [{startDate => $d->[0], endDate => $d->[1] || '1daysAgo'}];
Condition100%2/2
$d->[1] || '1daysAgo'
l!l
11
MC/DC100%1/1
$d->[1] || '1daysAgo'
$d->[1]
Truth table100%2/2
A
A= $d->[1]
Aresult
11
00
266 }
267  
268 3 $query{dimensions} = [map { +{name => $_} } split /,/, $query{dimensions}]
269 6 ▶ if $query{dimensions} and not ref $query{dimensions};
Branch: 1 branch
BranchTrueFalseTotal
if $query{"dimensions"} and not ref $query{"dimensions"} 1 5 6
Condition66%2/3
$query{"dimensions"} and not ref $query{"dimensions"}
!ll&&!rl&&r
501
MC/DC50%1/2
$query{"dimensions"} and not ref $query{"dimensions"}
$query{"dimensions"} not ref $query{"dimensions"}
Truth table66%2/3
A and not(B)
A= $query{"dimensions"}B= not ref $query{"dimensions"}
ABresult
0X0
100
111
270 3 $query{metrics} = [map { +{expression => $_} } split /,/, $query{metrics}]
271 6 ▶ if $query{metrics} and not ref $query{metrics};
Branch: 1 branch
BranchTrueFalseTotal
if $query{"metrics"} and not ref $query{"metrics"} 1 5 6
Condition66%2/3
$query{"metrics"} and not ref $query{"metrics"}
!ll&&!rl&&r
501
MC/DC50%1/2
$query{"metrics"} and not ref $query{"metrics"}
$query{"metrics"} not ref $query{"metrics"}
Truth table66%2/3
A and not(B)
A= $query{"metrics"}B= not ref $query{"metrics"}
ABresult
0X0
100
111
272 6 ▶ $query{pageSize} = delete $query{rows} if exists $query{rows};
Branch: 1 branch
BranchTrueFalseTotal
if exists $query{"rows"} 1 5 6
273 6 ▶ $query{viewId} ||= $self->view_id;
Condition33%1/3
$query{"viewId"} ||= $self->view_id
l!l&&r!l&&!r
060
MC/DC0%0/2
$query{"viewId"} ||= $self->view_id
$query{"viewId"} $self->view_id
Truth table33%1/3
A ||= B
A= $query{"viewId"}B= $self->view_id
ABresult
1X1
011
000
274  
275 6 return \%query;
276 }
277  
278 5 1;
279  
280 =encoding utf8
281  
282 =head1 NAME
283  
284 Mojo::GoogleAnalytics - Extract data from Google Analytics using Mojo UserAgent
285  
286 =head1 SYNOPSIS
287  
288 my $ga = Mojo::GoogleAnalytics->new("/path/to/credentials.json");
289 my $report = $ga->batch_get({
290 viewId => "ga:123456789",
291 dateRanges => [{startDate => "7daysAgo", endDate => "1daysAgo"}],
292 dimensions => [{name => "ga:country"}, {name => "ga:browser"}],
293 metrics => [{expression => "ga:pageviews"}, {expression => "ga:sessions"}],
294 orderBys => [{fieldName => "ga:pageviews", sortOrder => "DESCENDING"}],
295 pageSize => 10,
296 });
297  
298 print $report->rows_to_table(as => "text");
299  
300 =head1 DESCRIPTION
301  
302 L<Mojo::GoogleAnalytics> is a Google Analytics client which allow you to
303 extract data non-blocking.
304  
305 This module is work in progress and currently EXPERIMENTAL. Let me know if you
306 start using it or has any feedback regarding the API.
307  
308 =head1 ATTRIBUTES
309  
310 =head2 authorization
311  
312 $hash_ref = $self->authorization;
313  
314 Holds authorization data, extracted by L</authorize>. This can be useful to set
315 from a cache if L<Mojo::GoogleAnalytics> objects are created and destroyed
316 frequently, but with the same credentials.
317  
318 =head2 client_email
319  
320 $str = $self->client_email;
321  
322 Example: "some-app@some-project.iam.gserviceaccount.com".
323  
324 =head2 client_id
325  
326 $str = $self->client_id;
327  
328 Example: "103742165385019792511".
329  
330 =head2 private_key
331  
332 $str = $self->private_key;
333  
334 Holds the content of a pem file that looks like this:
335  
336 -----BEGIN PRIVATE KEY-----
337 ...
338 ...
339 -----END PRIVATE KEY-----
340  
341 =head2 ua
342  
343 $ua = $self->ua;
344 $self = $self->ua(Mojo::UserAgent->new);
345  
346 Holds a L<Mojo::UserAgent> object.
347  
348 =head2 view_id
349  
350 $str = $self->view_id;
351 $self = $self->view_id("ga:123456789");
352  
353 Default C<viewId>, used by L</get_report>.
354  
355 =head1 METHODS
356  
357 =head2 authorize
358  
359 $self = $self->authorize;
360 $self = $self->authorize(sub { my ($self, $err) = @_; });
361  
362 This method will set L</authorization>. Note that this method is automatically
363 called from inside of L</batch_get>, unless already authorized.
364  
365 =head2 authorize_p
366  
367 $promise = $self->authorize_p;
368  
369 Same as L</authorize>, but returns a L<Mojo::Promise>.
370  
371 =head2 batch_get
372  
373 $report = $self->batch_get(\%query);
374 $self = $self->batch_get(\%query, sub { my ($self, $err, $report) = @_ });
375  
376 Used to extract data from Google Analytics. C<$report> will be a
377 L<Mojo::Collection> if C<$query> is an array ref, and a single
378 L<Mojo::GoogleAnalytics::Report> object if C<$query> is a hash.
379  
380 C<$err> is a string on error and false value on success.
381  
382 =head2 batch_get_p
383  
384 $promise = $self->batch_get_p(\%query);
385  
386 Same as L</batch_get>, but returns a L<Mojo::Promise>.
387  
388 =head2 from_file
389  
390 $self = $self->from_file("/path/to/credentials.json");
391  
392 Used to load attributes from a JSON credentials file, generated from
393 L<https://console.developers.google.com/apis/credentials>. Example file:
394  
395 {
396 "type": "service_account",
397 "project_id": "cool-project-238176",
398 "private_key_id": "01234abc6780dc2a3284851423099daaad8cff92",
399 "private_key": "-----BEGIN PRIVATE KEY-----...\n-----END PRIVATE KEY-----\n",
400 "client_email": "some-name@cool-project-238176.iam.gserviceaccount.com",
401 "client_id": "103742165385019792511",
402 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
403 "token_uri": "https://accounts.google.com/o/oauth2/token",
404 }
405  
406 Note: The JSON credentials file will probably contain more fields than is
407 listed above.
408  
409 =head2 get_report
410  
411 $report = $self->get_report(\%query);
412 $self = $self->get_report(\%query, sub { my ($self, $err, $report) = @_ });
413  
414 This method is the same as L</batch_get>, but will do some translations on the
415 input queries before passing it on to L</batch_get>. Example:
416  
417 $self->get_report({
418 dimensions => "ga:productName",
419 metrics => "ga:productListClicks,ga:productListViews",
420 interval => [qw(7daysAgo 1daysAgo)],
421 order_by => ["ga:productListClicks desc"],
422 filters => [ ["ga:currencyCode" => "eq" => ["USD"]] ],
423 });
424  
425 =over 2
426  
427 =item * dimensions
428  
429 C<dimensions> will be translated from a comma separated string, or passed on
430 directly to Google Analytics if not. The example above results in this query:
431  
432 dimensions => [{name => "ga:productName"}]
433  
434 =item * filters
435  
436 C<filters> is a simpler version of C<dimensionFilterClauses> and
437 C<metricFilterClauses>. The format is:
438  
439 filters => [ [$fieldName, $operator, $value] ]
440  
441 The C<$operator> will be used to determine if the expression should go into
442 C<dimensionFilterClauses> or C<metricFilterClauses>.
443  
444 Input operator | Filter group | Analytics operator
445 ---------------|-----------------------|----------------------
446 eq | dimensionFilterClause | EXACT
447 ^ | dimensionFilterClause | BEGINS_WITH
448 $ | dimensionFilterClause | ENDS_WITH
449 =~ | dimensionFilterClause | REGEXP
450 substr | dimensionFilterClause | PARTIAL
451 == | metricFilterClause | EQUAL
452 > | metricFilterClause | GREATER_THAN
453 < | metricFilterClause | LESS_THAN
454  
455 The filter will be "NOT" if the operator is prefixed with "!".
456  
457 =item * interval
458  
459 C<interval> can be used as a simpler version of C<dateRanges>. The example above
460 results in:
461  
462 dateRanges => [{startDate => "7daysAgo", endDate => "1daysAgo"}]
463  
464 Note that C<endDate> will default to "1daysAgo" if not present.
465  
466 =item * metrics
467  
468 C<metrics> will be translated from a comma separated string, or passed on
469 directly to Google Analytics if not. The example above results in this query:
470  
471 metrics => [{name => "ga:productListClicks"}, {name => "ga:productListViews"}]
472  
473 =item * order_by
474  
475 C<order_by> can be used as a simpler version to C<orderBys>. The example above
476 results in:
477  
478 orderBys => [{fieldName => "ga:productListClicks", sortOrder => "DESCENDING'}]
479  
480 The sort order can be "asc" or "desc". Will result in "SORT_ORDER_UNSPECIFIED"
481 unless present.
482  
483 =item * rows
484  
485 Alias for C<pageSize>.
486  
487 =item * viewId
488  
489 C<viewId> will be set from L</view_id> if not present in the query.
490  
491 =back
492  
493 =head2 get_report_p
494  
495 $promise = $selfg->get_report_p(\%query);
496  
497 Same as L</get_report>, but returns a L<Mojo::Promise>.
498  
499 =head2 new
500  
501 $self = Mojo::GoogleAnalytics->new(%attrs);
502 $self = Mojo::GoogleAnalytics->new(\%attrs);
503 $self = Mojo::GoogleAnalytics->new("/path/to/credentials.json");
504  
505 Used to construct a new L<Mojo::GoogleAnalytics> object. Calling C<new()> with
506 a single argument will cause L</from_file> to be called with that argument.
507  
508 =head2 mock
509  
510 $self = $self->mock;
511 $self = $self->mock({batch_get_dir => "/path/to/some/dir"});
512 $self = $self->mock({batch_get_uri => sub { my ($self, $c) = @_; }, token_uri => sub { my ($self, $c) = @_; }});
513  
514 This method is useful when you want to test your application, but you don't
515 want to ask Google for reports. C<mock()> will be automatically called by
516 L</new> if the C<TEST_MOJO_GA_BATCH_GET_DIR> environment variable i set. The
517 arguments passed on to this method can be:
518  
519 =over 2
520  
521 =item * batch_get_dir
522  
523 Need to be an absolute path to a directory with the dummy response files for
524 L</batch_get>.
525  
526 Defaults to C<TEST_MOJO_GA_BATCH_GET_DIR> environment variable.
527  
528 =item * batch_get_uri
529  
530 A code ref that is used as an L<Mojolicious> action. The default code ref
531 provided by this module will look for a response file in C<batch_get_dir> with
532 the name C<$md5_sum.json>, where the MD5 sum is calculated from the JSON
533 request body. It will respond with an error message with the full path of the
534 expected file, unless the file could be read.
535  
536 =item * token_uri
537  
538 A code ref that is used as an L<Mojolicious> action. The default code ref will
539 respond with a dummy bearer token and log you in.
540  
541 =back
542  
543 =head1 AUTHOR
544  
545 Jan Henning Thorsen
546  
547 =head1 COPYRIGHT AND LICENSE
548  
549 This program is free software, you can redistribute it and/or modify it under
550 the terms of the Artistic License version 2.0.
551  
552 =cut
« GoogleAnalytics/Report.pm ↑ Summary