SelectPdf/ApiClient.pm

filter: Statementstmt 32.7% 54 / 165 Branchbran 8.3% 3 / 36 Conditioncond 11.1% 4 / 36 MC/DCmcdc 0.0% 0 / 22 Subroutinesub 39.2% 11 / 28 Podpod 45.0% 9 / 20 totaltotal 26.3% 81 / 307 CC 35 SCAR 39.5
CC
35
Cov
26%
readStandardResponseHeaders
182.0
processResponse
56.0
performPostAsMultipartFormData
42.0
CRAP 51.9
↑ Summary SelectPdf/PdfToTextClient.pm »
1 package SelectPdf::ApiClient;
2
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4
5 1 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use HTTP::Request::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use HTTP::Status qw(:constants :is status_message);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use SelectPdf::DemoExceptions;
Subroutine BEGIN: called CC=1 SCAR=0.0
10
11 1 ▶use constant MULTIPART_FORM_DATA_BOUNDARY => "------------SelectPdf_Api_Boundry_\$";
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use constant NEW_LINE => "\r\n";
Subroutine BEGIN: called CC=1 SCAR=0.0
13
14 1 our $VERSION = '1.6.0';
15
16 =head1 NAME
17
18 SelectPdf::ApiClient - Base class for API clients. Do not use this directly.
19
20 =head1 METHODS
21
22 =head2 new
23
24 ApiClient Constructor. Do not use this directly.
25 =cut
26 7 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
27 7 my $type = shift;
28 7 my $self = {};
29
30 # API endpoint
31 7 $self->{apiEndpoint} = "https://selectpdf.com/api2/convert/";
32
33 # API async jobs endpoint
34 7 $self->{apiAsyncEndpoint} = "https://selectpdf.com/api2/asyncjob/";
35
36 # API web elements endpoint
37 7 $self->{apiWebElementsEndpoint} = "https://selectpdf.com/api2/webelements/";
38
39 # Parameters that will be sent to the API.
40 7 $self->{parameters} = {};
41
42 # HTTP Headers that will be sent to the API.
43 7 $self->{headers} = {};
44
45 # Files that will be sent to the API.
46 7 $self->{files} = {};
47
48 # Binary data that will be sent to the API.
49 7 $self->{binaryData} = {};
50
51 # Number of pages of the pdf document resulted from the conversion.
52 7 $self->{numberOfPages} = 0;
53
54 # Job ID for asynchronous calls or for calls that require a second request.
55 7 $self->{jobId} = "";
56
57 # Last HTTP Code
58 7 $self->{lastHTTPCode} = "";
59
60 # Subscription monthly conversion limit, parsed from X-SelectPdf-Credits-Total.
61 # -1 indicates unlimited (Dedicated tier). Undef when the header is absent.
62 7 $self->{creditsTotal} = undef;
63
64 # Conversions remaining in the current month, parsed from X-SelectPdf-Credits-Remaining.
65 # -1 for unlimited subscriptions. Undef when the header is absent.
66 7 $self->{creditsRemaining} = undef;
67
68 # Endpoint mode of the most recent response, parsed from X-SelectPdf-Mode ("production" or "demo").
69 7 $self->{mode} = "";
70
71 # Server-side execution path of the most recent response, parsed from X-SelectPdf-Execution.
72 7 $self->{executionMode} = "";
73
74 # Ping interval in seconds for asynchronous calls. Default value is 3 seconds.
75 7 $self->{AsyncCallsPingInterval} = 3;
76
77 # Maximum number of pings for asynchronous calls. Default value is 1,000 pings.
78 7 $self->{AsyncCallsMaxPings} = 1000;
79
80 7 bless $self, $type;
81 7 return $self;
82 }
83
84 =head2 setApiEndpoint( $apiEndpoint )
85
86 Set a custom SelectPdf API endpoint. Do not use this method unless advised by SelectPdf.
87
88 $client->setApiEndpoint($apiEndpoint);
89
90 Parameters:
91
92 - $apiEndpoint API endpoint.
93 =cut
94 0 ▶sub setApiEndpoint {
Subroutine setApiEndpoint: not called CC=2 SCAR=17.9
Pod documented
95 0 my($self, $apiEndpoint) = @_;
96 0 ▶ $self->{apiEndpoint} = $apiEndpoint if defined($apiEndpoint);
Branch: 1 branch
BranchTrueFalseTotal
if defined $apiEndpoint 0 0 0
97 0 return $self->{apiEndpoint};
98 }
99
100 =head2 setApiAsyncEndpoint( $apiAsyncEndpoint )
101
102 Set a custom SelectPdf API endpoint for async jobs. Do not use this method unless advised by SelectPdf.
103
104 $client->setApiAsyncEndpoint($apiAsyncEndpoint);
105
106 Parameters:
107
108 - $apiAsyncEndpoint API async jobs endpoint.
109 =cut
110 0 ▶sub setApiAsyncEndpoint {
Subroutine setApiAsyncEndpoint: not called CC=2 SCAR=17.9
Pod documented
111 0 my($self, $apiAsyncEndpoint) = @_;
112 0 ▶ $self->{apiAsyncEndpoint} = $apiAsyncEndpoint if defined($apiAsyncEndpoint);
Branch: 1 branch
BranchTrueFalseTotal
if defined $apiAsyncEndpoint 0 0 0
113 0 return $self->{apiAsyncEndpoint};
114 }
115
116 =head2 setApiWebElementsEndpoint( $apiWebElementsEndpoint )
117
118 Set a custom SelectPdf API endpoint for web elements. Do not use this method unless advised by SelectPdf.
119
120 $client->setApiWebElementsEndpoint($apiWebElementsEndpoint);
121
122 Parameters:
123
124 - $apiWebElementsEndpoint API web elements endpoint.
125 =cut
126 0 ▶sub setApiWebElementsEndpoint {
Subroutine setApiWebElementsEndpoint: not called CC=2 SCAR=17.9
Pod documented
127 0 my($self, $apiWebElementsEndpoint) = @_;
128 0 ▶ $self->{apiWebElementsEndpoint} = $apiWebElementsEndpoint if defined($apiWebElementsEndpoint);
Branch: 1 branch
BranchTrueFalseTotal
if defined $apiWebElementsEndpoint 0 0 0
129 0 return $self->{apiWebElementsEndpoint};
130 }
131
132 # Reset the results of the previous call.
133 0 ▶sub resetResults {
Subroutine resetResults: not called CC=1 SCAR=6.9
Pod undocumented
134 0 my($self) = @_;
135
136 0 $self->{numberOfPages} = 0;
137 0 $self->{jobId} = "";
138 0 $self->{lastHTTPCode} = "";
139 0 $self->{creditsTotal} = undef;
140 0 $self->{creditsRemaining} = undef;
141 0 $self->{mode} = "";
142 0 $self->{executionMode} = "";
143 }
144
145 # Create the user agent used for API calls and set the request headers.
146 0 ▶sub createUserAgent {
Subroutine createUserAgent: not called CC=2 SCAR=17.9
Pod undocumented
147 0 my($self) = @_;
148
149 0 my $ua = LWP::UserAgent->new;
150 0 $ua->timeout(6000); # 6,000 seconds = 100 min
151
152 0 $self->{headers}{"selectpdf-api-client"} = "perl-$]-$VERSION";
153
154 0 foreach my $k (keys(%{ $self->{headers} })) {
155 0 $ua->default_header($k => $self->{headers}{$k});
156 }
157
158 0 return $ua;
159 }
160
161 # Send the request to the API.
162 #
163 # Responses can carry long headers (for example the web elements locations, when
164 # pdf_web_elements_selectors is set), so the default Net::HTTP limits (8 KB per header
165 # line, 128 header lines) are lifted for SelectPdf API calls only.
166 0 ▶sub sendRequest {
Subroutine sendRequest: not called CC=1 SCAR=6.9
Pod undocumented
167 0 my($self, $ua, $request) = @_;
168
169 0 require LWP::Protocol::http;
170 0 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (@LWP::Protocol::http::EXTRA_SOCK_OPTS, MaxLineLength => 0, MaxHeaderLines => 0);
171
172 0 return $ua->request($request);
173 }
174
175 # Read the standard X-SelectPdf-* response headers.
176 0 ▶sub readStandardResponseHeaders {
Subroutine readStandardResponseHeaders: not called CC=13 SCAR=52.0
Pod undocumented
177 0 my($self, $response) = @_;
178
179 0 my $pages = $response->header("X-SelectPdf-Pages");
180 0 ▶ if (defined($pages) and $pages =~ m/^\s*-?\d+\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pages and $pages =~ /^\s*-?\d+\s*$/) 0 0 0
Condition0%0/3
defined $pages and $pages =~ /^\s*-?\d+\s*$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $pages and $pages =~ /^\s*-?\d+\s*$/
defined $pages $pages =~ /^\s*-?\d+\s*$/
Truth table0%0/3
A and B
A= defined $pagesB= $pages =~ /^\s*-?\d+\s*$/
ABresult
0X0
100
111
181 0 $self->{numberOfPages} = int($pages);
182 }
183
184 0 my $jobId = $response->header("X-SelectPdf-Job-Id");
185 0 ▶ if (defined($jobId) and $jobId ne "") {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $jobId and $jobId ne "") 0 0 0
Condition0%0/3
defined $jobId and $jobId ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $jobId and $jobId ne ""
defined $jobId $jobId ne ""
Truth table0%0/3
A and B
A= defined $jobIdB= $jobId ne ""
ABresult
0X0
100
111
186 0 $self->{jobId} = $jobId;
187 }
188
189 0 my $total = $response->header("X-SelectPdf-Credits-Total");
190 0 ▶ if (defined($total) and $total =~ m/^\s*-?\d+\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $total and $total =~ /^\s*-?\d+\s*$/) 0 0 0
Condition0%0/3
defined $total and $total =~ /^\s*-?\d+\s*$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $total and $total =~ /^\s*-?\d+\s*$/
defined $total $total =~ /^\s*-?\d+\s*$/
Truth table0%0/3
A and B
A= defined $totalB= $total =~ /^\s*-?\d+\s*$/
ABresult
0X0
100
111
191 0 $self->{creditsTotal} = int($total);
192 }
193
194 0 my $remaining = $response->header("X-SelectPdf-Credits-Remaining");
195 0 ▶ if (defined($remaining) and $remaining =~ m/^\s*-?\d+\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining and $remaining =~ /^\s*-?\d+\s*$/) 0 0 0
Condition0%0/3
defined $remaining and $remaining =~ /^\s*-?\d+\s*$/
!ll&&!rl&&r
000
MC/DC0%0/2
defined $remaining and $remaining =~ /^\s*-?\d+\s*$/
defined $remaining $remaining =~ /^\s*-?\d+\s*$/
Truth table0%0/3
A and B
A= defined $remainingB= $remaining =~ /^\s*-?\d+\s*$/
ABresult
0X0
100
111
196 0 $self->{creditsRemaining} = int($remaining);
197 }
198
199 0 my $mode = $response->header("X-SelectPdf-Mode");
200 0 ▶ if (defined($mode) and $mode ne "") {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $mode and $mode ne "") 0 0 0
Condition0%0/3
defined $mode and $mode ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $mode and $mode ne ""
defined $mode $mode ne ""
Truth table0%0/3
A and B
A= defined $modeB= $mode ne ""
ABresult
0X0
100
111
201 0 $self->{mode} = $mode;
202 }
203
204 0 my $executionMode = $response->header("X-SelectPdf-Execution");
205 0 ▶ if (defined($executionMode) and $executionMode ne "") {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $executionMode and $executionMode ne "") 0 0 0
Condition0%0/3
defined $executionMode and $executionMode ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $executionMode and $executionMode ne ""
defined $executionMode $executionMode ne ""
Truth table0%0/3
A and B
A= defined $executionModeB= $executionMode ne ""
ABresult
0X0
100
111
206 0 $self->{executionMode} = $executionMode;
207 }
208 }
209
210 # Hook called after a successful response (200 or 202), with the HTTP::Response object.
211 # Subclasses can override it to capture endpoint-specific headers. Default implementation does nothing.
212 0 ▶sub onResponseHeadersReceived {
Subroutine onResponseHeadersReceived: not called CC=1 SCAR=6.9
Pod undocumented
213 0 my($self, $response) = @_;
214 }
215
216 # Process the API response.
217 #
218 # @returns Response content.
219 0 ▶sub processResponse {
Subroutine processResponse: not called CC=7 SCAR=40.3
Pod undocumented
220 0 my($self, $response) = @_;
221
222 0 my $code = $response->code;
223 0 $self->{lastHTTPCode} = $code;
224
225 0 ▶ if ($code == HTTP_OK) {
Branch: 2 branches
BranchTrueFalseTotal
if ($code == 200) { } 0 0 0
elsif ($code == 202) { } 0 0 0
226 0 $self->readStandardResponseHeaders($response);
227 0 eval { $self->onResponseHeadersReceived($response); };
228
229 0 return $response->decoded_content;
230 }
231 elsif ($code == HTTP_ACCEPTED) {
232 # request accepted (for asynchronous jobs)
233 0 $self->readStandardResponseHeaders($response);
234 0 eval { $self->onResponseHeadersReceived($response); };
235
236 0 return undef;
237 }
238 else {
239 0 my $message = $response->message;
240 0 my $content = $response->decoded_content;
241 0 ▶ if ($content) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content) 0 0 0
242 0 $message = $content;
243 }
244
245 # The demo endpoint returns JSON error bodies for 400 / 413 / 429 / 503.
246 # Parse those into typed exceptions so callers can react programmatically.
247 0 my $contentType = $response->header("Content-Type");
248 0 ▶ if (defined($contentType) and $contentType =~ m/application\/json/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $contentType and $contentType =~ m[application/json]i) 0 0 0
Condition0%0/3
defined $contentType and $contentType =~ m[application/json]i
!ll&&!rl&&r
000
MC/DC0%0/2
defined $contentType and $contentType =~ m[application/json]i
defined $contentType $contentType =~ m[application/json]i
Truth table0%0/3
A and B
A= defined $contentTypeB= $contentType =~ m[application/json]i
ABresult
0X0
100
111
249 0 my $demoException = SelectPdf::DemoException->fromResponse($code, $content, $response->header("Retry-After"));
250 0 ▶ die $demoException if defined($demoException);
Branch: 1 branch
BranchTrueFalseTotal
if defined $demoException 0 0 0
251 }
252
253 0 die "($code) $message";
254 }
255 }
256
257 # Create a POST request.
258 #
259 # @returns Response content.
260 0 ▶sub performPost {
Subroutine performPost: not called CC=1 SCAR=6.9
Pod undocumented
261 0 my($self) = @_;
262
263 # reset results
264 0 $self->resetResults();
265
266 # set headers
267 0 $self->{headers}{"Content-type"} = "application/x-www-form-urlencoded";
268
269 # prepare request
270 0 my $ua = $self->createUserAgent();
271
272 # call the API
273 0 my $response = $self->sendRequest($ua, POST($self->{apiEndpoint}, $self->{parameters}));
274
275 0 return $self->processResponse($response);
276 }
277
278 # Create a POST request.
279 #
280 # @returns Response content.
281 0 ▶sub performPostAsMultipartFormData {
Subroutine performPostAsMultipartFormData: not called CC=6 SCAR=37.4
Pod undocumented
282 0 my($self) = @_;
283
284 # reset results
285 0 $self->resetResults();
286
287 # prepare request
288 0 my $ua = $self->createUserAgent();
289
290 # merge parameters, files and binary data
291 0 my $alldata = {};
292 0 foreach my $k (keys(%{ $self->{parameters} })) {
293 0 my $v = $self->{parameters}{$k};
294 0 ▶ $v = Encode::encode('UTF-8', $v) if (defined($v) and utf8::is_utf8($v));
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and utf8::is_utf8($v) 0 0 0
Condition0%0/3
defined $v and utf8::is_utf8($v)
!ll&&!rl&&r
000
MC/DC0%0/2
defined $v and utf8::is_utf8($v)
defined $v utf8::is_utf8($v)
Truth table0%0/3
A and B
A= defined $vB= utf8::is_utf8($v)
ABresult
0X0
100
111
295 0 $alldata->{$k} = $v;
296 }
297 0 foreach my $k (keys(%{ $self->{files} })) {
298 0 $alldata->{$k} = [$self->{files}{$k}];
299 }
300 0 foreach my $k (keys(%{ $self->{binaryData} })) {
301 0 $alldata->{$k} = [undef, $k, Content_Type => 'application/octet-stream', Content => $self->{binaryData}{$k}];
302 }
303
304 # call the API
305 0 my $response = $self->sendRequest($ua, POST($self->{apiEndpoint}, Content_Type => 'form-data', Content => $alldata));
306
307 0 return $self->processResponse($response);
308 }
309
310 # Start an asynchronous job.
311 #
312 # @returns Asynchronous job ID.
313 0 ▶sub startAsyncJob {
Subroutine startAsyncJob: not called CC=1 SCAR=6.9
Pod undocumented
314 0 my($self) = @_;
315
316 0 $self->{parameters}{"async"} = "True";
317 0 $self->performPost();
318
319 0 return $self->{jobId};
320 }
321
322 # Start an asynchronous job that requires multipart form data.
323 #
324 # @returns Asynchronous job ID.
325 0 ▶sub startAsyncJobMultipartFormData {
Subroutine startAsyncJobMultipartFormData: not called CC=1 SCAR=6.9
Pod undocumented
326 0 my($self) = @_;
327
328 0 $self->{parameters}{"async"} = "True";
329 0 $self->performPostAsMultipartFormData();
330
331 0 return $self->{jobId};
332 }
333
334 =head2 getNumberOfPages
335
336 Get the number of pages of the PDF document resulted from the API call.
337
338 $pages = $client->getNumberOfPages();
339
340 Returns:
341
342 - Number of pages of the PDF document.
343 =cut
344 0 ▶sub getNumberOfPages {
Subroutine getNumberOfPages: not called CC=1 SCAR=6.9
Pod documented
345 0 my($self) = @_;
346 0 return $self->{numberOfPages};
347 }
348
349 =head2 getCreditsTotal
350
351 Get the subscription monthly conversion limit reported by the server (X-SelectPdf-Credits-Total response header).
352
353 $total = $client->getCreditsTotal();
354
355 Returns:
356
357 - Monthly conversion limit. -1 means unlimited (Dedicated tier). Undef when the most recent response did not include credit information (e.g. demo endpoint, error response).
358 =cut
359 0 ▶sub getCreditsTotal {
Subroutine getCreditsTotal: not called CC=1 SCAR=6.9
Pod documented
360 0 my($self) = @_;
361 0 return $self->{creditsTotal};
362 }
363
364 =head2 getCreditsRemaining
365
366 Get the number of conversions remaining in the current month, as reported by the server (X-SelectPdf-Credits-Remaining response header).
367
368 $remaining = $client->getCreditsRemaining();
369
370 Returns:
371
372 - Conversions remaining this month. -1 means unlimited (Dedicated tier). Undef when the most recent response did not include credit information.
373 =cut
374 0 ▶sub getCreditsRemaining {
Subroutine getCreditsRemaining: not called CC=1 SCAR=6.9
Pod documented
375 0 my($self) = @_;
376 0 return $self->{creditsRemaining};
377 }
378
379 =head2 getMode
380
381 Get the endpoint mode of the most recent response (X-SelectPdf-Mode response header).
382
383 $mode = $client->getMode();
384
385 Returns:
386
387 - "production" or "demo". Empty string when the response did not include the header.
388 =cut
389 1 ▶sub getMode {
Subroutine getMode: called CC=1 SCAR=0.0
Pod documented
390 1 my($self) = @_;
391 1 return $self->{mode};
392 }
393
394 =head2 getExecutionMode
395
396 Get the server-side execution path of the most recent conversion (X-SelectPdf-Execution response header).
397
398 $executionMode = $client->getExecutionMode();
399
400 Returns:
401
402 - "in-process" or "worker". Empty string for endpoints that do not perform a conversion (e.g. usage, web elements) or when the header is absent.
403 =cut
404 0 ▶sub getExecutionMode {
Subroutine getExecutionMode: not called CC=1 SCAR=6.9
Pod documented
405 0 my($self) = @_;
406 0 return $self->{executionMode};
407 }
408
409 # Serialize boolean values as "True" or "False" for the API.
410 #
411 # @returns Serialized value.
412 2 ▶sub serializeBoolean {
Subroutine serializeBoolean: called CC=8 SCAR=27.7
Pod undocumented
413 2 my($self, $value) = @_;
414
415 2 ▶ if (not defined($value) or $value eq 'undef') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value or $value eq 'undef') { } 0 2 2
Condition33%1/3
not defined $value or $value eq "undef"
l!l&&r!l&&!r
002
MC/DC0%0/2
not defined $value or $value eq "undef"
not defined $value $value eq "undef"
Truth table33%1/3
not(A) or B
A= not defined $valueB= $value eq "undef"
ABresult
1X1
011
000
416 0 $value = 0;
417 }
418 else {
419 2 $value =~ s/^\s+|\s+$//g;
420 2 $value = lc $value;
421
422 2 ▶ if ($value eq 'false' or $value eq 'no' or $value eq '0' or $value eq 'off') {
Branch: 1 branch
BranchTrueFalseTotal
if ($value eq "false" or $value eq "no" or $value eq 0 or $value eq "off") 0 2 2
Condition33%3/9
$value eq "false" or $value eq "no" or $value eq 0 or $value eq "off"
l!l&&r!l&&!r
002
$value eq "false" or $value eq "no" or $value eq 0
l!l&&r!l&&!r
002
$value eq "false" or $value eq "no"
l!l&&r!l&&!r
002
MC/DC0%0/4
$value eq "false" or $value eq "no" or $value eq 0 or $value eq "off"
$value eq "false" $value eq "no" $value eq 0 $value eq "off"
Truth table20%1/5
A or B or C or D
A= $value eq "false"B= $value eq "no"C= $value eq 0D= $value eq "off"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
423 0 $value = 0;
424 }
425 }
426 2 ▶ return $value ? 'True' : 'False';
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 2 0 2
427 }
428
429 1 1;
↑ Summary SelectPdf/PdfToTextClient.pm »