blib/lib/HTTP/Thin/UserAgent.pm

filter: Statementstmt 54.5% 78 / 143 Branchbran 0.0% 0 / 12 Conditioncond 50.0% 1 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 48.8% 21 / 43 Podpod 22.2% 2 / 9 totaltotal 48.5% 102 / 210 SCAR 33.9
CC
12
Cov
50%
_build_response
12.0
find
12.0
as_json
6.0
CRAP 29.7
↑ Summary
1 package HTTP::Thin::UserAgent;
2 4 $HTTP::Thin::UserAgent::VERSION = '0.014';
3 4 ▶use 5.12.1;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 # ABSTRACT: A Thin UserAgent around some useful modules.
7  
8  
9 {
10 package
11 HTTP::Thin::UserAgent::HTTPExceptionWithResponse;
12 4 ▶ use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 has response => ( is => 'ro' );
14 }
15  
16 {
17 4 package
18 HTTP::Thin::UserAgent::Error::UnexpectedResponse;
19  
20 4 ▶ use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 4 extends qw(Throwable::Error);
22 4 with qw(HTTP::Thin::UserAgent::HTTPExceptionWithResponse);
23  
24 }
25  
26 {
27 4 package
28 HTTP::Thin::UserAgent::HTTP::Throwable::Factory;
29 4 ▶ use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 4 extends qw(HTTP::Throwable::Factory);
32  
33 sub extra_roles {
34 0 ▶ return qw(
Subroutine extra_roles: not called CC=1 SCAR=6.9
Pod documented
35 HTTP::Throwable::Role::TextBody
36 HTTP::Thin::UserAgent::HTTPExceptionWithResponse
37 );
38 }
39 }
40  
41 {
42  
43 4 package
44 HTTP::Thin::UserAgent::Client;
45  
46 4 ▶ use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 4 ▶ use MooX::late;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 4 ▶ use MooX::ChainedAttributes;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 4 ▶ use HTTP::Thin;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 4 ▶ use JSON::Any;
Subroutine BEGIN: called CC=1 SCAR=0.0
51 4 ▶ use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
52 4 ▶ use Scalar::Util qw/weaken/;
Subroutine BEGIN: called CC=1 SCAR=0.0
53 4 ▶ use Carp qw(confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
54  
55 4 ▶ use constant TRACE => $ENV{TRACE} // 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{"TRACE"} // 0
l!l
04
MC/DC0%0/1
$ENV{"TRACE"} // 0
$ENV{"TRACE"}
Truth table50%1/2
A
A= $ENV{"TRACE"}
Aresult
11
00
56 4 ▶ use constant UnexpectedResponse => 'HTTP::Thin::UserAgent::Error::UnexpectedResponse';
Subroutine BEGIN: called CC=1 SCAR=0.0
57 4 ▶ use constant HTTPException => 'HTTP::Thin::UserAgent::HTTP::Throwable::Factory';
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 has ua => (
60 is => 'ro',
61 0 ▶ default => sub { HTTP::Thin->new() },
Subroutine __ANON__: not called CC=1 SCAR=6.9
62 4 );
63  
64 4 has request => (
65 is => 'ro',
66 required => 1,
67 );
68  
69 has on_error => (
70 is => 'rw',
71 0 ▶ default => sub { sub { confess $_->message } },
Subroutine __ANON__: not called CC=1 SCAR=6.9
72 4 chained => 1,
73 );
74  
75 has decoder => (
76 is => 'rw',
77 chained => 1,
78 default => sub {
79 0 ▶ sub { shift->decoded_content }
Subroutine __ANON__: not called CC=1 SCAR=6.9
80 0 ▶ },
Subroutine __ANON__: not called CC=1 SCAR=6.9
81 4 );
82  
83 sub decoded_content {
84 0 ▶ my $self = shift;
Subroutine decoded_content: not called CC=1 SCAR=6.9
Pod undocumented
85 0 return $self->decoder->( $self->response );
86 }
87  
88 0 ▶ sub decode { warn 'decode is deprecated, please call decoded_content instead'; shift->decoded_content }
Subroutine decode: not called CC=1 SCAR=6.9
Pod undocumented
89  
90 4 has response => (
91 is => 'ro',
92 lazy => 1,
93 builder => '_build_response',
94 handles => { 'content' => 'decoded_content' },
95 );
96  
97 sub _build_response {
98 0 ▶ my $self = shift;
Subroutine _build_response: not called CC=3 SCAR=24.8
99 0 my $ua = $self->ua;
100 0 my $request = $self->request;
101  
102 0 warn $request->dump if TRACE;
103 0 my $res = $ua->request($request);
104 0 warn $res->dump if TRACE;
105  
106 0 ▶ if ($res->is_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 0 0 0
107  
108 0 my $e = HTTPException->new_exception({
109 status_code => $res->code,
110 reason => $res->message,
111 additional_headers => [
112 $res->headers->flatten(),
113 ],
114 response => $res,
115 });
116  
117 0 for ($e) {
118 0 $self->on_error->($e);
119 }
120 }
121  
122 0 return $res;
123 }
124  
125 sub as_json {
126 0 ▶ my $self = shift;
Subroutine as_json: not called CC=2 SCAR=17.9
Pod undocumented
127  
128 0 my $request = $self->request;
129  
130 0 $request->header(
131 'Accept' => 'application/json',
132 'Content-Type' => 'application/json',
133 );
134  
135 0 ▶ if ( my $data = shift ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = shift()) 0 0 0
136 0 $request->content( JSON::Any->encode($data) );
137 }
138  
139 0 weaken($self);
140 $self->decoder(
141 sub {
142 0 ▶ my $res = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
143 0 my $content_type = $res->header('Content-Type');
144 my $data = try {
145 0 ▶ die "Content-Type was $content_type not application/json"
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
unless $content_type =~ m[application/json]u 0 0 0
146 unless $content_type =~ m'application/json';
147 0 JSON::Any->decode( $res->decoded_content );
148 }
149 catch {
150 0 ▶ my $error = UnexpectedResponse->new(
Subroutine __ANON__: not called CC=2 SCAR=17.9
151 message => $_,
152 response => $res,
153 );
154 0 for ($error) {
155 0 $self->on_error->($error);
156 }
157 0 };
158 }
159 0 );
160 0 return $self;
161 }
162  
163 0 ▶ sub dump { require Data::Dumper; return Data::Dumper::Dumper(shift) }
Subroutine dump: not called CC=1 SCAR=6.9
Pod undocumented
164  
165 sub scraper {
166 0 ▶ my ( $self, $scraper ) = @_;
Subroutine scraper: not called CC=1 SCAR=6.9
Pod undocumented
167  
168 0 weaken($self);
169 $self->decoder(
170 sub {
171 0 ▶ my $res = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
172 0 ▶ my $data = try { $scraper->scrape( $res->decoded_content ) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
173 catch {
174 0 ▶ my $error = UnexpectedResponse->new(
Subroutine __ANON__: not called CC=2 SCAR=17.9
175 message => $_,
176 response => $res
177 );
178 0 for ($error) { $self->on_error->($error); }
179 0 };
180 0 return $data;
181 }
182 0 );
183 0 return $self;
184 }
185  
186 sub tree {
187 0 ▶ my ($self) = @_;
Subroutine tree: not called CC=2 SCAR=17.9
Pod undocumented
188 0 my $t = HTML::TreeBuilder::XPath->new;
189 0 ▶ $t->store_comments(1) if ( $t->can('store_comments') );
Branch: 1 branch
BranchTrueFalseTotal
if $t->can("store_comments") 0 0 0
190 0 $t->ignore_unknown(0);
191 0 $t->parse( $self->content );
192 0 return $t;
193 }
194  
195 sub find {
196 0 ▶ my ( $self, $exp ) = @_;
Subroutine find: not called CC=3 SCAR=24.8
Pod undocumented
197  
198 0 ▶ my $xpath =
Branch: 1 branch
BranchTrueFalseTotal
$exp =~ m[^(?:/|id\()]u ? : 0 0 0
199 $exp =~ m!^(?:/|id\()!
200 ? $exp
201 : HTML::Selector::XPath::selector_to_xpath($exp);
202  
203 0 ▶ my @nodes = try { $self->tree->findnodes($xpath) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
204 catch {
205 0 ▶ for ($_) { $self->on_error($_) }
Subroutine __ANON__: not called CC=2 SCAR=17.9
206 0 };
207 0 ▶ return unless @nodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @nodes 0 0 0
208 0 return \@nodes;
209 }
210  
211 }
212  
213 4 ▶use parent qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
214 4 ▶use Import::Into;
Subroutine BEGIN: called CC=1 SCAR=0.0
215 4 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
216 4 ▶use Web::Scraper;
Subroutine BEGIN: called CC=1 SCAR=0.0
217  
218 4 our @EXPORT = qw(http);
219  
220 sub import {
221 3 ▶ shift->export_to_level(1);
Subroutine import: called CC=1 SCAR=0.0
222 3 HTTP::Request::Common->import::into( scalar caller );
223 3 Web::Scraper->import::into( scalar caller );
224 }
225  
226 0 ▶sub http { HTTP::Thin::UserAgent::Client->new( request => shift ) }
Subroutine http: not called CC=1 SCAR=6.9
Pod documented
227  
228 4 1;
229  
230 __END__
231  
232 =pod
233  
234 =encoding UTF-8
235  
236 =head1 NAME
237  
238 HTTP::Thin::UserAgent - A Thin UserAgent around some useful modules.
239  
240 =head1 VERSION
241  
242 version 0.014
243  
244 =head1 SYNOPSIS
245  
246 use HTTP::Thin::UserAgent;
247  
248 my $favorites = http(GET 'http://api.metacpan.org/v0/author/PERIGRIN?join=favorite')->as_json->decoded_content;
249  
250 my $results = http(GET 'http://www.imdb.com/find?q=Kevin+Bacon')->scraper(
251 scraper {
252 process '.findResult', 'results[]' => scraper {
253 process '.result_text', text => 'TEXT';
254 process '.result_text > a', link => '@href';
255 }
256 }
257 );
258  
259 =head1 DESCRIPTION
260  
261 C<HTTP::Thin::UserAgent> provides a layer over L<HTTP::Thin>. It exposes an functional API that hopefully makes writing HTTP clients easier.
262  
263 =head1 EXPORTS
264  
265 =over 4
266  
267 =item http
268  
269 A function that returns a new C<HTTP::Thin::UserAgent::Client> object, which does the actual work for the request. You pas in an L<HTTP::Request> object.
270  
271 =item GET / PUT / POST
272  
273 Exports from L<HTTP::Request::Common> to make generating L<HTTP::Request> objects easier.
274  
275 =item scraper / process
276  
277 Exports from L<Web::Scraper> to assist in building scrapers for HTML documents.
278  
279 =back
280  
281 =head1 METHODS
282  
283 C<HTTP::Thin::UserAgent::Client> has the following methods.
284  
285 =over 4
286  
287 =item response( )
288  
289 Returns the L<HTTP::Response> object returned by L<HTTP::Thin>
290  
291 =item as_json( $data )
292  
293 This sets the request up to use C<application/json> and then adds a decoder to decode the L<HTTP::Response> content. If data is passed in it will be encoded into JSON and supplied in as the request data.
294  
295 =item scraper( $scraper )
296  
297 Sets up the request to process the response through the L<Web::Scraper> object supplied. It will return the data (if any) returned by the scraper object.
298  
299 =item decoded_content( )
300  
301 Returns the decoded content, currently we only support HTML (in which case we return scraped content) and JSON (in which case we decode the JSON using JSON::Any).
302  
303 =item tree( )
304  
305 Returns a L<HTML::Treebuilder::XPath> object.
306  
307 =item find( $exp )
308  
309 Takes a CSS or XPath expression and returns an arrayref of L<HTML::Treebuilder::XPath> nodes.
310  
311 =item on_error( $coderef )
312  
313 A code reference that if there is an error in fetching the HTTP response handles that error. C<$_> will be set to the error being handled. Exceptions are
314 L<HTTP::Throwable> objects for server side errors.
315  
316 =back
317  
318 =head1 ENVIRONMENT
319  
320 =over 4
321  
322 =item TRACE
323  
324 When set to true the C<TRACE> variable will cause C<HTTP::Thin::UserAgent::Client> to emit dumps of the request and response objects as it processes them. This is to help you in debugging the HTTP requests.
325  
326 =back
327  
328 =head1 AUTHOR
329  
330 Chris Prather <chris@prather.org>
331  
332 =head1 COPYRIGHT AND LICENSE
333  
334 This software is copyright (c) 2013 by Chris Prather.
335  
336 This is free software; you can redistribute it and/or modify it under
337 the same terms as the Perl 5 programming language system itself.
338  
339 =cut
↑ Summary