File Coverage

blib/lib/WWW/Google/PageSpeedOnline.pm
Criterion Covered Total %
statement 44 90 48.8
branch 1 10 10.0
condition 1 5 20.0
subroutine 15 19 78.9
pod 1 1 100.0
total 62 125 49.6


line stmt bran cond sub pod time code
1             package WWW::Google::PageSpeedOnline;
2              
3             $WWW::Google::PageSpeedOnline::VERSION = '0.28';
4             $WWW::Google::PageSpeedOnline::AUTHORITY = 'cpan:MANWAR';
5              
6             =head1 NAME
7              
8             WWW::Google::PageSpeedOnline - Interface to Google Page Speed Online API.
9              
10             =head1 VERSION
11              
12             Version 0.28
13              
14             =cut
15              
16 4     4   66688 use 5.006;
  4         28  
17 4     4   2495 use JSON;
  4         48197  
  4         19  
18 4     4   3041 use Data::Dumper;
  4         30137  
  4         271  
19              
20 4     4   1806 use WWW::Google::UserAgent;
  4         462981  
  4         190  
21 4     4   2427 use WWW::Google::UserAgent::DataTypes -all;
  4         626467  
  4         66  
22 4     4   75820 use WWW::Google::PageSpeedOnline::Params qw(validate $FIELDS);
  4         10  
  4         604  
23 4     4   1769 use WWW::Google::PageSpeedOnline::Stats;
  4         13  
  4         133  
24 4     4   1861 use WWW::Google::PageSpeedOnline::Advise;
  4         14  
  4         138  
25 4     4   1813 use WWW::Google::PageSpeedOnline::Result;
  4         18  
  4         135  
26 4     4   1886 use WWW::Google::PageSpeedOnline::Result::Rule;
  4         24  
  4         121  
27              
28 4     4   27 use Moo;
  4         8  
  4         15  
29 4     4   2141 use namespace::autoclean;
  4         8  
  4         18  
