Client.pm

filter: Statementstmt 100% 412 / 412 Branchbran 98.4% 185 / 188 Conditioncond 98.0% 50 / 51 MC/DCmcdc 96.7% 30 / 31 Subroutinesub 100% 62 / 62 Podpod 100% 17 / 17 totaltotal 99.3% 756 / 761 CC 122 SCAR 23.6
CC
122
Cov
99%
send
24.0
kvp2str_each
22.0
new_request
20.0
CRAP 10.6
↑ Summary DataTypeMarker.pm »
1 package HTTP::API::Client;
2 95 $HTTP::API::Client::VERSION = '1.26';
3 95 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 =head1 NAME
6  
7 HTTP::API::Client - lightweight HTTP/REST client with per-request signing
8 hooks, retry-with-backoff, and JSON/form encoding
9  
10 =head1 DESCRIPTION
11  
12 Talking to an authenticated JSON or form-urlencoded REST API with plain
13 L<LWP::UserAgent> usually means the same boilerplate on every call: compute
14 a signature or auth header from the request's own data, remember not to
15 leak the signing secret into the body, retry on a flaky response, and
16 serialize Perl values (which have no native boolean and no native
17 comma-list) unambiguously. C<HTTP::API::Client> is that boilerplate,
18 written once - a thin L<LWP::UserAgent> wrapper with:
19  
20 =over 4
21  
22 =item * An event/callback system (see L</"new_request(%options)">) that computes
23 header or data values from the rest of the request at build time - the
24 mechanism for a signed-request header, not a special case bolted on top
25 of it.
26  
27 =item * Retry-with-backoff on failed responses, configurable per status
28 code (see L</"ENVIRONMENT VARIABLES">).
29  
30 =item * JSON and form-urlencoded body encoding from the same C<%data>
31 hash, including L<HTTP::API::DataTypeMarker>'s C<xTRUE>/C<xCSV>-family
32 markers for the values Perl scalars can't represent unambiguously on
33 their own.
34  
35 =back
36  
37 If none of that boilerplate applies to what you're calling - no signing,
38 no retry policy, plain data - reaching for L<LWP::UserAgent> or
39 L<HTTP::Tiny> directly is simpler. This module earns its weight
40 specifically for authenticated API clients that would otherwise
41 reimplement the same header-signing/retry logic by hand.
42  
43 =head1 USAGE
44  
45 use HTTP::API::Client;
46  
47 The constructor takes no required arguments:
48  
49 my $ua = HTTP::API::Client->new(
50 base_url => "https://api.example.com",
51 );
52  
53 =head2 A signed request
54  
55 This is the case the module exists for: compute an auth header from the
56 request's own data, once, at construction - every call this client makes
57 carries it automatically, and the secret used to compute it never appears
58 in the request itself.
59  
60 my $ua = HTTP::API::Client->new(
61 base_url => "https://api.example.com",
62 pre_defined_data => {
63 api_key => "AKIA123",
64 api_secret => sub { "s3cr3t" }, # or read from config/env
65 },
66 pre_defined_headers => {
67 APIKEY => sub { my (undef, %o) = @_; $o{data}{api_key} },
68 Signature => sub {
69 my (undef, %o) = @_;
70 "$o{data}{api_key}:$o{data}{api_secret}"; # a real HMAC in practice
71 },
72 },
73 pre_defined_events => {
74 not_include => { api_secret => 1 }, # keep the secret out of the body/query
75 },
76 );
77  
78 $ua->get("/search", { q => "widgets" });
79 # -> GET https://api.example.com/search?api_key=AKIA123&q=widgets
80 # APIKEY: AKIA123
81 # Signature: AKIA123:s3cr3t
82  
83 See L</"new_request(%options)"> for the full list of build-time hooks this uses.
84  
85 =head2 Shorthand methods
86  
87 C<get>/C<post>/C<put>/C<head>/C<delete> are shorthand over C<send()>:
88  
89 $ua->get($url); # same as $ua->send( GET, $url )
90 $ua->post($url, \%data, \%headers); # same as $ua->send( POST, $url, \%data, \%headers )
91  
92 =head2 JSON in, JSON out
93  
94 my $ua = HTTP::API::Client->new(base_url => "http://example.com");
95 $ua->get("/search", { q => "something" });
96 my $decoded = $ua->json_response; # the response body, JSON-decoded
97  
98 =head2 Form-urlencoded
99  
100 my $ua = HTTP::API::Client->new(content_type => "application/x-www-form-urlencoded");
101 $ua->post("http://example.com", { q => "something" });
102 my $response = $ua->last_response; # an HTTP::Response object
103  
104 Body encoding only knows how to serialize into JSON or a query string
105 (see C<convert_data()> below) - any other content type must be built and
106 passed in already-encoded.
107  
108 =head1 ATTRIBUTES
109  
110 All constructor arguments below are also read-write accessors
111 (C<< $ua->base_url("http://new-host") >>), except C<engine> which is
112 read-only after construction. Several fall back to an environment
113 variable (see L</"ENVIRONMENT VARIABLES">) when not passed explicitly.
114  
115 =over 4
116  
117 =item base_url
118  
119 Prefixed onto every C<$path> passed to C<send()> (and the shorthand
120 methods). Not set by default - a bare path is used as-is.
121  
122 =item username / password
123  
124 HTTP Basic auth credentials. If either is set, Basic auth is used and
125 C<auth_token> is ignored. Default from C<HTTP_USERNAME>/C<HTTP_PASSWORD>.
126  
127 =item auth_token
128  
129 Sent verbatim as the C<Authorization> header when C<username>/C<password>
130 are both unset. Default from C<HTTP_AUTH_TOKEN>.
131  
132 =item content_type
133  
134 Forces the request content type. Left unset, GET defaults to
135 C<application/x-www-form-urlencoded> and every other method defaults to
136 C<application/json; charset=$charset>.
137  
138 =item charset
139  
140 Used to build the default JSON content-type header and to decide whether
141 UTF-8 byte-encoding is applied to the request body. Default C<utf8>, from
142 C<HTTP_CHARSET>. Must be a real L<JSON::XS> charset method name (C<utf8>,
143 C<latin1>, C<ascii>, ...) - an invalid value dies immediately and clearly,
144 naming the bad value, the next time C<kvp2json()> is called, whether or
145 not C<json> has already been built.
146  
147 =item timeout
148  
149 Request timeout in seconds, passed to the underlying L<LWP::UserAgent>.
150 Default C<60>, from C<HTTP_TIMEOUT>. Re-applied to C<ua> at the start of
151 every C<send()> call, so changing it between calls takes effect on the
152 next one, not just at construction.
153  
154 =item ssl_verify
155  
156 Passed through as C<verify_hostname> to L<LWP::UserAgent>'s C<ssl_opts>.
157 Default off (C<0>), from C<SSL_VERIFY>. Re-applied to C<ua> at the start
158 of every C<send()> call, so changing it between calls takes effect on
159 the next one, not just at construction.
160  
161 =item pre_defined_data / pre_defined_headers / pre_defined_events
162  
163 Hashrefs merged underneath the C<%data>/C<%headers>/C<%events> passed to
164 each individual call - set once at construction time for values every
165 request should carry (an API key, a fixed header, a standing callback),
166 then override per-call as needed.
167  
168 =item engine
169  
170 Read-only. Defaults to C<"LWP::UserAgent">, the only engine C<send()>
171 actually dispatches requests through - C<_build_ua> will call a
172 same-named method on a subclass to build an alternate UA object, but
173 C<send()> itself does not yet know how to use anything other than
174 L<LWP::UserAgent> with it (see C<t/12_unsupported_engine.t>: setting a
175 different engine fails with a clear error rather than silently doing
176 nothing).
177  
178 =item last_response
179  
180 Read-write. The most recent L<HTTP::Response>, set by C<send()> and read by
181 L</json_response>/L</kvp_response>. C<undef> until the first request.
182  
183 =item ua
184  
185 Read-write. The underlying user-agent object C<send()> dispatches through
186 - an L<LWP::UserAgent> by default, built lazily by C<_build_ua> on first
187 use, then reused for every subsequent call. Set this directly to inject
188 a stand-in (a fake, a mock, a pre-configured instance) instead of the
189 real one; this is how the test suite avoids making real network calls.
190 C<browser_id>/C<timeout>/C<ssl_verify> are re-applied to it (via
191 C<< $ua->agent >>/C<< $ua->timeout >>/C<< $ua->ssl_opts >>, each only if
192 C<ua> supports that method) at the start of every C<send()> call, not
193 just when it's first built.
194  
195 =item browser_id
196  
197 Read-write. The C<User-Agent> header value passed to the underlying
198 C<ua>. Defaults to C<"HTTP API Client v$VERSION"> - C<$VERSION> is only
199 set when running the installed CPAN release (Dist::Zilla's
200 C<[PkgVersion]> plugin injects it at build time), so a development
201 checkout reports C<"HTTP API Client vdev"> instead. Re-applied to C<ua>
202 at the start of every C<send()> call, so changing it between calls takes
203 effect on the next one, not just at construction.
204  
205 =item retry
206  
207 Read-write. B<Not> a live view of C<send()>'s actual retry behavior -
208 despite the naming symmetry with C<retry_config>, C<send()> never reads
209 this attribute. It's a lazily-built, one-time snapshot of C<retry_config>
210 (and the C<RETRY_*> env vars) taken whichever moment it's first accessed,
211 kept only for external callers who already read C<< $api->retry >>
212 directly. Use C<retry_config> (or the C<RETRY_*> env vars) to actually
213 configure or inspect retry behavior - those are re-applied fresh on every
214 C<send()> call, this is not.
215  
216 =item retry_config
217  
218 Read-write hashref C<< { fail_response => $n, fail_status => $csv, delay
219 => $seconds } >>. The programmatic equivalent of
220 C<RETRY_FAIL_RESPONSE>/C<RETRY_FAIL_STATUS>/C<RETRY_DELAY> - set this
221 directly to configure retry behavior at construction without touching
222 process environment variables. A partial hashref is fine - any key you
223 omit falls back to that same env var's default (C<0>/C<''>/C<5>), not to
224 the environment variable itself. Re-applied at the start of every
225 C<send()> call, so changing it between calls takes effect on the next
226 one, not just at construction. See L</"ENVIRONMENT VARIABLES"> for what
227 each key does.
228  
229 =item json
230  
231 Read-write. The L<JSON::XS> instance C<kvp2json()> encodes through and
232 C<json_response()> decodes through, built lazily with
233 C<->canonical->allow_nonref>. Set this directly to inject a
234 differently-configured instance (e.g. one with C<->allow_blessed>
235 enabled) instead of the default. C<charset> is re-applied to it (via its
236 C<utf8>/C<latin1>/etc method) at the start of every C<kvp2json()>/
237 C<json_response()> call, not just when C<json> is first built, so a
238 C<charset> change takes effect on the next encode or decode even if
239 C<json> was already in use - this also applies to an injected custom
240 instance.
241  
242 =item debug_flags
243  
244 Read-write hashref C<< { in_out => $bool, send_out => $bool, response =>
245 $bool, response_header_only => $bool, response_if_fail => $bool } >>. The
246 programmatic equivalent of the C<DEBUG_*> env vars - set this directly to
247 enable debug output without touching process environment variables. Like
248 C<retry_config> and C<json>, it's re-applied at the start of every
249 C<send()> call, so changing it between calls takes effect on the next one,
250 not just at construction. See L</"ENVIRONMENT VARIABLES"> for what each
251 key does.
252  
253 =back
254  
255 =head1 ENVIRONMENT VARIABLES
256  
257 These environment variables expose the controls without changing the existing code.
258  
259 HTTP VARIABLES
260  
261 HTTP_USERNAME - basic auth username
262 HTTP_PASSWORD - basic auth password
263 HTTP_AUTH_TOKEN - basic auth token string
264 HTTP_CHARSET - content type charset. default utf8
265 HTTP_TIMEOUT - timeout the request in seconds. default 60 seconds.
266 SSL_VERIFY - verify ssl url. default is off
267  
268 DEBUG VARIABLES
269  
270 DEBUG_IN_OUT - print out request and response in string to STDERR
271 DEBUG_SEND_OUT - print out request in string to STDERR
272 DEBUG_RESPONSE - print out response in string to STDERR
273 DEBUG_RESPONSE_HEADER_ONLY - print out response header only without the body
274 DEBUG_RESPONSE_IF_FAIL - narrows DEBUG_IN_OUT/DEBUG_RESPONSE to only print
275 on a failed response. Does nothing by itself -
276 DEBUG_IN_OUT or DEBUG_RESPONSE must also be set.
277  
278 RETRY VARIABLES
279  
280 RETRY_FAIL_RESPONSE - number of time to retry if response comes back is failed. default 0 retry.
281 A negative value is clamped to 0 (no retry) rather than silently
282 making zero attempts.
283 RETRY_FAIL_STATUS - only retry if specified status code. e.g. 500,404
284 An empty entry (a doubled comma, stray whitespace) is
285 skipped rather than becoming a bogus always-false entry.
286 RETRY_DELAY - retry with wait time of 5 seconds in between, by default. A negative
287 value is clamped to 0 rather than reaching sleep() as-is.
288  
289 =head1 METHODS
290  
291 =head2 get / post / put / head / delete ($path, \%data, \%headers, \%events)
292  
293 Shorthand for C<send($METHOD, $path, \%data, \%headers, \%events)>. C<$path>
294 is appended to the C<base_url> attribute if one was given. Returns whatever
295 C<send()> returns - normally an L<HTTP::Response>.
296  
297 =head2 send($method, $path, \%data, \%headers, \%events)
298  
299 Builds and sends one HTTP request, retrying per L</"ENVIRONMENT VARIABLES">
300 if configured. C<%data> and C<%headers> are merged over C<pre_defined_data>
301 and C<pre_defined_headers>. C<%events> are the per-call callbacks documented
302 under C<new_request()> below. Sets and returns the C<last_response>
303 attribute.
304  
305 Any C<CODE> value in C<%data> (and separately, C<%headers>) is resolved by
306 calling it before the request is built - the mechanism the signed-request
307 example above uses for C<api_secret>. All of C<%data> resolves before any
308 of C<%headers> does, so a header callback reading an already-resolved data
309 value (as C<APIKEY>/C<Signature> do above) is safe and reliable. Two
310 C<CODE> values within the I<same> hash (two data keys, or two header keys)
311 resolve in sorted key order - if one reads a sibling key's value, only
312 rely on that if the sibling sorts first; there's no dependency-graph
313 resolution, just a fixed, predictable order.
314  
315 C<send()> shallow-copies C<\%data>/C<\%headers>/C<\%events> before doing
316 anything with them, so a hashref you pass in (and may reuse across other
317 calls) always comes back with the same top-level keys it went in with -
318 no merged-in C<pre_defined_*> keys or event-hook keys added by C<send()>'s
319 own machinery, and no key silently autovivified into existence just
320 because C<%events> mentioned it.
321  
322 This is a shallow copy, not a deep one, and deliberately so: a live
323 C<xBOOLEAN(\$flag)> marker depends on the exact same scalar reference
324 surviving unchanged, and deep-copying would clone it, breaking live
325 tracking. The consequence is that a I<value> which is itself a reference
326 - a nested hashref, an arrayref - is the same reference the caller
327 passed in, not a copy of it. A callback that reaches into C<%o{data}>
328 (or C<headers>/C<events>) and mutates a value at that depth mutates the
329 caller's own original data structure, exactly as if C<send()> had never
330 copied anything. Only the top level is protected.
331  
332 Passing C<< $events->{test_request_object} = 1 >> makes it return the built
333 L<HTTP::Request> instead of sending it - the way this module's own test
334 suite inspects what would have gone out.
335  
336 =head2 json_response
337  
338 Decode the C<last_response> body as JSON and return the resulting hashref.
339 Never dies - a missing response or invalid JSON comes back as
340 C<< { status => "error", error => $message } >> instead. C<charset> is
341 re-applied to C<json> at the start of every call, the same as
342 C<kvp2json()> does on the encode side, so a C<charset> change takes
343 effect on the next decode too.
344  
345 =head2 kvp_response
346  
347 Parse the C<last_response> body as a C<key=value&key=value> query string
348 and return it as a hashref. Returns C<{}> if no request has been made yet,
349 or the response body is empty. A key that repeats (the shape
350 C<kvp2str_each> produces when encoding an array-valued field) decodes to
351 an arrayref of every value seen, in order; a key seen once still decodes
352 to a plain scalar. Decodes both percent-encoding and the
353 C<application/x-www-form-urlencoded> convention of a literal C<+> meaning
354 a space (a genuinely percent-encoded literal C<+>, i.e. C<%2B>, still
355 decodes to C<+>) - this matters for a response body from any API, not
356 just one built by this module's own C<kvp2str_each>, which never emits a
357 raw C<+> itself. An empty C<&>-separated segment (a leading, trailing,
358 or doubled C<&>) is skipped rather than decoded into a bogus
359 C<< '' => undef >> entry.
360  
361 =head2 new_request(%options)
362  
363 Builds the L<HTTP::Request> for one call. This is where the C<%events>
364 callbacks passed to C<send()> are read: C<before_headers>, C<headers_keys> /
365 C<add_headers_keys> (which header keys to consider, in what order - both
366 paths' return value is deduplicated, first occurrence wins, order
367 otherwise preserved, not sorted; without that, a repeated key from either
368 would fire C<before_header>/C<after_header> once per repeat instead of
369 once, HAC-130), C<before_header>/C<after_header> keyed by header name, and
370 C<after_header_keys> - the hooks used to compute things like a signature
371 header from other data at build time. See F<t/04_callbacks.t> for a worked
372 example (API key + signature).
373  
374 C<%options> also accepts C<skip_headers>, a hashref of header names to
375 exclude from the request no matter what C<%headers> or the events above
376 say. Only reachable by calling C<new_request()> directly with it - C<send()>
377 never sets it, and setting it inside an C<%events> callback has no effect
378 (a callback receives a snapshot copy of C<%options>, not the one
379 C<new_request()> itself is iterating). See F<t/23_skip_headers.t>.
380  
381 L<HTTP::API::DataTypeMarker>'s C<xBOOLEAN()>/C<xCSV()> markers are only
382 unwrapped in body data (via C<kvp2json()>/C<kvp2str()>) - a header value
383 that's still a marker dies naming the offending header key, rather than
384 silently setting the header to Perl's default blessed-reference
385 stringification (C<"BOOL=ARRAY(0x...)">).
386  
387 =head2 get_content_type(%options)
388  
389 Resolves the effective content type for one call: the C<content_type>
390 attribute if set explicitly; otherwise C<application/x-www-form-urlencoded>
391 for a GET, or C<application/json; charset=$charset> for anything else.
392 Called internally by C<convert_data()>, C<prepare_request()>, and
393 C<new_request()> - there is normally no need to call this directly.
394  
395 =head2 convert_data(%options)
396  
397 Turn C<%options>'s C<data> hashref into the request body, according to
398 content type: JSON via C<kvp2json()> if the content type contains C<json>,
399 a query string via C<kvp2str()> if it is C<application/x-www-form-urlencoded>
400 optionally followed by a C<;>-separated parameter (e.g. C<< application/
401 x-www-form-urlencoded; charset=utf-8 >> - the same charset-suffix pattern
402 this module's own JSON default already uses). Any other content type
403 returns an empty string for empty data, or dies naming the content type -
404 there is no generic way to serialize arbitrary data into an arbitrary
405 content type.
406  
407 =head2 prepare_request(%options)
408  
409 Builds the bare L<HTTP::Request> (method, URL, content-type header) and
410 applies authentication: C<username>/C<password> take priority and are sent
411 as HTTP Basic auth via C<basic_authenticator()>; C<auth_token> is used only
412 if neither is set, and is sent as a raw C<Authorization> header value
413 verbatim (no C<Bearer> prefix is added for you - include it in the token
414 itself if the API expects one). C<auth_token> only supplies a I<default>
415 C<Authorization> header - an explicit one already present in C<%headers>
416 for this call (any casing: C<Authorization>, C<authorization>, ...) is
417 left alone rather than overwritten. Called by C<new_request()> - there is
418 normally no need to call this directly.
419  
420 =head2 basic_authenticator($request, $username, $password)
421  
422 Sets HTTP Basic auth on C<$request> via
423 C<< $request->headers->authorization_basic >>. Override this in a subclass
424 to change how basic auth is applied without touching the rest of request
425 building.
426  
427 =head2 kvp2json(%options) / kvp2str(%options)
428  
429 The two body encoders C<convert_data> dispatches to. C<kvp2json> walks
430 C<%options>'s C<data> hashref and JSON::XS-encodes it, resolving any
431 C<CODE> values by calling them and unwrapping L<HTTP::API::DataTypeMarker>'s
432 C<xBOOLEAN>-family markers into their JSON form; an C<xCSV>-marked value
433 has no special JSON handling and just JSON-encodes as an ordinary array
434 (there's no C<key=value&key=value> repetition problem in JSON for it to
435 solve). C<kvp2str> produces a C<key=value&key=value> query string instead,
436 with C<xCSV>-marked values joined by commas instead of repeated per key.
437 An empty arrayref value is omitted from C<kvp2str>'s output entirely (an
438 empty array has no C<key=value> representation), the same as a key
439 mapped to C<undef>/missing already is - including an empty array nested
440 inside an C<xCSV(...)> list, which contributes nothing to the joined
441 string rather than leaving a blank comma segment behind. An C<xCSV()>
442 with no elements at all is different: it still emits C<key=> (present,
443 empty value) rather than being omitted - there is no join-corruption
444 risk to avoid the way there is for a nested empty array, and C<key=> is
445 valid, parseable form data distinct from the key being absent.
446 Both respect an C<< $events->{keys} >> callback to control which keys are
447 included and in what order - its return value is deduplicated (first
448 occurrence wins, order otherwise preserved, not sorted) before use, so a
449 repeated key is processed once rather than once per occurrence; without
450 that, a C<CODE> value at that key would fire once per repeat and
451 C<kvp2str> would emit the same key twice with two different computed
452 values (HAC-129). Both also accept a C<skip_key> hashref in
453 C<%options> (same reachability caveat as C<new_request()>'s
454 C<skip_headers> above - only useful from a direct call, e.g. a C<data>
455 callback recursively re-invoking C<kvp2str()>/C<kvp2json()> on itself to
456 build its own value without infinite-looping on its own key; see
457 F<t/04_callbacks.t>) to exclude a key from the encoded body.
458  
459 C<kvp2str> alone also fires C<< $events->{before_sorting_keys} >> and
460 C<< $events->{after_sorting_keys} >>, each called with C<< keys => \@keys
461 >> - an arrayref of the field names about to be (respectively, just
462 were) sorted. Both are genuinely live: a callback that mutates
463 C<@$keys> in place (push/splice/grep out an element) changes what
464 C<kvp2str> actually encodes, as long as C<< $events->{keys} >> isn't
465 also set (which replaces C<@keys> outright, discarding
466 C<before_sorting_keys>' mutation). See F<t/21_before_events.t> and
467 F<t/33_before_sorting_keys_mutation.t>. C<kvp2json> has no equivalent
468 hook - its C<@keys> is either C<< $events->{keys} >>'s return value or
469 an unsorted C<keys %$data>, with no separate sorting step to hook into.
470  
471 C<kvp2json> encodes a numeric-looking string value as a genuine JSON
472 number rather than a quoted string - but only when doing so loses
473 nothing (stringifying the number back reproduces the original value
474 exactly). A value like C<"5"> becomes C<5>, but C<"00501"> (a US zip
475 code) or C<"5.0"> stays a string, since numifying either would silently
476 discard meaningful formatting. A value like C<"NaN">, C<"Inf">, or
477 C<"-Inf"> also stays a string even though it round-trips losslessly as
478 a Perl number - JSON has no valid representation for a non-finite
479 number, and numifying it would make C<kvp2json> emit the bareword
480 C<nan>/C<inf>/C<-inf>, which is not valid JSON and no parser (including
481 this module's own JSON::XS) can decode. C<kvp2str> never numifies at
482 all - a query string has no separate number/string type, so there was
483 never a reason to risk altering the original representation.
484  
485 =head2 kvp2json_each(%options) / kvp2str_each(%options)
486  
487 The per-value helpers C<kvp2json()>/C<kvp2str()> recurse into for each key
488 via C<%options>'s C<value> (and C<key> - the field's own key, available
489 to a C<CODE> value's callback via C<%options>; C<kvp2json_each> passes it
490 through at every level, including a nested hash value's own key, not
491 just the top-level field's). Resolves a C<CODE> value by calling it,
492 unwraps L<HTTP::API::DataTypeMarker> markers (C<xCSV>/C<xBOOLEAN> and
493 friends), and recurses into plain array values. There is normally no
494 need to call these directly - they exist as public methods so a
495 C<data>/C<value> callback can recursively re-invoke them on itself (see
496 C<kvp2json()>/C<kvp2str()> above).
497  
498 These two are not symmetric on invalid input, in two ways. First,
499 C<kvp2json_each> dies if a raw-bytes (non-UTF8-flagged) value is not
500 valid UTF-8, rather than silently corrupting it into C<U+FFFD>
501 replacement characters - JSON has no way to represent arbitrary bytes.
502 C<kvp2str_each> has no such restriction; a query string can carry any
503 byte sequence unescaped-safe via percent-encoding, so the same input
504 that dies in the JSON path passes through the form-urlencoded path
505 unchanged. Second, a plain hash value recurses in C<kvp2json_each> (JSON
506 has a native object type for it) but dies in C<kvp2str_each> - a query
507 string has no standard convention for representing a nested hash.
508  
509 C<undef> is also handled differently by nesting depth, deliberately left
510 this way rather than made symmetric. C<kvp2json()>'s own top-level loop
511 omits a key entirely when its value is C<undef> (see
512 L</"kvp2json(%options)"> above). A nested hash value's own
513 C<undef> sub-value is not: C<kvp2json_each>'s recursion into a hash value
514 has no equivalent skip step, so an C<undef> sub-value becomes an empty
515 JSON string (C<"">) rather than disappearing from the encoded object -
516 C<< kvp2json(data => { a => { x => 1, y => undef } }) >> encodes as
517 C<< {"a":{"x":1,"y":""}} >>, keeping C<y>, while the same C<undef> at the
518 top level would have dropped the key outright.
519  
520 Both die - with the same message, naming the offending ref type and
521 pointing at C<xBOOLEAN()> - on any other reference type neither of them
522 otherwise recognizes, most commonly a bare (not C<xBOOLEAN>-wrapped)
523 scalar ref: a value like C<< \$flag >> passed directly, typically from
524 forgetting to call C<xBOOLEAN(\$flag)> around it. Before this die was
525 added, C<kvp2str_each> silently stringified such a value as
526 C<SCALAR(0x...)>, and C<kvp2json_each> reached the same outcome only by
527 accident of JSON::XS itself refusing to encode an arbitrary scalar ref
528 - with a message that never mentioned this module's own vocabulary.
529  
530 C<kvp2str_each>'s C<%options> also accepts C<no_key>, set internally when
531 recursing into an ARRAY or C<xCSV> element: when true, the returned
532 fragment omits the leading C<key=> prefix (a plain scalar, C<xCSV>, and
533 C<xBOOLEAN>-marked value all honor this identically) so a CSV/array
534 element joins as a bare value rather than a spurious embedded
535 C<key=value> pair.
536  
537 Both encoders unwrap an C<xBOOLEAN(\$flag)> live scalar ref to whatever
538 C<$flag> currently holds, not just the C<0>/C<1> case C<xTRUE>/C<xFALSE>
539 use - a live ref that currently holds exactly (C<eq>, not merely
540 numerically C<==>) the string C<0> or C<1> still becomes a native JSON
541 boolean in C<kvp2json_each> (matching C<xTRUE>/C<xFALSE>; JSON::XS's own
542 convention only accepts that exact canonical form, not e.g. C<"01"> or
543 C<"1.0">), but any other live value - including one that is numerically
544 equal to C<0>/C<1> without being formatted exactly that way - encodes as
545 its own actual contents in both encoders alike, the same way a plain
546 (non-live) C<xBOOLEAN> value already did - including
547 C<kvp2json_each>'s invalid-UTF-8 die documented above, which a live
548 non-canonical value goes through exactly like the plain-scalar case
549 does. A live value that currently holds C<undef> is treated as an
550 empty string in both encoders, not C<undef> itself - it never reaches
551 the invalid-UTF-8 check (an empty string is trivially valid UTF-8) and
552 encodes as C<""> in JSON, matching how C<kvp2str_each> already handled
553 this case.
554  
555 A plain (non-live) C<xBOOLEAN> value - anything other than the
556 C<\1>/C<\0> shape C<xTRUE>/C<xFALSE> use, including a value passed to
557 C<xBOOLEAN()> directly with no leading backslash - goes through the
558 exact same invalid-UTF-8 die and lossless-numify treatment in
559 C<kvp2json_each> as the plain scalar branch: C<xBOOLEAN("5")> encodes as
560 the JSON number C<5>, and invalid UTF-8 bytes die with the same message
561 rather than silently corrupting into JSON, just like a plain scalar
562 value with the identical content would.
563  
564 C<xBOOLEAN()> only accepts a plain scalar or a scalar ref - wrapping
565 anything else (an arrayref, a hashref) dies with a clear message naming
566 the offending ref type in both encoders, rather than silently
567 stringifying it (e.g. into C<"HASH(0x...)">) the way an unmarked
568 reference of the wrong shape does elsewhere in this module (see
569 C<kvp2str_each>'s nested-hash die, above).
570  
571 =head1 LICENSE AND COPYRIGHT
572  
573 This software is Copyright (c) 2026 by Michael Vu.
574  
575 This is free software, licensed under:
576  
577 The MIT (X11) License
578  
579 The MIT License
580  
581 Permission is hereby granted, free of charge, to any person
582 obtaining a copy of this software and associated
583 documentation files (the "Software"), to deal in the Software
584 without restriction, including without limitation the rights to
585 use, copy, modify, merge, publish, distribute, sublicense,
586 and/or sell copies of the Software, and to permit persons to
587 whom the Software is furnished to do so, subject to the
588 following conditions:
589  
590 The above copyright notice and this permission notice shall
591 be included in all copies or substantial portions of the
592 Software.
593  
594 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT
595 WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
596 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
597 MERCHANTABILITY, FITNESS FOR A PARTICULAR
598 PURPOSE AND NONINFRINGEMENT. IN NO EVENT
599 SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
600 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
601 LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
602 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
603 CONNECTION WITH THE SOFTWARE OR THE USE OR
604 OTHER DEALINGS IN THE SOFTWARE.
605  
606 =cut
607  
608 95 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
609 95 ▶use HTTP::Headers;
Subroutine BEGIN: called CC=1 SCAR=0.0
610 95 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
611 95 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
612 95 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
613 95 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
614 95 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
615 95 ▶use URI::Escape qw( uri_escape uri_unescape );
Subroutine BEGIN: called CC=1 SCAR=0.0
616 95 ▶use Scalar::Util qw( looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
617 95 ▶use POSIX qw( isnan isinf );
Subroutine BEGIN: called CC=1 SCAR=0.0
618 95 ▶use HTTP::API::DataTypeMarker;
Subroutine BEGIN: called CC=1 SCAR=0.0
619  
620 95 extends 'Exporter';
621  
622 95 our @EXPORT = @HTTP::API::DataTypeMarker::EXPORT;
623  
624 95 has username => (
625 is => "rw",
626 lazy => 1,
627 builder => 1,
628 );
629  
630 78 ▶sub _build_username { _defor($ENV{HTTP_USERNAME}, '') }
Subroutine _build_username: called CC=1 SCAR=0.0
631  
632 95 has password => (
633 is => "rw",
634 lazy => 1,
635 builder => 1,
636 );
637  
638 78 ▶sub _build_password { _defor($ENV{HTTP_PASSWORD}, '') }
Subroutine _build_password: called CC=1 SCAR=0.0
639  
640 95 has auth_token => (
641 is => "rw",
642 lazy => 1,
643 builder => 1,
644 );
645  
646 81 ▶sub _build_auth_token { _defor($ENV{HTTP_AUTH_TOKEN}, '') }
Subroutine _build_auth_token: called CC=1 SCAR=0.0
647  
648 95 has base_url => (
649 is => "rw",
650 lazy => 1,
651 builder => 1,
652 );
653  
654 84 ▶sub _build_base_url {}
Subroutine _build_base_url: called CC=1 SCAR=0.0
655  
656 95 has last_response => (
657 is => "rw",
658 lazy => 1,
659 builder => 1,
660 );
661  
662 2 ▶sub _build_last_response {}
Subroutine _build_last_response: called CC=1 SCAR=0.0
663  
664 95 has charset => (
665 is => "rw",
666 lazy => 1,
667 builder => 1,
668 );
669  
670 54 ▶sub _build_charset { _defor($ENV{HTTP_CHARSET}, "utf8") }
Subroutine _build_charset: called CC=1 SCAR=0.0
671  
672 95 has browser_id => (
673 is => "rw",
674 lazy => 1,
675 builder => 1,
676 );
677  
678 91 ▶sub _build_browser_id {
Subroutine _build_browser_id: called CC=1 SCAR=0.0
679 91 my $ver = _defor($HTTP::API::Client::VERSION, 'dev');
680 91 return "HTTP API Client v$ver";
681 }
682  
683 95 has content_type => (
684 is => "rw",
685 lazy => 1,
686 builder => 1,
687 );
688  
689 61 ▶sub _build_content_type {}
Subroutine _build_content_type: called CC=1 SCAR=0.0
690  
691 329 ▶sub get_content_type {
Subroutine get_content_type: called CC=3 SCAR=11.0
Pod documented
692 329 my ($self, %o) = @_;
693 329 my $content_type = $self->content_type;
694  
695 329 ▶ if ($content_type) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type) 99 230 329
696 99 return $content_type;
697 }
698  
699 230 my $method = ${$o{method}};
700  
701 230 ▶ if ($method eq 'GET') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "GET") 198 32 230
702 198 return 'application/x-www-form-urlencoded';
703 }
704  
705 32 my $charset = $self->charset;
706 32 return "application/json; charset=$charset";
707 }
708  
709 95 has engine => (
710 is => "ro",
711 lazy => 1,
712 builder => 1,
713 );
714  
715 90 ▶sub _build_engine {"LWP::UserAgent"}
Subroutine _build_engine: called CC=1 SCAR=0.0
716  
717 95 has ua => (
718 is => "rw",
719 lazy => 1,
720 builder => 1,
721 );
722  
723 73 ▶sub _build_ua {
Subroutine _build_ua: called CC=2 SCAR=6.9
724 73 my ($self) = @_;
725 73 my $ssl_verify = $self->ssl_verify;
726 73 my $engine = $self->engine;
727  
728 73 my $ua;
729  
730 73 ▶ if ( $engine eq "LWP::UserAgent" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine eq 'LWP::UserAgent') { } 72 1 73
731 72 $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => $ssl_verify } );
732 72 $ua->agent( $self->browser_id );
733 72 $ua->timeout( $self->timeout );
734 }
735 else {
736 1 $ua = $self->$engine($ssl_verify);
737 }
738  
739 73 return $ua;
740 }
741  
742 95 has ssl_verify => (
743 is => "rw",
744 lazy => 1,
745 builder => 1,
746 );
747  
748 73 ▶sub _build_ssl_verify {
Subroutine _build_ssl_verify: called CC=1 SCAR=0.0
749 73 return _defor( $ENV{SSL_VERIFY}, 0 );
750 }
751  
752 # send() does NOT read this attribute - since HAC-068 it calls
753 # $self->_build_retry directly on every call, so retry_config changes
754 # take effect live. This accessor is kept only for external callers who
755 # already read $api->retry directly; it's a one-time snapshot at
756 # whatever moment it's first accessed, not a live view of send()'s
757 # actual behavior.
758 95 has retry => (
759 is => "rw",
760 lazy => 1,
761 builder => 1,
762 );
763  
764 113 ▶sub _build_retry {
Subroutine _build_retry: called CC=5 SCAR=16.1
765 113 my ($self) = @_;
766 113 my %retry = %{ _defor($self->retry_config, {}) };
767 113 my $count = _defor( $retry{fail_response}, 0 );
768 113 ▶ $count = 0 if looks_like_number($count) && $count < 0;
Branch: 1 branch
BranchTrueFalseTotal
if &looks_like_number($count) and $count < 0 1 112 113
Condition100%3/3
&looks_like_number($count) and $count < 0
!ll&&!rl&&r
11111
MC/DC100%2/2
&looks_like_number($count) and $count < 0
&looks_like_number($count) $count < 0
Truth table100%3/3
A and B
A= &looks_like_number($count)B= $count < 0
ABresult
0X0
100
111
769 13 my %status = map { $_ => 1 }
770 15 grep { length }
771 15 map { s/^\s+|\s+$//g; $_ }
772 113 split /,/, _defor($retry{fail_status}, '');
773  
774 113 my $delay = _defor( $retry{delay}, 5 );
775 113 ▶ $delay = 0 if looks_like_number($delay) && $delay < 0;
Branch: 1 branch
BranchTrueFalseTotal
if &looks_like_number($delay) and $delay < 0 3 110 113
Condition100%3/3
&looks_like_number($delay) and $delay < 0
!ll&&!rl&&r
11093
MC/DC100%2/2
&looks_like_number($delay) and $delay < 0
&looks_like_number($delay) $delay < 0
Truth table100%3/3
A and B
A= &looks_like_number($delay)B= $delay < 0
ABresult
0X0
100
111
776  
777 return {
778 113 count => $count,
779 status => \%status,
780 delay => $delay,
781 };
782 }
783  
784 95 has retry_config => (
785 is => "rw",
786 lazy => 1,
787 builder => 1,
788 );
789  
790 91 ▶sub _build_retry_config {
Subroutine _build_retry_config: called CC=1 SCAR=0.0
791 return {
792 fail_response => _defor( $ENV{RETRY_FAIL_RESPONSE}, 0 ),
793 fail_status => _defor($ENV{RETRY_FAIL_STATUS}, ''),
794 91 delay => _defor( $ENV{RETRY_DELAY}, 5 ),
795 };
796 }
797  
798 95 has timeout => (
799 is => "rw",
800 lazy => 1,
801 builder => 1,
802 );
803  
804 90 ▶sub _build_timeout { _defor($ENV{HTTP_TIMEOUT}, 60) }
Subroutine _build_timeout: called CC=1 SCAR=0.0
805  
806 95 has json => (
807 is => "rw",
808 lazy => 1,
809 builder => 1,
810 );
811  
812 33 ▶sub _build_json {
Subroutine _build_json: called CC=1 SCAR=0.0
813 33 my ($self) = @_;
814 33 return _apply_charset( JSON::XS->new->canonical->allow_nonref, $self->charset );
815 }
816  
817 95 ▶sub _apply_charset {
Subroutine _apply_charset: called CC=2 SCAR=6.9
818 95 my ($json, $charset) = @_;
819 95 ▶ eval { $json->$charset; 1 } or die "Unsupported charset '$charset': $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $json->$charset; 1 } } or die "Unsupported charset '${charset}': $@" 93 2 95
820 93 return $json;
821 }
822  
823 95 has debug_flags => (
824 is => "rw",
825 lazy => 1,
826 builder => 1,
827 );
828  
829 91 ▶sub _build_debug_flags {
Subroutine _build_debug_flags: called CC=1 SCAR=0.0
830 return {
831 in_out => $ENV{DEBUG_IN_OUT},
832 send_out => $ENV{DEBUG_SEND_OUT},
833 response => $ENV{DEBUG_RESPONSE},
834 response_header_only => $ENV{DEBUG_RESPONSE_HEADER_ONLY},
835 response_if_fail => $ENV{DEBUG_RESPONSE_IF_FAIL},
836 91 };
837 }
838  
839 95 has pre_defined_data => (
840 is => "rw",
841 lazy => 1,
842 builder => 1,
843 );
844  
845 87 ▶sub _build_pre_defined_data {{}}
Subroutine _build_pre_defined_data: called CC=1 SCAR=0.0
846  
847 95 has pre_defined_headers => (
848 is => "rw",
849 lazy => 1,
850 builder => 1,
851 );
852  
853 90 ▶sub _build_pre_defined_headers {{}}
Subroutine _build_pre_defined_headers: called CC=1 SCAR=0.0
854  
855 95 has pre_defined_events => (
856 is => "rw",
857 lazy => 1,
858 builder => 1,
859 );
860  
861 90 ▶sub _build_pre_defined_events {{}}
Subroutine _build_pre_defined_events: called CC=1 SCAR=0.0
862  
863 75 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
864 75 my ($self, @args) = @_;
865 75 return $self->send( GET => @args );
866 }
867  
868 23 ▶sub post {
Subroutine post: called CC=1 SCAR=0.0
Pod documented
869 23 my ($self, @args) = @_;
870 23 return $self->send( POST => @args );
871 }
872  
873 1 ▶sub put {
Subroutine put: called CC=1 SCAR=0.0
Pod documented
874 1 my ($self, @args) = @_;
875 1 return $self->send( PUT => @args );
876 }
877  
878 1 ▶sub head {
Subroutine head: called CC=1 SCAR=0.0
Pod documented
879 1 my ($self, @args) = @_;
880 1 return $self->send( HEAD => @args );
881 }
882  
883 1 ▶sub delete {
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
884 1 my ($self, @args) = @_;
885 1 return $self->send( DELETE => @args );
886 }
887  
888 206 ▶sub _execute_callbacks {
Subroutine _execute_callbacks: called CC=4 SCAR=13.9
889 206 my ($self, $type, %options) = @_;
890  
891 206 my $sth = $options{$type};
892  
893 206 for my $key (sort keys %$sth) {
894 155 my $callback = $sth->{$key};
895 155 ▶ next if !defined $callback;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $callback 2 153 155
896 153 ▶ next if !UNIVERSAL::isa($callback, 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($callback, "CODE") 136 17 153
897 17 $sth->{$key} = $self->$callback(key => $key, %options);
898 }
899 }
900  
901 103 ▶sub send {
Subroutine send: called CC=24 SCAR=31.8
Pod documented
902 103 my ($self, $method, $path,
903 $data, $headers, $events) = @_;
904  
905 103 $method = uc $method;
906 103 $path = _defor( $path, '' );
907 103 $data = { %{ _defor( $data, {} ) } };
908 103 $headers = { %{ _defor( $headers, {} ) } };
909 103 $events = { %{ _defor( $events, {} ) } };
910  
911 103 my $base_url = $self->base_url;
912 103 ▶ my $url = $base_url ? $base_url . $path : $path;
Branch: 1 branch
BranchTrueFalseTotal
$base_url ? : 13 90 103
913 103 my $ua = $self->ua;
914 103 ▶ $ua->agent( $self->browser_id ) if $ua->can('agent');
Branch: 1 branch
BranchTrueFalseTotal
if $ua->can("agent") 102 1 103
915 103 ▶ $ua->timeout( $self->timeout ) if $ua->can('timeout');
Branch: 1 branch
BranchTrueFalseTotal
if $ua->can("timeout") 102 1 103
916 103 ▶ $ua->ssl_opts( verify_hostname => $self->ssl_verify ) if $ua->can('ssl_opts');
Branch: 1 branch
BranchTrueFalseTotal
if $ua->can("ssl_opts") 83 20 103
917 103 my $retry_settings = $self->_build_retry;
918 103 my $retry_count = _defor( $retry_settings->{count}, 1 );
919 103 my $retry_delay = _defor( $retry_settings->{delay}, 5 );
920 103 my %retry_status = %{ _defor($retry_settings->{status}, {}) };
921 103 my %debug = %{ _defor($self->debug_flags, {}) };
922 103 my $eng = $self->engine;
923  
924 103 ▶ if ( my $pd = $self->pre_defined_data ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pd = $self->pre_defined_data) 103 0 103
925 103 %$data = ( %$pd, %$data );
926 }
927  
928 103 ▶ if ( my $ph = $self->pre_defined_headers ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ph = $self->pre_defined_headers) 103 0 103
929 103 %$headers = ( %$ph, %$headers );
930 }
931  
932 103 ▶ if ( my $pe = $self->pre_defined_events ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pe = $self->pre_defined_events) 103 0 103
933 103 %$events = ( %$pe, %$events );
934 }
935  
936 103 my %options = (
937 method => \$method,
938 url => \$url,
939 path => \$path,
940 data => $data,
941 headers => $headers,
942 events => $events,
943 );
944  
945 103 $self->_execute_callbacks(data => %options);
946 103 $self->_execute_callbacks(headers => %options);
947  
948 103 my $response;
949  
950 RETRY:
951 103 foreach my $retry ( 0 .. $retry_count ) {
952 111 my $started_time = time;
953 111 my $req;
954  
955 111 ▶ if ( $eng eq 'LWP::UserAgent' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eng eq 'LWP::UserAgent') { } 110 1 111
956 110 $req = $self->new_request( %options );
957  
958 104 ▶ if ($events->{test_request_object}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($events->{"test_request_object"}) 77 27 104
959 77 return $req;
960 }
961  
962 27 $response = $ua->request($req);
963 }
964 else {
965 1 die "Unsupported engine: $eng - only LWP::UserAgent is currently wired up in send()\n";
966 }
967  
968 27 ▶ my $suppress_on_success = $debug{response_if_fail} && $response->is_success;
Condition100%3/3
$debug{'response_if_fail'} && $response->is_success
!ll&&!rl&&r
2223
MC/DC100%2/2
$debug{'response_if_fail'} && $response->is_success
$debug{'response_if_fail'} $response->is_success
Truth table100%3/3
A && B
A= $debug{'response_if_fail'}B= $response->is_success
ABresult
0X0
100
111
969  
970 27 ▶ if ( $debug{send_out} || ( $debug{in_out} && !$suppress_on_success ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($debug{"send_out"} or $debug{"in_out"} and not $suppress_on_success) 8 19 27
Condition100%6/6
$debug{"send_out"} or $debug{"in_out"} and not $suppress_on_success
l!l&&r!l&&!r
5319
$debug{"in_out"} and not $suppress_on_success
!ll&&!rl&&r
1813
MC/DC100%3/3
$debug{"send_out"} or $debug{"in_out"} and not $suppress_on_success
$debug{"send_out"} $debug{"in_out"} not $suppress_on_success
Truth table100%4/4
A or B and not(C)
A= $debug{"send_out"}B= $debug{"in_out"}C= not $suppress_on_success
ABCresult
1XX1
0111
00X0
0100
971 8 print STDERR "-- REQUEST --\n";
972 8 ▶ if ( $retry_count && $retry ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry_count and $retry) 2 6 8
Condition100%3/3
$retry_count and $retry
!ll&&!rl&&r
512
MC/DC100%2/2
$retry_count and $retry
$retry_count $retry
Truth table100%3/3
A and B
A= $retry_countB= $retry
ABresult
0X0
100
111
973 2 print STDERR "-- RETRY $retry of $retry_count\n";
974 }
975 ## $response->request is the LAST request LWP::UserAgent sent, which
976 ## after a redirect (default-on for GET/HEAD) is a different object
977 ## pointing at the redirected-to URL - not the request this call
978 ## actually issued. Use $req, the one we built and passed in.
979 8 print STDERR $req->as_string;
980 8 print STDERR "\n";
981 }
982  
983 27 my $debug_response = _defor($debug{in_out}, $debug{response});
984  
985 27 ▶ $debug_response = 0
Branch: 1 branch
BranchTrueFalseTotal
if $suppress_on_success 3 24 27
986 if $suppress_on_success;
987  
988 27 ▶ if ($debug_response) {
Branch: 1 branch
BranchTrueFalseTotal
if ($debug_response) 6 21 27
989 6 my $used_time = time - $started_time;
990  
991 6 print STDERR "-- RESPONSE $used_time sec(s) --\n";
992  
993 print STDERR $debug{response_header_only}
994 6 ▶ ? $response->headers->as_string
Branch: 1 branch
BranchTrueFalseTotal
$debug{'response_header_only'} ? : 1 5 6
995 : $response->as_string;
996  
997 6 print STDERR ( "-" x 80 ) . "\n";
998 }
999  
1000 last RETRY ## request is success, not further for retry
1001 27 ▶ if $response->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $response->is_success 8 19 27
1002  
1003 last RETRY ## no attempts left, don't sleep for a retry that won't happen
1004 19 ▶ if $retry >= $retry_count;
Branch: 1 branch
BranchTrueFalseTotal
if $retry >= $retry_count 10 9 19
1005  
1006 9 ▶ if ( !%retry_status ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%retry_status) 4 5 9
1007 4 sleep $retry_delay;
1008 ## no retry pattern at all then just retry
1009 4 next RETRY;
1010 }
1011  
1012 5 ▶ $retry_status{ $response->code }
Branch: 1 branch
BranchTrueFalseTotal
$retry_status{$response->code} or last RETRY 4 1 5
1013 or
1014 last RETRY; ## status code not in RETRY_FAIL_STATUS, just stop retry
1015  
1016 4 sleep $retry_delay;
1017 4 next RETRY;
1018 }
1019  
1020 19 return $self->last_response($response);
1021 }
1022  
1023 5 ▶sub json_response {
Subroutine json_response: called CC=1 SCAR=0.0
Pod documented
1024 5 my ($self) = @_;
1025  
1026 5 ▶ my $response = try {
Subroutine __ANON__: called CC=1 SCAR=0.0
1027 5 my $content = _defor($self->last_response->decoded_content, '{}');
1028 4 my $json = _apply_charset( $self->json, $self->charset );
1029 4 $json->decode($content);
1030 }
1031 2 ▶ catch {
Subroutine __ANON__: called CC=1 SCAR=0.0
1032 2 my $error = $_;
1033 2 { status => "error", error => $error };
1034 5 };
1035  
1036 5 return $response;
1037 }
1038  
1039 13 ▶sub kvp_response {
Subroutine kvp_response: called CC=7 SCAR=19.5
Pod documented
1040 13 my ($self) = @_;
1041  
1042 13 ▶ my $response = $self->last_response
Branch: 1 branch
BranchTrueFalseTotal
my $response = $self->last_response or return {} 12 1 13
1043 or return {};
1044  
1045 12 ▶ my $content = $response->decoded_content
Branch: 1 branch
BranchTrueFalseTotal
my $content = $response->decoded_content or return {} 11 1 12
1046 or return {};
1047  
1048 11 my %data;
1049 11 for my $pair ( split /&/, $content ) {
1050 22 ▶ next if $pair eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $pair eq "" 2 20 22
1051 20 my ( $k, $v ) = map { ( my $s = $_ ) =~ tr/+/ /; uri_unescape($s) } split /=/, $pair, 2;
1052 20 ▶ if ( exists $data{$k} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data{$k}) { } 5 15 20
1053 5 ▶ $data{$k} = [ $data{$k} ] unless ref $data{$k} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data{$k} eq "ARRAY" 3 2 5
1054 5 push @{ $data{$k} }, $v;
1055 }
1056 else {
1057 15 $data{$k} = $v;
1058 }
1059 }
1060  
1061 11 return \%data;
1062 }
1063  
1064 111 ▶sub new_request {
Subroutine new_request: called CC=20 SCAR=30.0
Pod documented
1065 111 my ($self, %o) = @_;
1066  
1067 111 my ($method, $url) = map { $$_ } @o{qw(method url)};
1068  
1069 111 my ($data, $headers, $events) = @o{qw(data headers events)};
1070  
1071 111 my $content_type = $self->get_content_type(%o);
1072  
1073 111 my $content = $self->convert_data(%o);
1074  
1075 108 ▶ if ($content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content) 45 63 108
1076 45 ▶ if ($self->charset eq 'utf8') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->charset eq "utf8") 44 1 45
1077 44 $content = _tune_utf8($content);
1078 }
1079 }
1080  
1081 108 my $request;
1082  
1083 108 ▶ if ($method eq 'GET') {
Branch: 2 branches
BranchTrueFalseTotal
if ($method eq 'GET') { } 84 24 108
elsif ($content) { } 22 2 24
1084 84 ▶ if ($content_type !~ m{^application/x-www-form-urlencoded(?:;|$)}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $content_type =~ m[^application/x-www-form-urlencoded(?:;|$)]) { } 1 83 84
elsif ($content) { } 22 61 83
1085 1 die "Unable to create a get request with content_type: $content_type\n";
1086 }
1087 elsif ($content) {
1088 22 ▶ if ($url =~ m/\?/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($url =~ /\?/) { } 1 21 22
1089 1 $request = $self->prepare_request(%o, url => \"$url&$content");
1090 }
1091 else {
1092 21 $request = $self->prepare_request(%o, url => \"$url?$content");
1093 }
1094 }
1095 else {
1096 61 $request = $self->prepare_request(%o);
1097 }
1098 }
1099 elsif ($content) {
1100 22 $request = $self->prepare_request(%o);
1101 22 $request->content($content);
1102 }
1103 else {
1104 2 $request = $self->prepare_request(%o);
1105 }
1106  
1107 107 %o = (%o,
1108 request => $request,
1109 content => \$content,
1110 );
1111  
1112 107 ▶ if (my $do = $events->{before_headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"before_headers"}) 1 106 107
1113 1 $self->$do(%o);
1114 }
1115  
1116 107 my @keys;
1117  
1118 107 ▶ if (my $keys = $events->{headers_keys}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $keys = $events->{'headers_keys'}) { } 4 103 107
elsif (my $add = $events->{'add_headers_keys'}) { } 2 101 103
1119 4 my %seen;
1120 4 @keys = grep { !$seen{$_}++ } $self->$keys(%o);
1121 }
1122 elsif (my $add = $events->{add_headers_keys}) {
1123 2 my %seen;
1124 2 @keys = sort grep { !$seen{$_}++ } $self->$add(%o), keys %$headers;
1125 }
1126 else {
1127 101 @keys = sort keys %$headers;
1128 }
1129  
1130 107 foreach my $key ( @keys ) {
1131 31 ▶ if (my $do = $events->{before_header}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"before_header"}{$key}) 3 28 31
1132 3 $headers->{$key} = $self->$do(%o);
1133 }
1134  
1135 31 ▶ next if $o{skip_headers}{$key} || !exists $headers->{$key} || !defined $headers->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $o{"skip_headers"}{$key} or not exists $headers->{$key} or not defined $headers->{$key} 3 28 31
Condition100%6/6
$o{"skip_headers"}{$key} or not exists $headers->{$key} or not defined $headers->{$key}
l!l&&r!l&&!r
2128
$o{"skip_headers"}{$key} or not exists $headers->{$key}
l!l&&r!l&&!r
1129
MC/DC100%3/3
$o{"skip_headers"}{$key} or not exists $headers->{$key} or not defined $headers->{$key}
$o{"skip_headers"}{$key} not exists $headers->{$key} not defined $headers->{$key}
Truth table100%4/4
A or not(B) or not(C)
A= $o{"skip_headers"}{$key}B= not exists $headers->{$key}C= not defined $headers->{$key}
ABCresult
1XX1
01X1
0011
0000
1136  
1137 die "Header '$key' is an xBOOLEAN()/xCSV() marker - those are only "
1138 . "supported in body data (kvp2json/kvp2str), not headers\n"
1139 if ref $headers->{$key} eq 'HTTP::API::DataTypeMarker::BOOL'
1140 28 ▶ || ref $headers->{$key} eq 'HTTP::API::DataTypeMarker::CSV';
Branch: 1 branch
BranchTrueFalseTotal
if ref $headers->{$key} eq "HTTP::API::DataTypeMarker::BOOL" or ref $headers->{$key} eq "HTTP::API::DataTypeMarker::CSV" 2 26 28
Condition100%3/3
ref $headers->{$key} eq "HTTP::API::DataTypeMarker::BOOL" or ref $headers->{$key} eq "HTTP::API::DataTypeMarker::CSV"
l!l&&r!l&&!r
1126
MC/DC100%2/2
ref $headers->{$key} eq "HTTP::API::DataTypeMarker::BOOL" or ref $headers->{$key} eq "HTTP::API::DataTypeMarker::CSV"
ref $headers->{$key} eq "HTTP::API::DataTypeMarker::BOOL" ref $headers->{$key} eq "HTTP::API::DataTypeMarker::CSV"
Truth table100%3/3
A or B
A= ref $headers->{$key} eq "HTTP::API::DataTypeMarker::BOOL"B= ref $headers->{$key} eq "HTTP::API::DataTypeMarker::CSV"
ABresult
1X1
011
000
1141  
1142 26 $request->header( $key => _encode_if_utf8_flagged( $headers->{$key} ) );
1143  
1144 26 ▶ if (my $do = $events->{after_header}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"after_header"}{$key}) 5 21 26
1145 5 $self->$do(%o);
1146 }
1147 }
1148  
1149 105 ▶ if (my $do = $events->{after_header_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"after_header_keys"}) 1 104 105
1150 1 $self->$do(%o);
1151 }
1152  
1153 105 return $request;
1154 }
1155  
1156 107 ▶sub prepare_request {
Subroutine prepare_request: called CC=5 SCAR=16.1
Pod documented
1157 107 my ($self, %o) = @_;
1158  
1159 107 my ($method, $url) = map { $$_ } @o{qw(method url)};
1160  
1161 107 my ($headers) = @o{qw(headers)};
1162  
1163 107 my $request = HTTP::Request->new( $method => $url );
1164  
1165 107 $request->content_type($self->get_content_type(%o));
1166  
1167 107 my ($u, $p, $at) = map { _defor($self->$_, '') }
1168 qw(username password auth_token);
1169  
1170 107 ▶ if (length($u) || length($p)) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $u or length $p) { } 8 99 107
elsif (length $at) { } 5 94 99
Condition100%3/3
length $u or length $p
l!l&&r!l&&!r
7199
MC/DC100%2/2
length $u or length $p
length $u length $p
Truth table100%3/3
A or B
A= length $uB= length $p
ABresult
1X1
011
000
1171 8 $self->basic_authenticator( $request,
1172 _encode_if_utf8_flagged($u), _encode_if_utf8_flagged($p) );
1173 }
1174 elsif (length($at)) {
1175 $headers->{authorization} = $at
1176 5 ▶ unless grep { lc($_) eq 'authorization' } keys %$headers;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {lc $_ eq "authorization";} keys %$headers 3 2 5
1177 }
1178  
1179 107 return $request;
1180 }
1181  
1182 47 ▶sub _tune_utf8 {
Subroutine _tune_utf8: called CC=1 SCAR=0.0
1183 47 my ($content) = @_;
1184  
1185 47 my $req = HTTP::Request->new( POST => "http://find-encoding.com" );
1186  
1187 47 ▶ try {
Subroutine __ANON__: called CC=1 SCAR=0.0
1188 47 $req->content($content);
1189 }
1190 2 ▶ catch {
Subroutine __ANON__: called CC=2 SCAR=6.9
1191 2 my $error = $_;
1192 2 ▶ if ( $error =~ /content must be bytes/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error =~ /content must be bytes/) 1 1 2
1193 1 eval { $content = Encode::encode( utf8 => $content ); };
1194 }
1195 47 };
1196 47 return $content;
1197 }
1198  
1199 166 ▶sub _should_skip_key {
Subroutine _should_skip_key: called CC=3 SCAR=11.0
1200 166 my (%o) = @_;
1201 166 my ($key, $data) = @o{qw(key data)};
1202 166 ▶ return $o{skip_key}{$key} || !exists $data->{$key} || !defined $data->{$key};
Condition83%5/6
$o{'skip_key'}{$key} || !exists $data->{$key} || !defined($data->{$key})
l!l&&r!l&&!r
11164
$o{"skip_key"}{$key} or not exists $data->{$key}
l!l&&r!l&&!r
10165
MC/DC66%2/3
$o{'skip_key'}{$key} || !exists $data->{$key} || !defined($data->{$key})
$o{"skip_key"}{$key} not exists $data->{$key} !defined($data->{$key})
Truth table75%3/4
A or not(B) || not(C)
A= $o{"skip_key"}{$key}B= not exists $data->{$key}C= !defined($data->{$key})
ABCresult
1XX1
01X1
0011
0000
1203 }
1204  
1205 356 ▶sub _encode_if_utf8_flagged {
Subroutine _encode_if_utf8_flagged: called CC=2 SCAR=6.9
1206 356 my ($v) = @_;
1207 356 ▶ return utf8::is_utf8($v) ? Encode::encode( utf8 => $v ) : $v;
Branch: 1 branch
BranchTrueFalseTotal
utf8::is_utf8($v) ? : 6 350 356
1208 }
1209  
1210 314 ▶sub _uri_escape_bytes_or_chars {
Subroutine _uri_escape_bytes_or_chars: called CC=1 SCAR=0.0
1211 314 my ($v) = @_;
1212 314 return uri_escape( _encode_if_utf8_flagged($v) );
1213 }
1214  
1215 69 ▶sub _json_validate_utf8 {
Subroutine _json_validate_utf8: called CC=3 SCAR=11.0
1216 69 my ($v) = @_;
1217 69 ▶ return $v if utf8::is_utf8($v);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($v) 4 65 69
1218 65 my $decoded = eval { Encode::decode( utf8 => $v, Encode::FB_CROAK ) };
1219 65 ▶ die sprintf(
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decoded 4 61 65
1220 "kvp2json_each: value is not valid UTF-8, refusing to silently corrupt it into JSON (raw bytes: %v02x)\n",
1221 $v
1222 ) if !defined $decoded;
1223 61 return $decoded;
1224 }
1225  
1226 65 ▶sub _numify_if_lossless {
Subroutine _numify_if_lossless: called CC=5 SCAR=16.1
1227 65 my ($v) = @_;
1228 65 ▶ return $v if !looks_like_number($v);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($v) 18 47 65
1229 # NaN/Infinity have no valid JSON representation - JSON::XS's utf8-mode
1230 # encoder emits them as the bareword nan/inf/-inf, which is not valid
1231 # JSON. Leave the original string untouched rather than numifying into
1232 # a token no JSON parser (including JSON::XS itself) can decode.
1233 47 ▶ return $v if isnan($v + 0) || isinf($v + 0);
Branch: 1 branch
BranchTrueFalseTotal
if isnan($v + 0) or isinf($v + 0) 5 42 47
Condition100%3/3
isnan($v + 0) or isinf($v + 0)
l!l&&r!l&&!r
2342
MC/DC100%2/2
isnan($v + 0) or isinf($v + 0)
isnan($v + 0) isinf($v + 0)
Truth table100%3/3
A or B
A= isnan($v + 0)B= isinf($v + 0)
ABresult
1X1
011
000
1234 # Compare against a throwaway stringified copy, not $v+0 itself - comparing
1235 # a number with eq caches a string form on that same scalar (SvPOK), and
1236 # JSON::XS then encodes it as a JSON string instead of a JSON number.
1237 42 my $stringified = ($v + 0) . '';
1238 42 ▶ return $v eq $stringified ? $v + 0 : $v;
Branch: 1 branch
BranchTrueFalseTotal
$v eq $stringified ? : 37 5 42
1239 }
1240  
1241 111 ▶sub convert_data {
Subroutine convert_data: called CC=4 SCAR=13.9
Pod documented
1242 111 my ($self, %o) = @_;
1243  
1244 111 my ($data, $events) = @o{qw(data events)};
1245  
1246 111 my $content_type = $self->get_content_type(%o);
1247  
1248 111 ▶ if ($content_type =~ m/json/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($content_type =~ /json/) { } 17 94 111
elsif ($content_type =~ m[^application/x-www-form-urlencoded(?:;|$)]) { } 92 2 94
1249 17 return $self->kvp2json(%o);
1250 }
1251 elsif ($content_type =~ m{^application/x-www-form-urlencoded(?:;|$)}) {
1252 92 return $self->kvp2str(%o);
1253 }
1254 else {
1255 2 ▶ return '' if !%$data;
Branch: 1 branch
BranchTrueFalseTotal
unless %$data 1 1 2
1256 1 die "Unable to convert data for content_type: $content_type\n";
1257 }
1258 }
1259  
1260 58 ▶sub kvp2json {
Subroutine kvp2json: called CC=5 SCAR=16.1
Pod documented
1261 58 my ($self, %o) = @_;
1262  
1263 58 my ($data, $events) = @o{qw(data events)};
1264  
1265 58 my $json = _apply_charset( $self->json, $self->charset );
1266  
1267 57 my @keys;
1268  
1269 57 ▶ if (my $do = $events->{keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{'keys'}) { } 2 55 57
1270 2 my %seen;
1271 2 @keys = grep { !$seen{$_}++ } $self->$do(%o);
1272 }
1273 else {
1274 55 @keys = keys %$data;
1275 }
1276  
1277 57 my %data = ();
1278  
1279 57 foreach my $key(@keys) {
1280 69 ▶ if ($events->{not_include}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($events->{"not_include"}{$key}) 1 68 69
1281 next
1282 1 }
1283 68 ▶ next if _should_skip_key(%o, key => $key);
Branch: 1 branch
BranchTrueFalseTotal
if _should_skip_key(%o, "key", $key) 1 67 68
1284 67 $data{$key} = $self->kvp2json_each(%o, key => $key, value => $data->{$key});
1285 }
1286  
1287 51 return $json->encode(\%data);
1288 }
1289  
1290 101 ▶sub kvp2json_each {
Subroutine kvp2json_each: called CC=12 SCAR=24.8
Pod documented
1291 101 my ($self, %o) = @_;
1292  
1293 101 my ($v) = map { _defor($_, '') } @o{qw( value )};
1294  
1295 101 ▶ if (UNIVERSAL::isa($v, 'CODE')) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($v, "CODE")) 9 92 101
1296 9 $v = $self->$v(%o);
1297 }
1298  
1299 101 ▶ if (!ref $v) {
Branch: 4 branches
BranchTrueFalseTotal
if (not ref $v) { } 58 43 101
elsif (ref $v eq 'HTTP::API::DataTypeMarker::BOOL') { } 27 16 43
elsif (UNIVERSAL::isa($v, 'ARRAY')) { } 11 5 16
elsif (UNIVERSAL::isa($v, 'HASH')) { } 4 1 5
1300 58 return _numify_if_lossless( _json_validate_utf8($v) );
1301 }
1302 elsif (ref $v eq 'HTTP::API::DataTypeMarker::BOOL') {
1303 27 my $inner = $v->[0];
1304 27 ▶ if ( ref $inner eq 'SCALAR' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inner eq "SCALAR") 22 5 27
1305 22 my $live_value = _defor( $$inner, '' );
1306 22 ▶ if ( !( $live_value eq '0' || $live_value eq '1' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($live_value eq 0 or $live_value eq 1) 7 15 22
Condition100%3/3
$live_value eq 0 or $live_value eq 1
l!l&&r!l&&!r
697
MC/DC100%2/2
$live_value eq 0 or $live_value eq 1
$live_value eq 0 $live_value eq 1
Truth table100%3/3
A or B
A= $live_value eq 0B= $live_value eq 1
ABresult
1X1
011
000
1307 7 return _numify_if_lossless( _json_validate_utf8($live_value) );
1308 }
1309 15 return $inner;
1310 }
1311 5 ▶ die "xBOOLEAN() only accepts a plain scalar or a scalar ref, not a "
Branch: 1 branch
BranchTrueFalseTotal
if ref $inner 1 4 5
1312 . ref($inner) . " ref\n" if ref $inner;
1313 4 return _numify_if_lossless( _json_validate_utf8( _defor( $inner, '' ) ) );
1314 }
1315 elsif (UNIVERSAL::isa($v, 'ARRAY')) {
1316 11 my @parts;
1317  
1318 11 foreach my $val(@$v) {
1319 26 push @parts, $self->kvp2json_each(%o, value => $val);
1320 }
1321  
1322 11 return \@parts;
1323 }
1324 elsif (UNIVERSAL::isa($v, 'HASH')) {
1325 4 my %parts;
1326  
1327 4 foreach my $key(keys %$v) {
1328 8 $parts{$key} = $self->kvp2json_each(%o, key => $key, value => $v->{$key});
1329 }
1330  
1331 4 return \%parts;
1332 }
1333  
1334 die "Unable to convert a " . ref($v) . " reference into JSON for key '"
1335 1 . _defor( $o{key}, '' ) . "' - wrap it in xBOOLEAN() if you meant a "
1336 . "live boolean/tracked value\n";
1337 }
1338  
1339 117 ▶sub kvp2str {
Subroutine kvp2str: called CC=8 SCAR=20.8
Pod documented
1340 117 my ($self, %o) = @_;
1341  
1342 117 my ($data, $events) = @o{qw(data events)};
1343  
1344 117 my @keys = keys %$data;
1345  
1346 117 ▶ if (my $do = $events->{before_sorting_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"before_sorting_keys"}) 4 113 117
1347 4 $self->$do(%o, keys => \@keys);
1348 }
1349  
1350 117 ▶ if (my $do = $events->{keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{'keys'}) { } 5 112 117
1351 5 my %seen;
1352 5 @keys = grep { !$seen{$_}++ } $self->$do(%o);
1353 }
1354 else {
1355 112 @keys = sort @keys;
1356 }
1357  
1358 117 ▶ if (my $do = $events->{after_sorting_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"after_sorting_keys"}) 1 116 117
1359 1 $self->$do(%o, keys => \@keys);
1360 }
1361  
1362 117 my @parts;
1363  
1364 117 foreach my $key(@keys) {
1365 99 ▶ next if $events->{not_include}{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $events->{"not_include"}{$key} 1 98 99
1366 98 ▶ next if _should_skip_key(%o, key => $key);
Branch: 1 branch
BranchTrueFalseTotal
if _should_skip_key(%o, "key", $key) 1 97 98
1367 97 my $part = $self->kvp2str_each(%o, key => $key, value => $data->{$key});
1368 93 ▶ push @parts, $part if length $part;
Branch: 1 branch
BranchTrueFalseTotal
if length $part 90 3 93
1369 }
1370  
1371 113 return join '&', @parts;
1372 }
1373  
1374 176 ▶sub kvp2str_each {
Subroutine kvp2str_each: called CC=22 SCAR=30.9
Pod documented
1375 176 my ($self, %o) = @_;
1376  
1377 176 my ($raw_key, $v) = map { _defor($_, '') } @o{qw( key value )};
1378  
1379 176 my $k = _uri_escape_bytes_or_chars($raw_key);
1380  
1381 176 ▶ if (UNIVERSAL::isa($v, 'CODE')) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($v, "CODE")) 9 167 176
1382 9 $v = $self->$v(%o, key => $k);
1383 }
1384  
1385 176 ▶ if (!ref $v) {
Branch: 5 branches
BranchTrueFalseTotal
if (not ref $v) { } 112 64 176
elsif (ref $v eq 'HTTP::API::DataTypeMarker::BOOL') { } 27 37 64
elsif (ref $v eq 'ARRAY') { } 17 20 37
elsif (ref $v eq 'HTTP::API::DataTypeMarker::CSV') { } 17 3 20
elsif (UNIVERSAL::isa($v, 'HASH')) { } 2 1 3
1386 112 $v = _uri_escape_bytes_or_chars($v);
1387  
1388 112 ▶ if ($o{no_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o{'no_key'}) { } 42 70 112
1389 42 return $v;
1390 }
1391 else {
1392 70 return "$k=$v";
1393 }
1394 }
1395 elsif (ref $v eq 'HTTP::API::DataTypeMarker::BOOL') {
1396 27 my $inner = $v->[0];
1397 27 ▶ die "xBOOLEAN() only accepts a plain scalar or a scalar ref, not a "
Branch: 1 branch
BranchTrueFalseTotal
if ref $inner and ref $inner ne "SCALAR" 1 26 27
Condition100%3/3
ref $inner and ref $inner ne "SCALAR"
!ll&&!rl&&r
16101
MC/DC100%2/2
ref $inner and ref $inner ne "SCALAR"
ref $inner ref $inner ne "SCALAR"
Truth table100%3/3
A and B
A= ref $innerB= ref $inner ne "SCALAR"
ABresult
0X0
100
111
1398 . ref($inner) . " ref\n" if ref $inner && ref $inner ne 'SCALAR';
1399 26 ▶ my $bool_value = ref $inner eq 'SCALAR' ? $$inner : $inner;
Branch: 1 branch
BranchTrueFalseTotal
ref $inner eq 'SCALAR' ? : 10 16 26
1400 26 my $escaped = _uri_escape_bytes_or_chars( _defor($bool_value, '') );
1401 26 ▶ return $o{no_key} ? $escaped : "$k=$escaped";
Branch: 1 branch
BranchTrueFalseTotal
$o{'no_key'} ? : 2 24 26
1402 }
1403 elsif (ref $v eq 'ARRAY') {
1404 17 my @parts;
1405  
1406 17 foreach my $val(@$v) {
1407 31 my $part = $self->kvp2str_each(%o, key => $raw_key, value => $val, no_key => 0);
1408 31 ▶ push @parts, $part if length $part;
Branch: 1 branch
BranchTrueFalseTotal
if length $part 30 1 31
1409 }
1410  
1411 17 ▶ return '' if !@parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 4 13 17
1412  
1413 13 ▶ return ($o{no_key} ? '&' : '') . join '&', @parts;
Branch: 1 branch
BranchTrueFalseTotal
$o{'no_key'} ? : 3 10 13
1414 }
1415 elsif (ref $v eq 'HTTP::API::DataTypeMarker::CSV') {
1416 17 my @csv;
1417 my @parts;
1418  
1419 17 foreach my $val(@$v) {
1420 49 ▶ next if ref $val eq 'ARRAY' && !@$val;
Branch: 1 branch
BranchTrueFalseTotal
if ref $val eq "ARRAY" and not @$val 1 48 49
Condition100%3/3
ref $val eq "ARRAY" and not @$val
!ll&&!rl&&r
4531
MC/DC100%2/2
ref $val eq "ARRAY" and not @$val
ref $val eq "ARRAY" not @$val
Truth table100%3/3
A and not(B)
A= ref $val eq "ARRAY"B= not @$val
ABresult
0X0
100
111
1421  
1422 48 my $part = $self->kvp2str_each(%o, key => $raw_key, value => $val, no_key => 1);
1423  
1424 48 ▶ if ($part =~ m/&/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /&/) { } 3 45 48
1425 3 push @parts, $part;
1426 }
1427 else {
1428 45 push @csv, $part;
1429 }
1430 }
1431  
1432 17 ▶ my $csv = ($o{no_key} ? '' : "$k=") . join( ',', @csv);
Branch: 1 branch
BranchTrueFalseTotal
$o{'no_key'} ? : 1 16 17
1433  
1434 17 ▶ if (@parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts) 3 14 17
1435 3 return join '&', $csv, map { ( my $c = $_ ) =~ s/^&//; $c } @parts;
1436 }
1437  
1438 14 return $csv;
1439 }
1440 elsif (UNIVERSAL::isa($v, 'HASH')) {
1441 2 die "Unable to convert nested hash value for key '$k' into a form-urlencoded query string\n";
1442 }
1443  
1444 1 die "Unable to convert a " . ref($v) . " reference into a form-urlencoded "
1445 . "query string value for key '$k' - wrap it in xBOOLEAN() if you meant "
1446 . "a live boolean/tracked value\n";
1447 }
1448  
1449 8 ▶sub basic_authenticator {
Subroutine basic_authenticator: called CC=1 SCAR=0.0
Pod documented
1450 8 my ($self, $req, $u, $p) = @_;
1451 8 return $req->headers->authorization_basic($u, $p);
1452 }
1453  
1454 2952 ▶sub _defor {
Subroutine _defor: called CC=3 SCAR=11.0
1455 2952 my ($default, $or) = @_;
1456 2952 ▶ return (defined($default) && length($default)) ? $default : $or;
Branch: 1 branch
BranchTrueFalseTotal
defined $default && length $default ? : 1742 1210 2952
Condition100%3/3
defined $default and length $default
!ll&&!rl&&r
8084021742
MC/DC100%2/2
defined $default and length $default
defined $default length $default
Truth table100%3/3
A and B
A= defined $defaultB= length $default
ABresult
0X0
100
111
1457 }
1458  
1459 95 ▶no Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
1460  
1461 95 1;
↑ Summary DataTypeMarker.pm »