blib/lib/HTTP/Thin/UserAgent.pm

filter: Statementstmt 52.3% 78 / 149 Branchbran 0.0% 0 / 14 Conditioncond 50.0% 1 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 47.7% 21 / 44 Podpod 20.0% 2 / 10 totaltotal 46.3% 102 / 220 SCAR 36.1
CC
13
Cov
48%
_build_response
20.0
find
12.0
as_json
6.0
CRAP 36.9
↑ Summary
1 package HTTP::Thin::UserAgent;
2 4 $HTTP::Thin::UserAgent::VERSION = '0.015';
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 # A PR for this has been sent to HTTP::Throwable when that ships we can bump the dep
41 # and remove this method
42 sub ident_for_status_code {
43 0 ▶ my ($self, $code) = @_;
Subroutine ident_for_status_code: not called CC=1 SCAR=6.9
Pod undocumented
44  
45 0 my %lookup = (
46 300 => 'MultipleChoices',
47 301 => 'MovedPermanently',
48 302 => 'Found',
49 303 => 'SeeOther',
50 304 => 'NotModified',
51 305 => 'UseProxy',
52 307 => 'TemporaryRedirect',
53  
54 400 => 'BadRequest',
55 401 => 'Unauthorized',
56 403 => 'Forbidden',
57 404 => 'NotFound',
58 405 => 'MethodNotAllowed',
59 406 => 'NotAcceptable',
60 407 => 'ProxyAuthenticationRequired',
61 408 => 'RequestTimeout',
62 409 => 'Conflict',
63 410 => 'Gone',
64 411 => 'LengthRequired',
65 412 => 'PreconditionFailed',
66 413 => 'RequestEntityTooLarge',
67 414 => 'RequestURITooLong',
68 415 => 'UnsupportedMediaType',
69 416 => 'RequestedRangeNotSatisfiable',
70 417 => 'ExpectationFailed',
71  
72 500 => 'InternalServerError',
73 501 => 'NotImplemented',
74 502 => 'BadGateway',
75 503 => 'Status::ServiceUnavailable',
76 504 => 'GatewayTimeout',
77 505 => 'HTTPVersionNotSupported',
78 );
79  
80 0 return $lookup{$code};
81 }
82 }
83  
84 {
85  
86 4 package
87 HTTP::Thin::UserAgent::Client;
88  
89 4 ▶ use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
90 4 ▶ use MooX::late;
Subroutine BEGIN: called CC=1 SCAR=0.0
91 4 ▶ use MooX::ChainedAttributes;
Subroutine BEGIN: called CC=1 SCAR=0.0
92 4 ▶ use HTTP::Thin;
Subroutine BEGIN: called CC=1 SCAR=0.0
93 4 ▶ use JSON::Any;
Subroutine BEGIN: called CC=1 SCAR=0.0
94 4 ▶ use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
95 4 ▶ use Scalar::Util qw/weaken/;
Subroutine BEGIN: called CC=1 SCAR=0.0
96 4 ▶ use Carp qw(confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
97  
98 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
99 4 ▶ use constant UnexpectedResponse => 'HTTP::Thin::UserAgent::Error::UnexpectedResponse';
Subroutine BEGIN: called CC=1 SCAR=0.0
100 4 ▶ use constant HTTPException => 'HTTP::Thin::UserAgent::HTTP::Throwable::Factory';
Subroutine BEGIN: called CC=1 SCAR=0.0
101  
102 has ua => (
103 is => 'ro',
104 0 ▶ default => sub { HTTP::Thin->new() },
Subroutine __ANON__: not called CC=1 SCAR=6.9
105 4 );
106  
107 4 has request => (
108 is => 'ro',
109 required => 1,
110 );
111  
112 has on_error => (
113 is => 'rw',
114 0 ▶ default => sub { sub { confess $_->message } },
Subroutine __ANON__: not called CC=1 SCAR=6.9
115 4 chained => 1,
116 );
117  
118 has decoder => (
119 is => 'rw',
120 chained => 1,
121 default => sub {
122 0 ▶ sub { shift->decoded_content }
Subroutine __ANON__: not called CC=1 SCAR=6.9
123 0 ▶ },
Subroutine __ANON__: not called CC=1 SCAR=6.9
124 4 );
125  
126 sub decoded_content {
127 0 ▶ my $self = shift;
Subroutine decoded_content: not called CC=1 SCAR=6.9
Pod undocumented
128 0 return $self->decoder->( $self->response );
129 }
130  
131 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
132  
133 4 has response => (
134 is => 'ro',
135 lazy => 1,
136 builder => '_build_response',
137 handles => { 'content' => 'decoded_content' },
138 );
139  
140 sub _build_response {
141 0 ▶ my $self = shift;
Subroutine _build_response: not called CC=4 SCAR=30.0
142 0 my $ua = $self->ua;
143 0 my $request = $self->request;
144  
145 0 warn $request->dump if TRACE;
146 0 my $res = $ua->request($request);
147 0 warn $res->dump if TRACE;
148  
149 0 ▶ if ( $res->is_error ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 0 0 0
150 0 my $e;
151 0 ▶ if ( my $id = HTTPException->ident_for_status_code( $res->code ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = 'HTTP::Thin::UserAgent::HTTP::Throwable::Factory'->ident_for_status_code($res->code)) { } 0 0 0
152 0 $e = HTTPException->new_exception(
153 $id => {
154 additional_headers => [ $res->headers->flatten() ],
155 response => $res,
156 }
157 );
158 }
159 else {
160 0 $e = HTTPException->new_exception(
161 {
162 status_code => $res->code,
163 reason => $res->message,
164 additional_headers => [ $res->headers->flatten(), ],
165 response => $res,
166 }
167 );
168 }
169  
170 0 for ($e) { $self->on_error->($e) }
171 }
172  
173 0 return $res;
174 }
175  
176 sub as_json {
177 0 ▶ my $self = shift;
Subroutine as_json: not called CC=2 SCAR=17.9
Pod undocumented
178  
179 0 my $request = $self->request;
180  
181 0 $request->header(
182 'Accept' => 'application/json',
183 'Content-Type' => 'application/json',
184 );
185  
186 0 ▶ if ( my $data = shift ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $data = shift()) 0 0 0
187 0 $request->content( JSON::Any->encode($data) );
188 }
189  
190 0 weaken($self);
191 $self->decoder(
192 sub {
193 0 ▶ my $res = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
194 0 my $content_type = $res->header('Content-Type');
195 my $data = try {
196 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
197 unless $content_type =~ m'application/json';
198 0 JSON::Any->decode( $res->decoded_content );
199 }
200 catch {
201 0 ▶ my $error = UnexpectedResponse->new(
Subroutine __ANON__: not called CC=2 SCAR=17.9
202 message => $_,
203 response => $res,
204 );
205 0 for ($error) {
206 0 $self->on_error->($error);
207 }
208 0 };
209 }
210 0 );
211 0 return $self;
212 }
213  
214 0 ▶ sub dump { require Data::Dumper; return Data::Dumper::Dumper(shift) }
Subroutine dump: not called CC=1 SCAR=6.9
Pod undocumented
215  
216 sub scraper {
217 0 ▶ my ( $self, $scraper ) = @_;
Subroutine scraper: not called CC=1 SCAR=6.9
Pod undocumented
218  
219 0 weaken($self);
220 $self->decoder(
221 sub {
222 0 ▶ my $res = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
223 0 ▶ my $data = try { $scraper->scrape( $res->decoded_content ) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
224 catch {
225 0 ▶ my $error = UnexpectedResponse->new(
Subroutine __ANON__: not called CC=2 SCAR=17.9
226 message => $_,
227 response => $res
228 );
229 0 for ($error) { $self->on_error->($error); }
230 0 };
231 0 return $data;
232 }
233 0 );
234 0 return $self;
235 }
236  
237 sub tree {
238 0 ▶ my ($self) = @_;
Subroutine tree: not called CC=2 SCAR=17.9
Pod undocumented
239 0 my $t = HTML::TreeBuilder::XPath->new;
240 0 ▶ $t->store_comments(1) if ( $t->can('store_comments') );
Branch: 1 branch
BranchTrueFalseTotal
if $t->can("store_comments") 0 0 0
241 0 $t->ignore_unknown(0);
242 0 $t->parse( $self->content );
243 0 return $t;
244 }
245  
246 sub find {
247 0 ▶ my ( $self, $exp ) = @_;
Subroutine find: not called CC=3 SCAR=24.8
Pod undocumented
248  
249 0 ▶ my $xpath =
Branch: 1 branch
BranchTrueFalseTotal
$exp =~ m[^(?:/|id\()]u ? : 0 0 0
250 $exp =~ m!^(?:/|id\()!
251 ? $exp
252 : HTML::Selector::XPath::selector_to_xpath($exp);
253  
254 0 ▶ my @nodes = try { $self->tree->findnodes($xpath) }
Subroutine __ANON__: not called CC=1 SCAR=6.9
255 catch {
256 0 ▶ for ($_) { $self->on_error($_) }
Subroutine __ANON__: not called CC=2 SCAR=17.9
257 0 };
258 0 ▶ return unless @nodes;
Branch: 1 branch
BranchTrueFalseTotal
unless @nodes 0 0 0
259 0 return \@nodes;
260 }
261  
262 }
263  
264 4 ▶use parent qw(Exporter);
Subroutine BEGIN: called CC=1 SCAR=0.0
265 4 ▶use Import::Into;
Subroutine BEGIN: called CC=1 SCAR=0.0
266 4 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
267 4 ▶use Web::Scraper;
Subroutine BEGIN: called CC=1 SCAR=0.0
268  
269 4 our @EXPORT = qw(http);
270  
271 sub import {
272 3 ▶ shift->export_to_level(1);
Subroutine import: called CC=1 SCAR=0.0
273 3 HTTP::Request::Common->import::into( scalar caller );
274 3 Web::Scraper->import::into( scalar caller );
275 }
276  
277 0 ▶sub http { HTTP::Thin::UserAgent::Client->new( request => shift ) }
Subroutine http: not called CC=1 SCAR=6.9
Pod documented
278  
279 4 1;
280  
281 __END__
282  
283 =pod
284  
285 =encoding UTF-8
286  
287 =head1 NAME
288  
289 HTTP::Thin::UserAgent - A Thin UserAgent around some useful modules.
290  
291 =head1 VERSION
292  
293 version 0.015
294  
295 =head1 SYNOPSIS
296  
297 use HTTP::Thin::UserAgent;
298  
299 my $favorites = http(GET 'http://api.metacpan.org/v0/author/PERIGRIN?join=favorite')->as_json->decoded_content;
300  
301 my $results = http(GET 'http://www.imdb.com/find?q=Kevin+Bacon')->scraper(
302 scraper {
303 process '.findResult', 'results[]' => scraper {
304 process '.result_text', text => 'TEXT';
305 process '.result_text > a', link => '@href';
306 }
307 }
308 );
309  
310 =head1 DESCRIPTION
311  
312 C<HTTP::Thin::UserAgent> provides a layer over L<HTTP::Thin>. It exposes an functional API that hopefully makes writing HTTP clients easier.
313  
314 =head1 EXPORTS
315  
316 =over 4
317  
318 =item http
319  
320 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.
321  
322 =item GET / PUT / POST
323  
324 Exports from L<HTTP::Request::Common> to make generating L<HTTP::Request> objects easier.
325  
326 =item scraper / process
327  
328 Exports from L<Web::Scraper> to assist in building scrapers for HTML documents.
329  
330 =back
331  
332 =head1 METHODS
333  
334 C<HTTP::Thin::UserAgent::Client> has the following methods.
335  
336 =over 4
337  
338 =item response( )
339  
340 Returns the L<HTTP::Response> object returned by L<HTTP::Thin>
341  
342 =item as_json( $data )
343  
344 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.
345  
346 =item scraper( $scraper )
347  
348 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.
349  
350 =item decoded_content( )
351  
352 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).
353  
354 =item tree( )
355  
356 Returns a L<HTML::Treebuilder::XPath> object.
357  
358 =item find( $exp )
359  
360 Takes a CSS or XPath expression and returns an arrayref of L<HTML::Treebuilder::XPath> nodes.
361  
362 =item on_error( $coderef )
363  
364 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
365 L<HTTP::Throwable> objects for server side errors.
366  
367 =back
368  
369 =head1 ENVIRONMENT
370  
371 =over 4
372  
373 =item TRACE
374  
375 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.
376  
377 =back
378  
379 =head1 AUTHOR
380  
381 Chris Prather <chris@prather.org>
382  
383 =head1 COPYRIGHT AND LICENSE
384  
385 This software is copyright (c) 2013 by Chris Prather.
386  
387 This is free software; you can redistribute it and/or modify it under
388 the same terms as the Perl 5 programming language system itself.
389  
390 =cut
↑ Summary