30             extends 'WWW::Google::UserAgent';
31              
32             has prettyprint => (is => 'ro', isa => TrueFalse, default => sub { 'true' });
33             has strategy => (is => 'ro', isa => Strategy, default => sub { 'desktop' });
34             has locale => (is => 'ro', isa => Locale, default => sub { 'en_US' });
35             has [ qw(stats result advise) ] => (is => 'rw');
36              
37             our $BASE_URL = 'https://www.googleapis.com/pagespeedonline/v2/runPagespeed';
38              
39             =head1 DESCRIPTION
40              
41             Google Page Speed is a tool that helps developers optimize their web pages by
42             analyzing the pages and generating tailored suggestions to make the pages faster.
43             You can use the Page Speed Online API to programmatically generate Page Speed
44             scores and suggestions. Currently it supports version v2. Courtesy limit is 250
45             queries per day.
46              
47             IMPORTANT: The version v1 of the Google Page Speed Online API is in Labs and its
48             features might change unexpectedly until it graduates.
49              
50             The official Google API document can be found L.
51              
52             =head1 STRATEGIES
53              
54             +-------------+
55             | Strategy |
56             +-------------+
57             | desktop |
58             | mobile |
59             +-------------+
60              
61             =head1 RULES
62              
63             +---------------------------------------+
64             | Rule |
65             +---------------------------------------+
66             | AvoidCssImport |
67             | InlineSmallJavaScript |
68             | SpecifyCharsetEarly |
69             | SpecifyACacheValidator |
70             | SpecifyImageDimensions |
71             | MakeLandingPageRedirectsCacheable |
72             | MinimizeRequestSize |
73             | PreferAsyncResources |
74             | MinifyCss |
75             | ServeResourcesFromAConsistentUrl |
76             | MinifyHTML |
77             | OptimizeTheOrderOfStylesAndScripts |
78             | PutCssInTheDocumentHead |
79             | MinimizeRedirects |
80             | InlineSmallCss |
81             | MinifyJavaScript |
82             | DeferParsingJavaScript |
83             | SpecifyAVaryAcceptEncodingHeader |
84             | LeverageBrowserCaching |
85             | OptimizeImages |
86             | SpriteImages |
87             | RemoveQueryStringsFromStaticResources |
88             | ServeScaledImages |
89             | AvoidBadRequests |
90             | UseAnApplicationCache |
91             +---------------------------------------+
92              
93             =head1 LOCALES
94              
95             +-------+------------------------------+
96             | Code | Description |
97             +-------+------------------------------+
98             | ar | Arabic |
99             | bg | Bulgarian |
100             | ca | Catalan |
101             | zh_TW | Traditional Chinese (Taiwan) |
102             | zh_CN | Simplified Chinese |
103             | fr | Croatian |
104             | cs | Czech |
105             | da | Danish |
106             | nl | Dutch |
107             | en_US | English |
108             | en_GB | English UK |
109             | fil | Filipino |
110             | fi | Finnish |
111             | fr | French |
112             | de | German |
113             | el | Greek |
114             | lw | Hebrew |
115             | hi | Hindi |
116             | hu | Hungarian |
117             | id | Indonesian |
118             | it | Italian |
119             | ja | Japanese |
120             | ko | Korean |
121             | lv | Latvian |
122             | lt | Lithuanian |
123             | no | Norwegian |
124             | pl | Polish |
125             | pr_BR | Portuguese (Brazilian) |
126             | pt_PT | Portuguese (Portugal) |
127             | ro | Romanian |
128             | ru | Russian |
129             | sr | Serbian |
130             | sk | Slovakian |
131             | sl | Slovenian |
132             | es | Spanish |
133             | sv | Swedish |
134             | th | Thai |
135             | tr | Turkish |
136             | uk | Ukrainian |
137             | vi | Vietnamese |
138             +-------+------------------------------+
139              
140             =head1 CONSTRUCTOR
141              
142             The constructor expects at the least the API Key that you can get from Google for
143             FREE. You can also provide prettyprint switch as well, which can have either true
144             or false values.You can pass param as scalar the API key, if that is the only the
145             thing you would want to pass in.In case you would want to pass prettyprint switch
146             then you would have to pass as hashref like:
147              
148             +-------------+----------------------+
149             | Parameter | Meaning |
150             +-------------+----------+-----------+
151             | api_key | API Key (required) |
152             +-------------+----------------------+
153              
154             use strict; use warnings;
155             use WWW::Google::PageSpeedOnline;
156              
157             my $api_key = 'Your_API_Key';
158             my $page = WWW::Google::PageSpeedOnline->new({ api_key => $api_key });
159              
160             =head1 METHODS
161              
162             =head2 process()
163              
164             The method process() accepts URL (mandatory) parameter and optionally three other
165             parameters as well namely locale, strategy and rule.
166              
167             +-----------+----------+-----------------------------------------------------------------------------------+
168             | Parameter | Required | Meaning |
169             +-----------+----------+-----------------------------------------------------------------------------------+
170             | url | YES | The URL of the page for which the Page Speed Online API should generate results. |
171             | locale | NO | The locale that results should be generated in. Default is en_US. |
172             | strategy | NO | The strategy to use when analyzing the page. Default is desktop. |
173             | rule | NO | The Page Speed rules to run. Can have multiple rules something like for example, |
174             | | | ['AvoidBadRequests', 'MinifyJavaScript'] to request multiple rules. |
175             +-----------+----------+-----------------------------------------------------------------------------------+
176              
177             use strict; use warnings;
178             use WWW::Google::PageSpeedOnline;
179              
180             my $api_key = 'Your_API_Key';
181             my $page = WWW::Google::PageSpeedOnline->new({ api_key => $api_key });
182             $page->process({ url => 'http://code.google.com/speed/page-speed/' });
183              
184             =cut
185              
186             sub process {
187 7     7 1 881 my ($self, $values) = @_;
188              
189 7         19 my $response = $self->_process($values);
190 0         0 $self->{stats} = $self->_stats($response);
191 0         0 $self->{result} = $self->_result($response);
192 0         0 $self->{advise} = $self->_advise($response);
193             }
194              
195             sub _process {
196 7     7   15 my ($self, $values) = @_;
197              
198 7         20 my $params = { url => 1, strategy => 0, locale => 0, rule => 0 };
199 7         21 my $url = $self->_url($params, $values);
200 0         0 my $response = $self->get($url);
201              
202 0         0 return from_json($response->{content});
203             }
204              
205             =head2 stats()
206              
207             Returns the object L.
208              
209             use strict; use warnings;
210             use WWW::Google::PageSpeedOnline;
211              
212             my $api_key = 'Your_API_Key';
213             my $page = WWW::Google::PageSpeedOnline->new({ api_key => $api_key });
214             $page->process({ url => 'http://code.google.com/speed/page-speed/' });
215             my $stats = $page->stats();
216              
217             print "Total Request Bytes: ", $stats->totalRequestBytes, "\n";
218             print "HTML Response Bytes: ", $sstas->htmlResponseBytes, "\n";
219              
220             =cut
221              
222             sub _stats {
223 0     0   0 my ($self, $response) = @_;
224              
225 0         0 return WWW::Google::PageSpeedOnline::Stats->new($response->{pageStats});
226             }
227              
228             =head2 result()
229              
230             Returns the object L.
231              
232             use strict; use warnings;
233             use WWW::Google::PageSpeedOnline;
234              
235             my $api_key = 'Your_API_Key';
236             my $page = WWW::Google::PageSpeedOnline->new({ api_key => $api_key });
237             $page->process({ url => 'http://code.google.com/speed/page-speed/' });
238             my $result = $page->result();
239              
240             print "Id: ", $result->id, "\n";
241             print "Titile: ", $result->title, "\n";
242             print "Score: ", $result->score, "\n";
243              
244             =cut
245              
246             sub _result {
247 0     0   0 my ($self, $response) = @_;
248              
249 0         0 my $rules = [];
250 0         0 my $result = $response->{formattedResults}->{ruleResults};
251 0         0 foreach my $rule (keys %{$result}) {
  0         0  
252 0         0 push @$rules, WWW::Google::PageSpeedOnline::Result::Rule->new($result->{$rule});
253             }
254              
255             return WWW::Google::PageSpeedOnline::Result->new(
256             id => $response->{id},
257             title => $response->{title},
258             score => $response->{score},
259 0         0 rules => $rules);
260             }
261              
262             =head2 advise()
263              
264             Returns reference to the list of the objects L.
265              
266             use strict; use warnings;
267             use WWW::Google::PageSpeedOnline;
268              
269             my $api_key = 'Your_API_Key';
270             my $page = WWW::Google::PageSpeedOnline->new({ api_key => $api_key });
271             $page->process({ url => 'http://code.google.com/speed/page-speed/' });
272             my $advise = $page->advise();
273              
274             foreach (@$advise) {
275             print "Id: ", $_->id, ", Header: ", $_->header, "\n";
276             }
277              
278             =cut
279              
280             sub _advise {
281 0     0   0 my ($self, $response) = @_;
282              
283 0         0 my $advise = [];
284 0         0 my $result = $response->{formattedResults}->{ruleResults};
285 0         0 foreach my $rule (keys %{$result}) {
  0         0  
286 0 0       0 next unless exists $result->{$rule}->{urlBlocks};
287              
288 0         0 foreach my $block (@{$result->{$rule}->{urlBlocks}}) {
  0         0  
289 0         0 my $header = _format($block->{header}->{format}, $block->{header}->{args});
290 0         0 my $items = [];
291 0 0 0     0 if (exists($block->{urls}) && (scalar(@{$block->{urls}}))) {
  0         0  
292 0         0 foreach my $url (@{$block->{urls}}) {
  0         0  
293 0         0 push @$items, _format($url->{result}->{format}, $url->{result}->{args});
294             }
295             }
296 0         0 push @$advise, WWW::Google::PageSpeedOnline::Advise->new(
297             id => $rule,
298             header => $header,
299             items => $items);
300             }
301             }
302              
303 0         0 return $advise;
304             }
305              
306             #
307             # PRIVATE METHODS
308             #
309              
310             sub _url {
311 7     7   15 my ($self, $params, $values) = @_;
312              
313 7         43 my $url = sprintf("%s?key=%s&prettyprint=%s",
314             $BASE_URL, $self->api_key, $self->prettyprint);
315              
316 7 50 33     38 if (defined $params && defined $values) {
317 7         25 validate($params, $values);
318              
319 0           foreach my $key (keys %$params) {
320 0           my $_key = "&$key=%" . $FIELDS->{$key}->{type};
321 0 0         if (defined $values->{$key}) {
    0          
322 0           $url .= sprintf($_key, $values->{$key});
323             }
324             elsif (exists $values->{$key}) {
325 0           $url .= sprintf($_key, $self->{$key});
326             }
327             }
328             }
329              
330 0           return $url;
331             }
332              
333             sub _format {
334 0     0     my ($data, $args) = @_;
335              
336 0           $data =~ s/\s+/ /g;
337 0           my $counter = 1;
338 0           foreach my $arg (@{$args}) {
  0            
339 0           $data =~ s/\$$counter/$arg->{value}/e;
  0            
340 0           $counter++;
341             }
342              
343 0           return $data;
344             }
345              
346             =head1 AUTHOR
347              
348             Mohammad S Anwar, C<< >>
349              
350             =head1 REPOSITORY
351              
352             L
353              
354             =head1 BUGS
355              
356             Please report any bugs or feature requests to C
357             rt.cpan.org>, or through the web interface at L.
358             I will be notified, and then you'll automatically be notified of progress on your
359             bug as I make changes.
360              
361             =head1 SUPPORT
362              
363             You can find documentation for this module with the perldoc command.
364              
365             perldoc WWW::Google::PageSpeedOnline
366              
367             You can also look for information at:
368              
369             =over 4
370              
371             =item * RT: CPAN's request tracker (report bugs here)
372              
373             L
374              
375             =item * AnnoCPAN: Annotated CPAN documentation
376              
377             L
378              
379             =item * CPAN Ratings
380              
381             L
382              
383             =item * Search CPAN
384              
385             L
386              
387             =back
388              
389             =head1 LICENSE AND COPYRIGHT
390              
391             Copyright (C) 2011 - 2015 Mohammad S Anwar.
392              
393             This program is free software; you can redistribute it and/or modify it under
394             the terms of the the Artistic License (2.0). You may obtain a copy of the full
395             license at:
396              
397             L
398              
399             Any use, modification, and distribution of the Standard or Modified Versions is
400             governed by this Artistic License.By using, modifying or distributing the Package,
401             you accept this license. Do not use, modify, or distribute the Package, if you do
402             not accept this license.
403              
404             If your Modified Version has been derived from a Modified Version made by someone
405             other than you,you are nevertheless required to ensure that your Modified Version
406             complies with the requirements of this license.
407              
408             This license does not grant you the right to use any trademark, service mark,
409             tradename, or logo of the Copyright Holder.
410              
411             This license includes the non-exclusive, worldwide, free-of-charge patent license
412             to make, have made, use, offer to sell, sell, import and otherwise transfer the
413             Package with respect to any patent claims licensable by the Copyright Holder that
414             are necessarily infringed by the Package. If you institute patent litigation
415             (including a cross-claim or counterclaim) against any party alleging that the
416             Package constitutes direct or contributory patent infringement,then this Artistic
417             License to you shall terminate on the date that such litigation is filed.
418              
419             Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
420             CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
421             WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
422             NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
423             REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
424             INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
425             OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
426              
427             =cut
428              
429             1; # End of WWW::Google::PageSpeedOnline