Fastly/ApiClient.pm untested

filter: Statementstmt 0.0% 0 / 190 Branchbran 0.0% 0 / 102 Conditioncond 0.0% 0 / 45 MC/DCmcdc 0.0% 0 / 29 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 413 CC 52 SCAR 44.9
CC
52
Cov
0%
call_api
240.0
update_params_for_auth
156.0
deserialize
132.0
CRAP 89.0
1 =begin comment
2  
3 Fastly API
4  
5 Via the Fastly API you can perform any of the operations that are possible within the management console, including creating services, domains, and backends, configuring rules or uploading your own application code, as well as account operations such as user administration and billing reports. The API is organized into collections of endpoints that allow manipulation of objects related to Fastly services and accounts. For the most accurate and up-to-date API reference content, visit our [Developer Hub](https://www.fastly.com/documentation/reference/api/)
6  
7 The version of the API Spec document: 1.0.0
8 Contact: oss@fastly.com
9  
10 =end comment
11  
12 =cut
13  
14 #
15 # NOTE: This class is auto generated.
16 # Do not edit the class manually.
17 #
18 package WebService::Fastly::ApiClient;
19  
20 use strict;
21 use warnings;
22 use utf8;
23  
24 use MIME::Base64;
25 use LWP::UserAgent;
26 use HTTP::Headers;
27 use HTTP::Response;
28 use HTTP::Request::Common qw(DELETE POST GET HEAD PUT);
29 use HTTP::Status;
30 use URI::Query;
31 use JSON::MaybeXS qw(JSON to_json encode_json decode_json);
32 use URI::Escape;
33 use Scalar::Util 'blessed';
34 use Log::Any qw($log);
35 use Carp;
36 use Module::Runtime qw(use_module);
37  
38 use WebService::Fastly::Configuration;
39  
40 sub new {
41 my $class = shift;
42  
43 my $config;
44 if ( $_[0] && ref $_[0] && ref $_[0] eq 'WebService::Fastly::Configuration' ) {
45 $config = $_[0];
46 } else {
47 $config = WebService::Fastly::Configuration->new(@_);
48 }
49  
50 my (%args) = (
51 'ua' => LWP::UserAgent->new,
52 'config' => $config,
53 );
54  
55 return bless \%args, $class;
56 }
57  
58 # Set the user agent of the API client
59 #
60 # @param string $user_agent The user agent of the API client
61 #
62 sub set_user_agent {
63 my ($self, $user_agent) = @_;
64 $self->{http_user_agent}= $user_agent;
65 }
66  
67 # Set timeout
68 #
69 # @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
70 #
71 sub set_timeout {
72 my ($self, $seconds) = @_;
73 if (!looks_like_number($seconds)) {
74 croak('Timeout variable must be numeric.');
75 }
76 $self->{http_timeout} = $seconds;
77 }
78  
79 # make the HTTP request
80 # @param string $resourcePath path to method endpoint
81 # @param string $method method to call
82 # @param array $queryParams parameters to be place in query URL
83 # @param array $postData parameters to be placed in POST body
84 # @param array $headerParams parameters to be place in request header
85 # @return mixed
86 sub call_api {
87 my $self = shift;
88 my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_;
89  
90 # update parameters based on authentication settings
91 $self->update_params_for_auth($header_params, $query_params, $auth_settings);
92  
93 my $_url = $self->{config}{base_url} . $resource_path;
94  
95 # build query
96 if (%$query_params) {
97 $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify });
98 }
99  
100 # body data
101 if (defined $body_data) {
102 if (blessed $body_data && $body_data->can('to_hash')) {
103 $body_data = $body_data->to_hash;
104 }
105 # model to json string
106 $body_data = to_json($body_data);
107 }
108 my $_body_data = %$post_params ? $post_params : $body_data;
109  
110 # Make the HTTP request
111 my $_request;
112 if ($method eq 'POST') {
113 # multipart
114 $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
115 'form-data' : $header_params->{'Content-Type'};
116  
117 $_request = POST($_url, %$header_params, Content => $_body_data);
118  
119 }
120 elsif ($method eq 'PUT') {
121 # multipart
122 $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
123 'form-data' : $header_params->{'Content-Type'};
124  
125 $_request = PUT($_url, %$header_params, Content => $_body_data);
126  
127 }
128 elsif ($method eq 'GET') {
129 $_request = GET($_url, %$header_params);
130 }
131 elsif ($method eq 'HEAD') {
132 $_request = HEAD($_url, %$header_params);
133 }
134 elsif ($method eq 'DELETE') { #TODO support form data
135 $_request = DELETE($_url, %$header_params);
136 }
137 elsif ($method eq 'PATCH') { #TODO
138 }
139 else {
140 }
141  
142 $self->{ua}->timeout($self->{http_timeout} || $self->{config}{http_timeout});
143 $self->{ua}->agent($self->{http_user_agent} || $self->{config}{http_user_agent});
144  
145 $log->debugf("REQUEST: %s", $_request->as_string);
146 my $_response = $self->{ua}->request($_request);
147 $log->debugf("RESPONSE: %s", $_response->as_string);
148  
149  
150 if ($method ne 'GET' && $method ne 'HEAD') {
151 $self->{config}{rate_limit_remaining} = $_response->header( 'Fastly-RateLimit-Remaining' );
152 $self->{config}{rate_limit_reset} = $_response->header( 'Fastly-RateLimit-Reset' );
153 }
154  
155 unless ($_response->is_success) {
156 croak(sprintf "API Exception(%s): %s\n%s", $_response->code, $_response->message, $_response->content);
157 }
158  
159 return $_response->content;
160  
161 }
162  
163 # Take value and turn it into a string suitable for inclusion in
164 # the path, by url-encoding.
165 # @param string $value a string which will be part of the path
166 # @param boolean $allow_reserved if set to true, then value will not be url-encoded. Default false.
167 # @return string the serialized object
168 sub to_path_value {
169 my ($self, $value, $allow_reserved) = @_;
170 my $str = $self->to_string($value);
171 if (!$allow_reserved) {
172 $str = uri_escape($str);
173 }
174 return $str;
175 }
176  
177  
178 # Take value and turn it into a string suitable for inclusion in
179 # the query, by imploding comma-separated if it's an object.
180 # If it's a string, pass through unchanged. It will be url-encoded
181 # later.
182 # @param object $object an object to be serialized to a string
183 # @return string the serialized object
184 sub to_query_value {
185 my ($self, $object) = @_;
186 if (ref($object) eq 'ARRAY') {
187 return join(',', @$object);
188 } else {
189 return $self->to_string($object);
190 }
191 }
192  
193  
194 # Take value and turn it into a string suitable for inclusion in
195 # the header. If it's a string, pass through unchanged
196 # If it's a datetime object, format it in ISO8601
197 # @param string $value a string which will be part of the header
198 # @return string the header string
199 sub to_header_value {
200 my ($self, $value) = @_;
201 return $self->to_string($value);
202 }
203  
204 # Take value and turn it into a string suitable for inclusion in
205 # the http body (form parameter). If it's a string, pass through unchanged
206 # If it's a datetime object, format it in ISO8601
207 # @param string $value the value of the form parameter
208 # @return string the form string
209 sub to_form_value {
210 my ($self, $value) = @_;
211 return $self->to_string($value);
212 }
213  
214 # Take value and turn it into a string suitable for inclusion in
215 # the parameter. If it's a string, pass through unchanged
216 # If it's a datetime object, format it in ISO8601
217 # @param string $value the value of the parameter
218 # @return string the header string
219 sub to_string {
220 my ($self, $value) = @_;
221 if (ref($value) eq "DateTime") { # datetime in ISO8601 format
222 return $value->datetime();
223 }
224 else {
225 return $value;
226 }
227 }
228  
229 # Deserialize a JSON string into an object
230 #
231 # @param string $class class name is passed as a string
232 # @param string $data data of the body
233 # @return object an instance of $class
234 sub deserialize
235 {
236 my ($self, $class, $data) = @_;
237 $log->debugf("deserializing %s for %s", $data, $class);
238  
239 if (not defined $data) {
240 return undef;
241 } elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash
242 if ($class =~ /^HASH\[(.*),(.*)\]$/) {
243 my ($key_type, $type) = ($1, $2);
244 my %hash;
245 my $decoded_data = decode_json $data;
246 foreach my $key (keys %$decoded_data) {
247 if (ref $decoded_data->{$key} eq 'HASH') {
248 $hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key});
249 } else {
250 $hash{$key} = $self->deserialize($type, $decoded_data->{$key});
251 }
252 }
253 return \%hash;
254 } else {
255 #TODO log error
256 }
257 } elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data
258 return $data if $data eq '[]'; # return if empty array
259  
260 my $_sub_class = substr($class, 6, -1);
261 my $_json_data = decode_json $data;
262 my @_values = ();
263 foreach my $_value (@$_json_data) {
264 if (ref $_value eq 'ARRAY') {
265 push @_values, $self->deserialize($_sub_class, encode_json $_value);
266 } else {
267 push @_values, $self->deserialize($_sub_class, $_value);
268 }
269 }
270 return \@_values;
271 } elsif ($class eq 'DateTime') {
272 return DateTime->from_epoch(epoch => str2time($data));
273 } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) {
274 return $data;
275 } else { # model
276 my $_instance = use_module("WebService::Fastly::Object::$class")->new;
277 if (ref $data eq "HASH") {
278 return $_instance->from_hash($data);
279 } else { # string, need to json decode first
280 return $_instance->from_hash(decode_json $data);
281 }
282 }
283 }
284  
285 # return 'Accept' based on an array of accept provided
286 # @param [Array] header_accept_array Array fo 'Accept'
287 # @return String Accept (e.g. application/json)
288 sub select_header_accept
289 {
290 my ($self, @header) = @_;
291  
292 if (@header == 0 || (@header == 1 && $header[0] eq '')) {
293 return undef;
294 } elsif (grep(/^application\/json$/i, @header)) {
295 return 'application/json';
296 } else {
297 return join(',', @header);
298 }
299  
300 }
301  
302 # return the content type based on an array of content-type provided
303 # @param [Array] content_type_array Array fo content-type
304 # @return String Content-Type (e.g. application/json)
305 sub select_header_content_type
306 {
307 my ($self, @header) = @_;
308  
309 if (@header == 0 || (@header == 1 && $header[0] eq '')) {
310 return 'application/json'; # default to application/json
311 } elsif (grep(/^application\/json$/i, @header)) {
312 return 'application/json';
313 } else {
314 return join(',', @header);
315 }
316  
317 }
318  
319 # Get API key (with prefix if set)
320 # @param string key name
321 # @return string API key with the prefix
322 sub get_api_key_with_prefix
323 {
324 my ($self, $key_name) = @_;
325  
326 my $api_key = $self->{config}{api_key}{$key_name};
327  
328 return unless $api_key;
329  
330 my $prefix = $self->{config}{api_key_prefix}{$key_name};
331 return $prefix ? "$prefix $api_key" : $api_key;
332 }
333  
334 # update header and query param based on authentication setting
335 #
336 # @param array $headerParams header parameters (by ref)
337 # @param array $queryParams query parameters (by ref)
338 # @param array $authSettings array of authentication scheme (e.g ['api_key'])
339 sub update_params_for_auth {
340 my ($self, $header_params, $query_params, $auth_settings) = @_;
341  
342 return $self->_global_auth_setup($header_params, $query_params)
343 unless $auth_settings && @$auth_settings;
344  
345 # one endpoint can have more than 1 auth settings
346 foreach my $auth (@$auth_settings) {
347 # determine which one to use
348 if (!defined($auth)) {
349 # TODO show warning about auth setting not defined
350 }
351 elsif ($auth eq 'session_password_change') {
352 if ($self->{config}{username} || $self->{config}{password}) {
353 $header_params->{'Authorization'} = 'Basic ' . encode_base64($self->{config}{username} . ":" . $self->{config}{password});
354 }
355 }
356 elsif ($auth eq 'token') {
357 my $api_key = $self->get_api_key_with_prefix('Fastly-Key');
358 if ($auth eq 'token') {
359 $api_key //= $ENV{'FASTLY_API_TOKEN'};
360 }
361 if ($api_key) {
362 $header_params->{'Fastly-Key'} = $api_key;
363 }
364 }
365 elsif ($auth eq 'url_purge') {
366 if ($self->{config}{username} || $self->{config}{password}) {
367 $header_params->{'Authorization'} = 'Basic ' . encode_base64($self->{config}{username} . ":" . $self->{config}{password});
368 }
369 }
370 elsif ($auth eq 'username_and_password') {
371 if ($self->{config}{username} || $self->{config}{password}) {
372 $header_params->{'Authorization'} = 'Basic ' . encode_base64($self->{config}{username} . ":" . $self->{config}{password});
373 }
374 }
375 else {
376 # TODO show warning about security definition not found
377 }
378 }
379 }
380  
381 # The endpoint API class has not found any settings for auth. This may be deliberate,
382 # in which case update_params_for_auth() will be a no-op. But it may also be that the
383 # API Spec does not describe the intended authorization. So we check in the config for any
384 # auth tokens and if we find any, we use them for all endpoints;
385 sub _global_auth_setup {
386 my ($self, $header_params, $query_params) = @_;
387  
388 my $tokens = $self->{config}->get_tokens;
389 return unless keys %$tokens;
390  
391 # basic
392 if (my $uname = delete $tokens->{username}) {
393 my $pword = delete $tokens->{password};
394 $header_params->{'Authorization'} = 'Basic '.encode_base64($uname.":".$pword);
395 }
396  
397 # oauth
398 if (my $access_token = delete $tokens->{access_token}) {
399 $header_params->{'Authorization'} = 'Bearer ' . $access_token;
400 }
401  
402 # other keys
403 foreach my $token_name (keys %$tokens) {
404 my $in = $tokens->{$token_name}->{in};
405 my $token = $self->get_api_key_with_prefix($token_name);
406 if ($in eq 'head') {
407 $header_params->{$token_name} = $token;
408 }
409 elsif ($in eq 'query') {
410 $query_params->{$token_name} = $token;
411 }
412 else {
413 die "Don't know where to put token '$token_name' ('$in' is not 'head' or 'query')";
414 }
415 }
416 }
417  
418 1;