Client.pm

filter: Statementstmt 100% 405 / 405 Branchbran 96.2% 181 / 188 Conditioncond 90.2% 46 / 51 MC/DCmcdc 80.6% 25 / 31 Subroutinesub 100% 62 / 62 Podpod 100% 17 / 17 totaltotal 97.6% 736 / 754 CC 122 SCAR 24.1
CC
122
Cov
98%
send
26.1
kvp2str_each
22.0
new_request
20.0
CRAP 11.1
↑ Summary DataTypeMarker.pm »
1 package HTTP::API::Client;
2 84 $HTTP::API::Client::VERSION = '1.24';
3 84 ▶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),
366 C<before_header>/C<after_header> keyed by header name, and
367 C<after_header_keys> - the hooks used to compute things like a signature
368 header from other data at build time. See F<t/04_callbacks.t> for a worked
369 example (API key + signature).
370  
371 C<%options> also accepts C<skip_headers>, a hashref of header names to
372 exclude from the request no matter what C<%headers> or the events above
373 say. Only reachable by calling C<new_request()> directly with it - C<send()>
374 never sets it, and setting it inside an C<%events> callback has no effect
375 (a callback receives a snapshot copy of C<%options>, not the one
376 C<new_request()> itself is iterating). See F<t/23_skip_headers.t>.
377  
378 L<HTTP::API::DataTypeMarker>'s C<xBOOLEAN()>/C<xCSV()> markers are only
379 unwrapped in body data (via C<kvp2json()>/C<kvp2str()>) - a header value
380 that's still a marker dies naming the offending header key, rather than
381 silently setting the header to Perl's default blessed-reference
382 stringification (C<"BOOL=ARRAY(0x...)">).
383  
384 =head2 get_content_type(%options)
385  
386 Resolves the effective content type for one call: the C<content_type>
387 attribute if set explicitly; otherwise C<application/x-www-form-urlencoded>
388 for a GET, or C<application/json; charset=$charset> for anything else.
389 Called internally by C<convert_data()>, C<prepare_request()>, and
390 C<new_request()> - there is normally no need to call this directly.
391  
392 =head2 convert_data(%options)
393  
394 Turn C<%options>'s C<data> hashref into the request body, according to
395 content type: JSON via C<kvp2json()> if the content type contains C<json>,
396 a query string via C<kvp2str()> if it is C<application/x-www-form-urlencoded>
397 optionally followed by a C<;>-separated parameter (e.g. C<< application/
398 x-www-form-urlencoded; charset=utf-8 >> - the same charset-suffix pattern
399 this module's own JSON default already uses). Any other content type
400 returns an empty string for empty data, or dies naming the content type -
401 there is no generic way to serialize arbitrary data into an arbitrary
402 content type.
403  
404 =head2 prepare_request(%options)
405  
406 Builds the bare L<HTTP::Request> (method, URL, content-type header) and
407 applies authentication: C<username>/C<password> take priority and are sent
408 as HTTP Basic auth via C<basic_authenticator()>; C<auth_token> is used only
409 if neither is set, and is sent as a raw C<Authorization> header value
410 verbatim (no C<Bearer> prefix is added for you - include it in the token
411 itself if the API expects one). C<auth_token> only supplies a I<default>
412 C<Authorization> header - an explicit one already present in C<%headers>
413 for this call (any casing: C<Authorization>, C<authorization>, ...) is
414 left alone rather than overwritten. Called by C<new_request()> - there is
415 normally no need to call this directly.
416  
417 =head2 basic_authenticator($request, $username, $password)
418  
419 Sets HTTP Basic auth on C<$request> via
420 C<< $request->headers->authorization_basic >>. Override this in a subclass
421 to change how basic auth is applied without touching the rest of request
422 building.
423  
424 =head2 kvp2json(%options) / kvp2str(%options)
425  
426 The two body encoders C<convert_data> dispatches to. C<kvp2json> walks
427 C<%options>'s C<data> hashref and JSON::XS-encodes it, resolving any
428 C<CODE> values by calling them and unwrapping L<HTTP::API::DataTypeMarker>'s
429 C<xBOOLEAN>-family markers into their JSON form; an C<xCSV>-marked value
430 has no special JSON handling and just JSON-encodes as an ordinary array
431 (there's no C<key=value&key=value> repetition problem in JSON for it to
432 solve). C<kvp2str> produces a C<key=value&key=value> query string instead,
433 with C<xCSV>-marked values joined by commas instead of repeated per key.
434 An empty arrayref value is omitted from C<kvp2str>'s output entirely (an
435 empty array has no C<key=value> representation), the same as a key
436 mapped to C<undef>/missing already is - including an empty array nested
437 inside an C<xCSV(...)> list, which contributes nothing to the joined
438 string rather than leaving a blank comma segment behind. An C<xCSV()>
439 with no elements at all is different: it still emits C<key=> (present,
440 empty value) rather than being omitted - there is no join-corruption
441 risk to avoid the way there is for a nested empty array, and C<key=> is
442 valid, parseable form data distinct from the key being absent.
443 Both respect an C<< $events->{keys} >> callback to control which keys are
444 included and in what order, and both accept a C<skip_key> hashref in
445 C<%options> (same reachability caveat as C<new_request()>'s
446 C<skip_headers> above - only useful from a direct call, e.g. a C<data>
447 callback recursively re-invoking C<kvp2str()>/C<kvp2json()> on itself to
448 build its own value without infinite-looping on its own key; see
449 F<t/04_callbacks.t>) to exclude a key from the encoded body.
450  
451 C<kvp2str> alone also fires C<< $events->{before_sorting_keys} >> and
452 C<< $events->{after_sorting_keys} >>, each called with C<< keys => \@keys
453 >> - an arrayref of the field names about to be (respectively, just
454 were) sorted. Both are genuinely live: a callback that mutates
455 C<@$keys> in place (push/splice/grep out an element) changes what
456 C<kvp2str> actually encodes, as long as C<< $events->{keys} >> isn't
457 also set (which replaces C<@keys> outright, discarding
458 C<before_sorting_keys>' mutation). See F<t/21_before_events.t> and
459 F<t/33_before_sorting_keys_mutation.t>. C<kvp2json> has no equivalent
460 hook - its C<@keys> is either C<< $events->{keys} >>'s return value or
461 an unsorted C<keys %$data>, with no separate sorting step to hook into.
462  
463 C<kvp2json> encodes a numeric-looking string value as a genuine JSON
464 number rather than a quoted string - but only when doing so loses
465 nothing (stringifying the number back reproduces the original value
466 exactly). A value like C<"5"> becomes C<5>, but C<"00501"> (a US zip
467 code) or C<"5.0"> stays a string, since numifying either would silently
468 discard meaningful formatting. A value like C<"NaN">, C<"Inf">, or
469 C<"-Inf"> also stays a string even though it round-trips losslessly as
470 a Perl number - JSON has no valid representation for a non-finite
471 number, and numifying it would make C<kvp2json> emit the bareword
472 C<nan>/C<inf>/C<-inf>, which is not valid JSON and no parser (including
473 this module's own JSON::XS) can decode. C<kvp2str> never numifies at
474 all - a query string has no separate number/string type, so there was
475 never a reason to risk altering the original representation.
476  
477 =head2 kvp2json_each(%options) / kvp2str_each(%options)
478  
479 The per-value helpers C<kvp2json()>/C<kvp2str()> recurse into for each key
480 via C<%options>'s C<value> (and C<key> - the field's own key, available
481 to a C<CODE> value's callback via C<%options>; C<kvp2json_each> passes it
482 through at every level, including a nested hash value's own key, not
483 just the top-level field's). Resolves a C<CODE> value by calling it,
484 unwraps L<HTTP::API::DataTypeMarker> markers (C<xCSV>/C<xBOOLEAN> and
485 friends), and recurses into plain array values. There is normally no
486 need to call these directly - they exist as public methods so a
487 C<data>/C<value> callback can recursively re-invoke them on itself (see
488 C<kvp2json()>/C<kvp2str()> above).
489  
490 These two are not symmetric on invalid input, in two ways. First,
491 C<kvp2json_each> dies if a raw-bytes (non-UTF8-flagged) value is not
492 valid UTF-8, rather than silently corrupting it into C<U+FFFD>
493 replacement characters - JSON has no way to represent arbitrary bytes.
494 C<kvp2str_each> has no such restriction; a query string can carry any
495 byte sequence unescaped-safe via percent-encoding, so the same input
496 that dies in the JSON path passes through the form-urlencoded path
497 unchanged. Second, a plain hash value recurses in C<kvp2json_each> (JSON
498 has a native object type for it) but dies in C<kvp2str_each> - a query
499 string has no standard convention for representing a nested hash.
500  
501 C<undef> is also handled differently by nesting depth, deliberately left
502 this way rather than made symmetric. C<kvp2json()>'s own top-level loop
503 omits a key entirely when its value is C<undef> (see
504 L</"kvp2json(%options)"> above). A nested hash value's own
505 C<undef> sub-value is not: C<kvp2json_each>'s recursion into a hash value
506 has no equivalent skip step, so an C<undef> sub-value becomes an empty
507 JSON string (C<"">) rather than disappearing from the encoded object -
508 C<< kvp2json(data => { a => { x => 1, y => undef } }) >> encodes as
509 C<< {"a":{"x":1,"y":""}} >>, keeping C<y>, while the same C<undef> at the
510 top level would have dropped the key outright.
511  
512 Both die - with the same message, naming the offending ref type and
513 pointing at C<xBOOLEAN()> - on any other reference type neither of them
514 otherwise recognizes, most commonly a bare (not C<xBOOLEAN>-wrapped)
515 scalar ref: a value like C<< \$flag >> passed directly, typically from
516 forgetting to call C<xBOOLEAN(\$flag)> around it. Before this die was
517 added, C<kvp2str_each> silently stringified such a value as
518 C<SCALAR(0x...)>, and C<kvp2json_each> reached the same outcome only by
519 accident of JSON::XS itself refusing to encode an arbitrary scalar ref
520 - with a message that never mentioned this module's own vocabulary.
521  
522 C<kvp2str_each>'s C<%options> also accepts C<no_key>, set internally when
523 recursing into an ARRAY or C<xCSV> element: when true, the returned
524 fragment omits the leading C<key=> prefix (a plain scalar, C<xCSV>, and
525 C<xBOOLEAN>-marked value all honor this identically) so a CSV/array
526 element joins as a bare value rather than a spurious embedded
527 C<key=value> pair.
528  
529 Both encoders unwrap an C<xBOOLEAN(\$flag)> live scalar ref to whatever
530 C<$flag> currently holds, not just the C<0>/C<1> case C<xTRUE>/C<xFALSE>
531 use - a live ref that currently holds exactly (C<eq>, not merely
532 numerically C<==>) the string C<0> or C<1> still becomes a native JSON
533 boolean in C<kvp2json_each> (matching C<xTRUE>/C<xFALSE>; JSON::XS's own
534 convention only accepts that exact canonical form, not e.g. C<"01"> or
535 C<"1.0">), but any other live value - including one that is numerically
536 equal to C<0>/C<1> without being formatted exactly that way - encodes as
537 its own actual contents in both encoders alike, the same way a plain
538 (non-live) C<xBOOLEAN> value already did - including
539 C<kvp2json_each>'s invalid-UTF-8 die documented above, which a live
540 non-canonical value goes through exactly like the plain-scalar case
541 does. A live value that currently holds C<undef> is treated as an
542 empty string in both encoders, not C<undef> itself - it never reaches
543 the invalid-UTF-8 check (an empty string is trivially valid UTF-8) and
544 encodes as C<""> in JSON, matching how C<kvp2str_each> already handled
545 this case.
546  
547 A plain (non-live) C<xBOOLEAN> value - anything other than the
548 C<\1>/C<\0> shape C<xTRUE>/C<xFALSE> use, including a value passed to
549 C<xBOOLEAN()> directly with no leading backslash - goes through the
550 exact same invalid-UTF-8 die and lossless-numify treatment in
551 C<kvp2json_each> as the plain scalar branch: C<xBOOLEAN("5")> encodes as
552 the JSON number C<5>, and invalid UTF-8 bytes die with the same message
553 rather than silently corrupting into JSON, just like a plain scalar
554 value with the identical content would.
555  
556 C<xBOOLEAN()> only accepts a plain scalar or a scalar ref - wrapping
557 anything else (an arrayref, a hashref) dies with a clear message naming
558 the offending ref type in both encoders, rather than silently
559 stringifying it (e.g. into C<"HASH(0x...)">) the way an unmarked
560 reference of the wrong shape does elsewhere in this module (see
561 C<kvp2str_each>'s nested-hash die, above).
562  
563 =head1 LICENSE AND COPYRIGHT
564  
565 This software is Copyright (c) 2026 by Michael Vu.
566  
567 This is free software, licensed under:
568  
569 The MIT (X11) License
570  
571 The MIT License
572  
573 Permission is hereby granted, free of charge, to any person
574 obtaining a copy of this software and associated
575 documentation files (the "Software"), to deal in the Software
576 without restriction, including without limitation the rights to
577 use, copy, modify, merge, publish, distribute, sublicense,
578 and/or sell copies of the Software, and to permit persons to
579 whom the Software is furnished to do so, subject to the
580 following conditions:
581  
582 The above copyright notice and this permission notice shall
583 be included in all copies or substantial portions of the
584 Software.
585  
586 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT
587 WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
588 INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
589 MERCHANTABILITY, FITNESS FOR A PARTICULAR
590 PURPOSE AND NONINFRINGEMENT. IN NO EVENT
591 SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
592 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
593 LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
594 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
595 CONNECTION WITH THE SOFTWARE OR THE USE OR
596 OTHER DEALINGS IN THE SOFTWARE.
597  
598 =cut
599  
600 84 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
601 84 ▶use HTTP::Headers;
Subroutine BEGIN: called CC=1 SCAR=0.0
602 84 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
603 84 ▶use JSON::XS;
Subroutine BEGIN: called CC=1 SCAR=0.0
604 84 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
605 84 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
606 84 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
607 84 ▶use URI::Escape qw( uri_escape uri_unescape );
Subroutine BEGIN: called CC=1 SCAR=0.0
608 84 ▶use Scalar::Util qw( looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
609 84 ▶use POSIX qw( isnan isinf );
Subroutine BEGIN: called CC=1 SCAR=0.0
610 84 ▶use HTTP::API::DataTypeMarker;
Subroutine BEGIN: called CC=1 SCAR=0.0
611  
612 84 extends 'Exporter';
613  
614 84 our @EXPORT = @HTTP::API::DataTypeMarker::EXPORT;
615  
616 84 has username => (
617 is => "rw",
618 lazy => 1,
619 builder => 1,
620 );
621  
622 71 ▶sub _build_username { _defor($ENV{HTTP_USERNAME}, '') }
Subroutine _build_username: called CC=1 SCAR=0.0
623  
624 84 has password => (
625 is => "rw",
626 lazy => 1,
627 builder => 1,
628 );
629  
630 71 ▶sub _build_password { _defor($ENV{HTTP_PASSWORD}, '') }
Subroutine _build_password: called CC=1 SCAR=0.0
631  
632 84 has auth_token => (
633 is => "rw",
634 lazy => 1,
635 builder => 1,
636 );
637  
638 73 ▶sub _build_auth_token { _defor($ENV{HTTP_AUTH_TOKEN}, '') }
Subroutine _build_auth_token: called CC=1 SCAR=0.0
639  
640 84 has base_url => (
641 is => "rw",
642 lazy => 1,
643 builder => 1,
644 );
645  
646 ▶sub _build_base_url {}
Subroutine _build_base_url: called CC=1 SCAR=0.0
647  
648 84 has last_response => (
649 is => "rw",
650 lazy => 1,
651 builder => 1,
652 );
653  
654 ▶sub _build_last_response {}
Subroutine _build_last_response: called CC=1 SCAR=0.0
655  
656 84 has charset => (
657 is => "rw",
658 lazy => 1,
659 builder => 1,
660 );
661  
662 53 ▶sub _build_charset { _defor($ENV{HTTP_CHARSET}, "utf8") }
Subroutine _build_charset: called CC=1 SCAR=0.0
663  
664 84 has browser_id => (
665 is => "rw",
666 lazy => 1,
667 builder => 1,
668 );
669  
670 sub _build_browser_id {
671 83 ▶ my $ver = _defor($HTTP::API::Client::VERSION, 'dev');
Subroutine _build_browser_id: called CC=1 SCAR=0.0
672 83 return "HTTP API Client v$ver";
673 }
674  
675 84 has content_type => (
676 is => "rw",
677 lazy => 1,
678 builder => 1,
679 );
680  
681 ▶sub _build_content_type {}
Subroutine _build_content_type: called CC=1 SCAR=0.0
682  
683 sub get_content_type {
684 305 ▶ my ($self, %o) = @_;
Subroutine get_content_type: called CC=3 SCAR=11.0
Pod documented
685 305 my $content_type = $self->content_type;
686  
687 305 ▶ if ($content_type) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_type) 99 206 305
688 99 return $content_type;
689 }
690  
691 206 my $method = ${$o{method}};
692  
693 206 ▶ if ($method eq 'GET') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "GET") 174 32 206
694 174 return 'application/x-www-form-urlencoded';
695 }
696  
697 32 my $charset = $self->charset;
698 32 return "application/json; charset=$charset";
699 }
700  
701 84 has engine => (
702 is => "ro",
703 lazy => 1,
704 builder => 1,
705 );
706  
707 82 ▶sub _build_engine {"LWP::UserAgent"}
Subroutine _build_engine: called CC=1 SCAR=0.0
708  
709 84 has ua => (
710 is => "rw",
711 lazy => 1,
712 builder => 1,
713 );
714  
715 sub _build_ua {
716 69 ▶ my ($self) = @_;
Subroutine _build_ua: called CC=2 SCAR=6.9
717 69 my $ssl_verify = $self->ssl_verify;
718 69 my $engine = $self->engine;
719  
720 69 my $ua;
721  
722 69 ▶ if ( $engine eq "LWP::UserAgent" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine eq 'LWP::UserAgent') { } 68 1 69
723 68 $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => $ssl_verify } );
724 68 $ua->agent( $self->browser_id );
725 68 $ua->timeout( $self->timeout );
726 }
727 else {
728 1 $ua = $self->$engine($ssl_verify);
729 }
730  
731 69 return $ua;
732 }
733  
734 84 has ssl_verify => (
735 is => "rw",
736 lazy => 1,
737 builder => 1,
738 );
739  
740 sub _build_ssl_verify {
741 69 ▶ return _defor( $ENV{SSL_VERIFY}, 0 );
Subroutine _build_ssl_verify: called CC=1 SCAR=0.0
742 }
743  
744 # send() does NOT read this attribute - since HAC-068 it calls
745 # $self->_build_retry directly on every call, so retry_config changes
746 # take effect live. This accessor is kept only for external callers who
747 # already read $api->retry directly; it's a one-time snapshot at
748 # whatever moment it's first accessed, not a live view of send()'s
749 # actual behavior.
750 84 has retry => (
751 is => "rw",
752 lazy => 1,
753 builder => 1,
754 );
755  
756 sub _build_retry {
757 100 ▶ my ($self) = @_;
Subroutine _build_retry: called CC=3 SCAR=11.0
758 100 my %retry = %{ _defor($self->retry_config, {}) };
759 100 my $count = _defor( $retry{fail_response}, 0 );
760 100 ▶ $count = 0 if looks_like_number($count) && $count < 0;
Branch: 1 branch
BranchTrueFalseTotal
if &looks_like_number($count) and $count < 0 1 99 100
Condition66%2/3
&looks_like_number($count) and $count < 0
!ll&&!rl&&r
0991
MC/DC50%1/2
&looks_like_number($count) and $count < 0
&looks_like_number($count) $count < 0
Truth table66%2/3
A and B
A= &looks_like_number($count)B= $count < 0
ABresult
0X0
100
111
761 13 my %status = map { $_ => 1 }
762 15 grep { length }
763 15 map { s/^\s+|\s+$//g; $_ }
764 100 split /,/, _defor($retry{fail_status}, '');
765  
766 100 my $delay = _defor( $retry{delay}, 5 );
767  
768 return {
769 100 count => $count,
770 status => \%status,
771 delay => $delay,
772 };
773 }
774  
775 84 has retry_config => (
776 is => "rw",
777 lazy => 1,
778 builder => 1,
779 );
780  
781 sub _build_retry_config {
782 return {
783 fail_response => _defor( $ENV{RETRY_FAIL_RESPONSE}, 0 ),
784 fail_status => _defor($ENV{RETRY_FAIL_STATUS}, ''),
785 82 ▶ delay => _defor( $ENV{RETRY_DELAY}, 5 ),
Subroutine _build_retry_config: called CC=1 SCAR=0.0
786 };
787 }
788  
789 84 has timeout => (
790 is => "rw",
791 lazy => 1,
792 builder => 1,
793 );
794  
795 82 ▶sub _build_timeout { _defor($ENV{HTTP_TIMEOUT}, 60) }
Subroutine _build_timeout: called CC=1 SCAR=0.0
796  
797 84 has json => (
798 is => "rw",
799 lazy => 1,
800 builder => 1,
801 );
802  
803 sub _build_json {
804 32 ▶ my ($self) = @_;
Subroutine _build_json: called CC=1 SCAR=0.0
805 32 return _apply_charset( JSON::XS->new->canonical->allow_nonref, $self->charset );
806 }
807  
808 sub _apply_charset {
809 93 ▶ my ($json, $charset) = @_;
Subroutine _apply_charset: called CC=2 SCAR=6.9
810 93 ▶ eval { $json->$charset; 1 } or die "Unsupported charset '$charset': $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $json->$charset; 1 } } or die "Unsupported charset '${charset}': $@" 2 91 93
811 91 return $json;
812 }
813  
814 84 has debug_flags => (
815 is => "rw",
816 lazy => 1,
817 builder => 1,
818 );
819  
820 sub _build_debug_flags {
821 return {
822 in_out => $ENV{DEBUG_IN_OUT},
823 send_out => $ENV{DEBUG_SEND_OUT},
824 response => $ENV{DEBUG_RESPONSE},
825 response_header_only => $ENV{DEBUG_RESPONSE_HEADER_ONLY},
826 response_if_fail => $ENV{DEBUG_RESPONSE_IF_FAIL},
827 83 ▶ };
Subroutine _build_debug_flags: called CC=1 SCAR=0.0
828 }
829  
830 84 has pre_defined_data => (
831 is => "rw",
832 lazy => 1,
833 builder => 1,
834 );
835  
836 79 ▶sub _build_pre_defined_data {{}}
Subroutine _build_pre_defined_data: called CC=1 SCAR=0.0
837  
838 84 has pre_defined_headers => (
839 is => "rw",
840 lazy => 1,
841 builder => 1,
842 );
843  
844 82 ▶sub _build_pre_defined_headers {{}}
Subroutine _build_pre_defined_headers: called CC=1 SCAR=0.0
845  
846 84 has pre_defined_events => (
847 is => "rw",
848 lazy => 1,
849 builder => 1,
850 );
851  
852 82 ▶sub _build_pre_defined_events {{}}
Subroutine _build_pre_defined_events: called CC=1 SCAR=0.0
853  
854 sub get {
855 70 ▶ my ($self, @args) = @_;
Subroutine get: called CC=1 SCAR=0.0
Pod documented
856 70 return $self->send( GET => @args );
857 }
858  
859 sub post {
860 23 ▶ my ($self, @args) = @_;
Subroutine post: called CC=1 SCAR=0.0
Pod documented
861 23 return $self->send( POST => @args );
862 }
863  
864 sub put {
865 1 ▶ my ($self, @args) = @_;
Subroutine put: called CC=1 SCAR=0.0
Pod documented
866 1 return $self->send( PUT => @args );
867 }
868  
869 sub head {
870 1 ▶ my ($self, @args) = @_;
Subroutine head: called CC=1 SCAR=0.0
Pod documented
871 1 return $self->send( HEAD => @args );
872 }
873  
874 sub delete {
875 1 ▶ my ($self, @args) = @_;
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
876 1 return $self->send( DELETE => @args );
877 }
878  
879 sub _execute_callbacks {
880 190 ▶ my ($self, $type, %options) = @_;
Subroutine _execute_callbacks: called CC=4 SCAR=13.9
881  
882 190 my $sth = $options{$type};
883  
884 190 for my $key (sort keys %$sth) {
885 151 my $callback = $sth->{$key};
886 151 ▶ next if !defined $callback;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $callback 2 149 151
887 149 ▶ next if !UNIVERSAL::isa($callback, 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($callback, "CODE") 132 17 149
888 17 $sth->{$key} = $self->$callback(key => $key, %options);
889 }
890 }
891  
892 sub send {
893 95 ▶ my ($self, $method, $path,
Subroutine send: called CC=26 SCAR=32.6
Pod documented
894 $data, $headers, $events) = @_;
895  
896 95 $method = uc $method;
897 95 $path = _defor( $path, '' );
898 95 $data = { %{ _defor( $data, {} ) } };
899 95 $headers = { %{ _defor( $headers, {} ) } };
900 95 $events = { %{ _defor( $events, {} ) } };
901  
902 95 my $base_url = $self->base_url;
903 95 ▶ my $url = $base_url ? $base_url . $path : $path;
Branch: 1 branch
BranchTrueFalseTotal
$base_url ? : 13 82 95
904 95 my $ua = $self->ua;
905 95 ▶ $ua->agent( $self->browser_id ) if $ua->can('agent');
Branch: 1 branch
BranchTrueFalseTotal
if $ua->can("agent") 94 1 95
906 95 ▶ $ua->timeout( $self->timeout ) if $ua->can('timeout');
Branch: 1 branch
BranchTrueFalseTotal
if $ua->can("timeout") 94 1 95
907 95 ▶ $ua->ssl_opts( verify_hostname => $self->ssl_verify ) if $ua->can('ssl_opts');
Branch: 1 branch
BranchTrueFalseTotal
if $ua->can("ssl_opts") 79 16 95
908 95 my $retry_settings = $self->_build_retry;
909 95 my $retry_count = _defor( $retry_settings->{count}, 1 );
910 95 my $retry_delay = _defor( $retry_settings->{delay}, 5 );
911 95 ▶ $retry_delay = 0 if looks_like_number($retry_delay) && $retry_delay < 0;
Branch: 1 branch
BranchTrueFalseTotal
if &looks_like_number($retry_delay) and $retry_delay < 0 1 94 95
Condition66%2/3
&looks_like_number($retry_delay) and $retry_delay < 0
!ll&&!rl&&r
0941
MC/DC50%1/2
&looks_like_number($retry_delay) and $retry_delay < 0
&looks_like_number($retry_delay) $retry_delay < 0
Truth table66%2/3
A and B
A= &looks_like_number($retry_delay)B= $retry_delay < 0
ABresult
0X0
100
111
912 95 my %retry_status = %{ _defor($retry_settings->{status}, {}) };
913 95 my %debug = %{ _defor($self->debug_flags, {}) };
914 95 my $eng = $self->engine;
915  
916 95 ▶ if ( my $pd = $self->pre_defined_data ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pd = $self->pre_defined_data) 95 0 95
917 95 %$data = ( %$pd, %$data );
918 }
919  
920 95 ▶ if ( my $ph = $self->pre_defined_headers ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ph = $self->pre_defined_headers) 95 0 95
921 95 %$headers = ( %$ph, %$headers );
922 }
923  
924 95 ▶ if ( my $pe = $self->pre_defined_events ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pe = $self->pre_defined_events) 95 0 95
925 95 %$events = ( %$pe, %$events );
926 }
927  
928 95 my %options = (
929 method => \$method,
930 url => \$url,
931 path => \$path,
932 data => $data,
933 headers => $headers,
934 events => $events,
935 );
936  
937 95 $self->_execute_callbacks(data => %options);
938 95 $self->_execute_callbacks(headers => %options);
939  
940 95 my $response;
941  
942 RETRY:
943 95 foreach my $retry ( 0 .. $retry_count ) {
944 103 my $started_time = time;
945  
946 103 ▶ if ( $eng eq 'LWP::UserAgent' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eng eq 'LWP::UserAgent') { } 102 1 103
947 102 my $req = $self->new_request( %options );
948  
949 96 ▶ if ($events->{test_request_object}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($events->{"test_request_object"}) 73 23 96
950 73 return $req;
951 }
952  
953 23 $response = $ua->request($req);
954 }
955 else {
956 1 die "Unsupported engine: $eng - only LWP::UserAgent is currently wired up in send()\n";
957 }
958  
959 23 ▶ my $suppress_on_success = $debug{response_if_fail} && $response->is_success;
Condition100%3/3
$debug{'response_if_fail'} && $response->is_success
!ll&&!rl&&r
1823
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
960  
961 23 ▶ 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) 6 17 23
Condition100%6/6
$debug{"send_out"} or $debug{"in_out"} and not $suppress_on_success
l!l&&r!l&&!r
4217
$debug{"in_out"} and not $suppress_on_success
!ll&&!rl&&r
1612
MC/DC66%2/3
$debug{"send_out"} or $debug{"in_out"} and not $suppress_on_success
$debug{"send_out"} $debug{"in_out"} not $suppress_on_success
Truth table75%3/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
962 6 print STDERR "-- REQUEST --\n";
963 6 ▶ if ( $retry_count && $retry ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($retry_count and $retry) 2 4 6
Condition100%3/3
$retry_count and $retry
!ll&&!rl&&r
312
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
964 2 print STDERR "-- RETRY $retry of $retry_count\n";
965 }
966 6 print STDERR $response->request->as_string;
967 6 print STDERR "\n";
968 }
969  
970 23 my $debug_response = _defor($debug{in_out}, $debug{response});
971  
972 23 ▶ $debug_response = 0
Branch: 1 branch
BranchTrueFalseTotal
if $suppress_on_success 3 20 23
973 if $suppress_on_success;
974  
975 23 ▶ if ($debug_response) {
Branch: 1 branch
BranchTrueFalseTotal
if ($debug_response) 3 20 23
976 3 my $used_time = time - $started_time;
977  
978 3 print STDERR "-- RESPONSE $used_time sec(s) --\n";
979  
980 print STDERR $debug{response_header_only}
981 3 ▶ ? $response->headers->as_string
Branch: 1 branch
BranchTrueFalseTotal
$debug{'response_header_only'} ? : 0 3 3
982 : $response->as_string;
983  
984 3 print STDERR ( "-" x 80 ) . "\n";
985 }
986  
987 last RETRY ## request is success, not further for retry
988 23 ▶ if $response->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $response->is_success 4 19 23
989  
990 last RETRY ## no attempts left, don't sleep for a retry that won't happen
991 19 ▶ if $retry >= $retry_count;
Branch: 1 branch
BranchTrueFalseTotal
if $retry >= $retry_count 10 9 19
992  
993 9 ▶ if ( !%retry_status ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (%retry_status) 4 5 9
994 4 sleep $retry_delay;
995 ## no retry pattern at all then just retry
996 4 next RETRY;
997 }
998  
999 5 ▶ $retry_status{ $response->code }
Branch: 1 branch
BranchTrueFalseTotal
$retry_status{$response->code} or last RETRY 1 4 5
1000 or
1001 last RETRY; ## status code not in RETRY_FAIL_STATUS, just stop retry
1002  
1003 4 sleep $retry_delay;
1004 4 next RETRY;
1005 }
1006  
1007 15 return $self->last_response($response);
1008 }
1009  
1010 sub json_response {
1011 5 ▶ my ($self) = @_;
Subroutine json_response: called CC=1 SCAR=0.0
Pod documented
1012  
1013 my $response = try {
1014 5 ▶ my $content = _defor($self->last_response->decoded_content, '{}');
Subroutine __ANON__: called CC=1 SCAR=0.0
1015 4 my $json = _apply_charset( $self->json, $self->charset );
1016 4 $json->decode($content);
1017 }
1018 catch {
1019 2 ▶ my $error = $_;
Subroutine __ANON__: called CC=1 SCAR=0.0
1020 2 { status => "error", error => $error };
1021 5 };
1022  
1023 5 return $response;
1024 }
1025  
1026 sub kvp_response {
1027 12 ▶ my ($self) = @_;
Subroutine kvp_response: called CC=7 SCAR=19.5
Pod documented
1028  
1029 12 ▶ my $response = $self->last_response
Branch: 1 branch
BranchTrueFalseTotal
my $response = $self->last_response or return {} 1 11 12
1030 or return {};
1031  
1032 11 ▶ my $content = $response->decoded_content
Branch: 1 branch
BranchTrueFalseTotal
my $content = $response->decoded_content or return {} 0 11 11
1033 or return {};
1034  
1035 11 my %data;
1036 11 for my $pair ( split /&/, $content ) {
1037 22 ▶ next if $pair eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $pair eq "" 2 20 22
1038 20 my ( $k, $v ) = map { ( my $s = $_ ) =~ tr/+/ /; uri_unescape($s) } split /=/, $pair, 2;
1039 20 ▶ if ( exists $data{$k} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data{$k}) { } 5 15 20
1040 5 ▶ $data{$k} = [ $data{$k} ] unless ref $data{$k} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data{$k} eq "ARRAY" 3 2 5
1041 5 push @{ $data{$k} }, $v;
1042 }
1043 else {
1044 15 $data{$k} = $v;
1045 }
1046 }
1047  
1048 11 return \%data;
1049 }
1050  
1051 sub new_request {
1052 103 ▶ my ($self, %o) = @_;
Subroutine new_request: called CC=20 SCAR=30.0
Pod documented
1053  
1054 103 my ($method, $url) = map { $$_ } @o{qw(method url)};
1055  
1056 103 my ($data, $headers, $events) = @o{qw(data headers events)};
1057  
1058 103 my $content_type = $self->get_content_type(%o);
1059  
1060 103 my $content = $self->convert_data(%o);
1061  
1062 100 ▶ if ($content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content) 45 55 100
1063 45 ▶ if ($self->charset eq 'utf8') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->charset eq "utf8") 44 1 45
1064 44 $content = _tune_utf8($content);
1065 }
1066 }
1067  
1068 100 my $request;
1069  
1070 100 ▶ if ($method eq 'GET') {
Branch: 2 branches
BranchTrueFalseTotal
if ($method eq 'GET') { } 76 24 100
elsif ($content) { } 22 2 24
1071 76 ▶ if ($content_type !~ m{^application/x-www-form-urlencoded(?:;|$)}) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $content_type =~ m[^application/x-www-form-urlencoded(?:;|$)]) { } 1 75 76
elsif ($content) { } 22 53 75
1072 1 die "Unable to create a get request with content_type: $content_type\n";
1073 }
1074 elsif ($content) {
1075 22 ▶ if ($url =~ m/\?/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($url =~ /\?/) { } 1 21 22
1076 1 $request = $self->prepare_request(%o, url => \"$url&$content");
1077 }
1078 else {
1079 21 $request = $self->prepare_request(%o, url => \"$url?$content");
1080 }
1081 }
1082 else {
1083 53 $request = $self->prepare_request(%o);
1084 }
1085 }
1086 elsif ($content) {
1087 22 $request = $self->prepare_request(%o);
1088 22 $request->content($content);
1089 }
1090 else {
1091 2 $request = $self->prepare_request(%o);
1092 }
1093  
1094 99 %o = (%o,
1095 request => $request,
1096 content => \$content,
1097 );
1098  
1099 99 ▶ if (my $do = $events->{before_headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"before_headers"}) 1 98 99
1100 1 $self->$do(%o);
1101 }
1102  
1103 99 my @keys;
1104  
1105 99 ▶ if (my $keys = $events->{headers_keys}) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $keys = $events->{'headers_keys'}) { } 1 98 99
elsif (my $add = $events->{'add_headers_keys'}) { } 2 96 98
1106 1 @keys = $self->$keys(%o);
1107 }
1108 elsif (my $add = $events->{add_headers_keys}) {
1109 2 my %seen;
1110 2 @keys = sort grep { !$seen{$_}++ } $self->$add(%o), keys %$headers;
1111 }
1112 else {
1113 96 @keys = sort keys %$headers;
1114 }
1115  
1116 99 foreach my $key ( @keys ) {
1117 26 ▶ if (my $do = $events->{before_header}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"before_header"}{$key}) 2 24 26
1118 2 $headers->{$key} = $self->$do(%o);
1119 }
1120  
1121 26 ▶ 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} 1 24 25
Condition83%5/6
$o{"skip_headers"}{$key} or not exists $headers->{$key} or not defined $headers->{$key}
l!l&&r!l&&!r
1124
$o{"skip_headers"}{$key} or not exists $headers->{$key}
l!l&&r!l&&!r
1025
MC/DC66%2/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 table75%3/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
1122  
1123 die "Header '$key' is an xBOOLEAN()/xCSV() marker - those are only "
1124 . "supported in body data (kvp2json/kvp2str), not headers\n"
1125 if ref $headers->{$key} eq 'HTTP::API::DataTypeMarker::BOOL'
1126 24 ▶ || 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 22 24
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
1122
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
1127  
1128 22 $request->header( $key => _encode_if_utf8_flagged( $headers->{$key} ) );
1129  
1130 22 ▶ if (my $do = $events->{after_header}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"after_header"}{$key}) 2 20 22
1131 2 $self->$do(%o);
1132 }
1133 }
1134  
1135 97 ▶ if (my $do = $events->{after_header_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"after_header_keys"}) 1 96 97
1136 1 $self->$do(%o);
1137 }
1138  
1139 97 return $request;
1140 }
1141  
1142 sub prepare_request {
1143 99 ▶ my ($self, %o) = @_;
Subroutine prepare_request: called CC=5 SCAR=16.1
Pod documented
1144  
1145 99 my ($method, $url) = map { $$_ } @o{qw(method url)};
1146  
1147 99 my ($headers) = @o{qw(headers)};
1148  
1149 99 my $request = HTTP::Request->new( $method => $url );
1150  
1151 99 $request->content_type($self->get_content_type(%o));
1152  
1153 99 my ($u, $p, $at) = map { _defor($self->$_, '') }
1154 qw(username password auth_token);
1155  
1156 99 ▶ if (length($u) || length($p)) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $u or length $p) { } 7 92 99
elsif (length $at) { } 5 87 92
Condition66%2/3
length $u or length $p
l!l&&r!l&&!r
7092
MC/DC50%1/2
length $u or length $p
length $u length $p
Truth table66%2/3
A or B
A= length $uB= length $p
ABresult
1X1
011
000
1157 7 $self->basic_authenticator( $request,
1158 _encode_if_utf8_flagged($u), _encode_if_utf8_flagged($p) );
1159 }
1160 elsif (length($at)) {
1161 $headers->{authorization} = $at
1162 5 ▶ unless grep { lc($_) eq 'authorization' } keys %$headers;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {lc $_ eq "authorization";} keys %$headers 3 2 5
1163 }
1164  
1165 99 return $request;
1166 }
1167  
1168 sub _tune_utf8 {
1169 46 ▶ my ($content) = @_;
Subroutine _tune_utf8: called CC=1 SCAR=0.0
1170  
1171 46 my $req = HTTP::Request->new( POST => "http://find-encoding.com" );
1172  
1173 try {
1174 46 ▶ $req->content($content);
Subroutine __ANON__: called CC=1 SCAR=0.0
1175 }
1176 catch {
1177 1 ▶ my $error = $_;
Subroutine __ANON__: called CC=2 SCAR=7.0
1178 1 ▶ if ( $error =~ /content must be bytes/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error =~ /content must be bytes/) 1 0 1
1179 1 eval { $content = Encode::encode( utf8 => $content ); };
1180 }
1181 46 };
1182 46 return $content;
1183 }
1184  
1185 sub _should_skip_key {
1186 160 ▶ my (%o) = @_;
Subroutine _should_skip_key: called CC=3 SCAR=11.0
1187 160 my ($key, $data) = @o{qw(key data)};
1188 160 ▶ 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
11158
$o{"skip_key"}{$key} or not exists $data->{$key}
l!l&&r!l&&!r
10159
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
1189 }
1190  
1191 sub _encode_if_utf8_flagged {
1192 336 ▶ my ($v) = @_;
Subroutine _encode_if_utf8_flagged: called CC=2 SCAR=6.9
1193 336 ▶ return utf8::is_utf8($v) ? Encode::encode( utf8 => $v ) : $v;
Branch: 1 branch
BranchTrueFalseTotal
utf8::is_utf8($v) ? : 6 330 336
1194 }
1195  
1196 sub _uri_escape_bytes_or_chars {
1197 300 ▶ my ($v) = @_;
Subroutine _uri_escape_bytes_or_chars: called CC=1 SCAR=0.0
1198 300 return uri_escape( _encode_if_utf8_flagged($v) );
1199 }
1200  
1201 sub _json_validate_utf8 {
1202 68 ▶ my ($v) = @_;
Subroutine _json_validate_utf8: called CC=3 SCAR=11.0
1203 68 ▶ return $v if utf8::is_utf8($v);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($v) 4 64 68
1204 64 my $decoded = eval { Encode::decode( utf8 => $v, Encode::FB_CROAK ) };
1205 64 ▶ die sprintf(
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decoded 4 60 64
1206 "kvp2json_each: value is not valid UTF-8, refusing to silently corrupt it into JSON (raw bytes: %v02x)\n",
1207 $v
1208 ) if !defined $decoded;
1209 60 return $decoded;
1210 }
1211  
1212 sub _numify_if_lossless {
1213 64 ▶ my ($v) = @_;
Subroutine _numify_if_lossless: called CC=5 SCAR=16.1
1214 64 ▶ return $v if !looks_like_number($v);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($v) 17 47 64
1215 # NaN/Infinity have no valid JSON representation - JSON::XS's utf8-mode
1216 # encoder emits them as the bareword nan/inf/-inf, which is not valid
1217 # JSON. Leave the original string untouched rather than numifying into
1218 # a token no JSON parser (including JSON::XS itself) can decode.
1219 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
1220 # Compare against a throwaway stringified copy, not $v+0 itself - comparing
1221 # a number with eq caches a string form on that same scalar (SvPOK), and
1222 # JSON::XS then encodes it as a JSON string instead of a JSON number.
1223 42 my $stringified = ($v + 0) . '';
1224 42 ▶ return $v eq $stringified ? $v + 0 : $v;
Branch: 1 branch
BranchTrueFalseTotal
$v eq $stringified ? : 37 5 42
1225 }
1226  
1227 sub convert_data {
1228 103 ▶ my ($self, %o) = @_;
Subroutine convert_data: called CC=4 SCAR=13.9
Pod documented
1229  
1230 103 my ($data, $events) = @o{qw(data events)};
1231  
1232 103 my $content_type = $self->get_content_type(%o);
1233  
1234 103 ▶ if ($content_type =~ m/json/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($content_type =~ /json/) { } 17 86 103
elsif ($content_type =~ m[^application/x-www-form-urlencoded(?:;|$)]) { } 84 2 86
1235 17 return $self->kvp2json(%o);
1236 }
1237 elsif ($content_type =~ m{^application/x-www-form-urlencoded(?:;|$)}) {
1238 84 return $self->kvp2str(%o);
1239 }
1240 else {
1241 2 ▶ return '' if !%$data;
Branch: 1 branch
BranchTrueFalseTotal
unless %$data 1 1 2
1242 1 die "Unable to convert data for content_type: $content_type\n";
1243 }
1244 }
1245  
1246 sub kvp2json {
1247 57 ▶ my ($self, %o) = @_;
Subroutine kvp2json: called CC=5 SCAR=16.1
Pod documented
1248  
1249 57 my ($data, $events) = @o{qw(data events)};
1250  
1251 57 my $json = _apply_charset( $self->json, $self->charset );
1252  
1253 56 my @keys;
1254  
1255 56 ▶ if (my $do = $events->{keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{'keys'}) { } 1 55 56
1256 1 @keys = $self->$do(%o);
1257 }
1258 else {
1259 55 @keys = keys %$data;
1260 }
1261  
1262 56 my %data = ();
1263  
1264 56 foreach my $key(@keys) {
1265 68 ▶ if ($events->{not_include}{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($events->{"not_include"}{$key}) 1 67 68
1266 next
1267 1 }
1268 67 ▶ next if _should_skip_key(%o, key => $key);
Branch: 1 branch
BranchTrueFalseTotal
if _should_skip_key(%o, "key", $key) 1 66 67
1269 66 $data{$key} = $self->kvp2json_each(%o, key => $key, value => $data->{$key});
1270 }
1271  
1272 50 return $json->encode(\%data);
1273 }
1274  
1275 sub kvp2json_each {
1276 100 ▶ my ($self, %o) = @_;
Subroutine kvp2json_each: called CC=12 SCAR=24.8
Pod documented
1277  
1278 100 my ($v) = map { _defor($_, '') } @o{qw( value )};
1279  
1280 100 ▶ if (UNIVERSAL::isa($v, 'CODE')) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($v, "CODE")) 8 92 100
1281 8 $v = $self->$v(%o);
1282 }
1283  
1284 100 ▶ if (!ref $v) {
Branch: 4 branches
BranchTrueFalseTotal
if (not ref $v) { } 57 43 100
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
1285 57 return _numify_if_lossless( _json_validate_utf8($v) );
1286 }
1287 elsif (ref $v eq 'HTTP::API::DataTypeMarker::BOOL') {
1288 27 my $inner = $v->[0];
1289 27 ▶ if ( ref $inner eq 'SCALAR' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inner eq "SCALAR") 22 5 27
1290 22 my $live_value = _defor( $$inner, '' );
1291 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
1292 7 return _numify_if_lossless( _json_validate_utf8($live_value) );
1293 }
1294 15 return $inner;
1295 }
1296 5 ▶ die "xBOOLEAN() only accepts a plain scalar or a scalar ref, not a "
Branch: 1 branch
BranchTrueFalseTotal
if ref $inner 1 4 5
1297 . ref($inner) . " ref\n" if ref $inner;
1298 4 return _numify_if_lossless( _json_validate_utf8( _defor( $inner, '' ) ) );
1299 }
1300 elsif (UNIVERSAL::isa($v, 'ARRAY')) {
1301 11 my @parts;
1302  
1303 11 foreach my $val(@$v) {
1304 26 push @parts, $self->kvp2json_each(%o, value => $val);
1305 }
1306  
1307 11 return \@parts;
1308 }
1309 elsif (UNIVERSAL::isa($v, 'HASH')) {
1310 4 my %parts;
1311  
1312 4 foreach my $key(keys %$v) {
1313 8 $parts{$key} = $self->kvp2json_each(%o, key => $key, value => $v->{$key});
1314 }
1315  
1316 4 return \%parts;
1317 }
1318  
1319 die "Unable to convert a " . ref($v) . " reference into JSON for key '"
1320 1 . _defor( $o{key}, '' ) . "' - wrap it in xBOOLEAN() if you meant a "
1321 . "live boolean/tracked value\n";
1322 }
1323  
1324 sub kvp2str {
1325 106 ▶ my ($self, %o) = @_;
Subroutine kvp2str: called CC=8 SCAR=20.8
Pod documented
1326  
1327 106 my ($data, $events) = @o{qw(data events)};
1328  
1329 106 my @keys = keys %$data;
1330  
1331 106 ▶ if (my $do = $events->{before_sorting_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"before_sorting_keys"}) 4 102 106
1332 4 $self->$do(%o, keys => \@keys);
1333 }
1334  
1335 106 ▶ if (my $do = $events->{keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{'keys'}) { } 3 103 106
1336 3 @keys = $self->$do(%o);
1337 }
1338 else {
1339 103 @keys = sort @keys;
1340 }
1341  
1342 106 ▶ if (my $do = $events->{after_sorting_keys}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $do = $events->{"after_sorting_keys"}) 1 105 106
1343 1 $self->$do(%o, keys => \@keys);
1344 }
1345  
1346 106 my @parts;
1347  
1348 106 foreach my $key(@keys) {
1349 94 ▶ next if $events->{not_include}{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $events->{"not_include"}{$key} 1 93 94
1350 93 ▶ next if _should_skip_key(%o, key => $key);
Branch: 1 branch
BranchTrueFalseTotal
if _should_skip_key(%o, "key", $key) 1 92 93
1351 92 my $part = $self->kvp2str_each(%o, key => $key, value => $data->{$key});
1352 88 ▶ push @parts, $part if length $part;
Branch: 1 branch
BranchTrueFalseTotal
if length $part 85 3 88
1353 }
1354  
1355 102 return join '&', @parts;
1356 }
1357  
1358 sub kvp2str_each {
1359 168 ▶ my ($self, %o) = @_;
Subroutine kvp2str_each: called CC=22 SCAR=30.9
Pod documented
1360  
1361 168 my ($raw_key, $v) = map { _defor($_, '') } @o{qw( key value )};
1362  
1363 168 my $k = _uri_escape_bytes_or_chars($raw_key);
1364  
1365 168 ▶ if (UNIVERSAL::isa($v, 'CODE')) {
Branch: 1 branch
BranchTrueFalseTotal
if (UNIVERSAL::isa($v, "CODE")) 8 160 168
1366 8 $v = $self->$v(%o, key => $k);
1367 }
1368  
1369 168 ▶ if (!ref $v) {
Branch: 5 branches
BranchTrueFalseTotal
if (not ref $v) { } 106 62 168
elsif (ref $v eq 'HTTP::API::DataTypeMarker::BOOL') { } 27 35 62
elsif (ref $v eq 'ARRAY') { } 15 20 35
elsif (ref $v eq 'HTTP::API::DataTypeMarker::CSV') { } 17 3 20
elsif (UNIVERSAL::isa($v, 'HASH')) { } 2 1 3
1370 106 $v = _uri_escape_bytes_or_chars($v);
1371  
1372 106 ▶ if ($o{no_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o{'no_key'}) { } 42 64 106
1373 42 return $v;
1374 }
1375 else {
1376 64 return "$k=$v";
1377 }
1378 }
1379 elsif (ref $v eq 'HTTP::API::DataTypeMarker::BOOL') {
1380 27 my $inner = $v->[0];
1381 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
1382 . ref($inner) . " ref\n" if ref $inner && ref $inner ne 'SCALAR';
1383 26 ▶ my $bool_value = ref $inner eq 'SCALAR' ? $$inner : $inner;
Branch: 1 branch
BranchTrueFalseTotal
ref $inner eq 'SCALAR' ? : 10 16 26
1384 26 my $escaped = _uri_escape_bytes_or_chars( _defor($bool_value, '') );
1385 26 ▶ return $o{no_key} ? $escaped : "$k=$escaped";
Branch: 1 branch
BranchTrueFalseTotal
$o{'no_key'} ? : 2 24 26
1386 }
1387 elsif (ref $v eq 'ARRAY') {
1388 15 my @parts;
1389  
1390 15 foreach my $val(@$v) {
1391 28 my $part = $self->kvp2str_each(%o, key => $raw_key, value => $val, no_key => 0);
1392 28 ▶ push @parts, $part if length $part;
Branch: 1 branch
BranchTrueFalseTotal
if length $part 28 0 28
1393 }
1394  
1395 15 ▶ return '' if !@parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 3 12 15
1396  
1397 12 ▶ return ($o{no_key} ? '&' : '') . join '&', @parts;
Branch: 1 branch
BranchTrueFalseTotal
$o{'no_key'} ? : 3 9 12
1398 }
1399 elsif (ref $v eq 'HTTP::API::DataTypeMarker::CSV') {
1400 17 my @csv;
1401 my @parts;
1402  
1403 17 foreach my $val(@$v) {
1404 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
1405  
1406 48 my $part = $self->kvp2str_each(%o, key => $raw_key, value => $val, no_key => 1);
1407  
1408 48 ▶ if ($part =~ m/&/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /&/) { } 3 45 48
1409 3 push @parts, $part;
1410 }
1411 else {
1412 45 push @csv, $part;
1413 }
1414 }
1415  
1416 17 ▶ my $csv = ($o{no_key} ? '' : "$k=") . join( ',', @csv);
Branch: 1 branch
BranchTrueFalseTotal
$o{'no_key'} ? : 1 16 17
1417  
1418 17 ▶ if (@parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts) 3 14 17
1419 3 return join '&', $csv, map { ( my $c = $_ ) =~ s/^&//; $c } @parts;
1420 }
1421  
1422 14 return $csv;
1423 }
1424 elsif (UNIVERSAL::isa($v, 'HASH')) {
1425 2 die "Unable to convert nested hash value for key '$k' into a form-urlencoded query string\n";
1426 }
1427  
1428 1 die "Unable to convert a " . ref($v) . " reference into a form-urlencoded "
1429 . "query string value for key '$k' - wrap it in xBOOLEAN() if you meant "
1430 . "a live boolean/tracked value\n";
1431 }
1432  
1433 sub basic_authenticator {
1434 7 ▶ my ($self, $req, $u, $p) = @_;
Subroutine basic_authenticator: called CC=1 SCAR=0.0
Pod documented
1435 7 return $req->headers->authorization_basic($u, $p);
1436 }
1437  
1438 sub _defor {
1439 2721 ▶ my ($default, $or) = @_;
Subroutine _defor: called CC=3 SCAR=11.0
1440 2721 ▶ return (defined($default) && length($default)) ? $default : $or;
Branch: 1 branch
BranchTrueFalseTotal
defined $default && length $default ? : 1627 1094 2721
Condition100%3/3
defined $default and length $default
!ll&&!rl&&r
7243701627
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
1441 }
1442  
1443 84 ▶no Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
1444  
1445 84 1;
↑ Summary DataTypeMarker.pm »