blib/lib/HTTP/Promise/Body/Form/Data.pm untested

filter: Statementstmt 0.0% 0 / 187 Branchbran 0.0% 0 / 66 Conditioncond 0.0% 0 / 67 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 354 CC 34 SCAR 51.0
CC
34
Cov
0%
make_parts
420.0
as_urlencoded
42.0
as_string
20.0
CRAP 164.6
1 ##----------------------------------------------------------------------------
2 ## Asynchronous HTTP Request and Promise - ~/lib/HTTP/Promise/Body/Form/Data.pm
3 ## Version v0.2.1
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2022/06/13
7 ## Modified 2026/03/09
8 ## All rights reserved.
9 ##
10 ##
11 ## This program is free software; you can redistribute it and/or modify it
12 ## under the same terms as Perl itself.
13 ##----------------------------------------------------------------------------
14 package HTTP::Promise::Body::Form::Data;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTTP::Promise' );
20 use parent qw( HTTP::Promise::Body::Form );
21 use vars qw( $VERSION $CRLF $DEBUG );
22 use Data::UUID;
23 our $CRLF = "\015\012";
24 our $VERSION = 'v0.2.1';
25 our $DEBUG = 0; # REMOVE ME
26 };
27  
28 use strict;
29 use warnings;
30  
31 sub init
32 {
33 my $self = shift( @_ );
34 $self->{order} = [];
35 $self->{debug} = $DEBUG;
36 $self->{_init_strict_use_sub} = 1;
37 $self->SUPER::init( @_ ) || return( $self->pass_error );
38 return( $self );
39 }
40  
41 sub as_string
42 {
43 my $self = shift( @_ );
44 my $opts = $self->_get_args_as_hash( @_ );
45 my $boundary = $opts->{boundary} || $self->boundary || Data::UUID->new->create_str;
46 my $eol = $opts->{eol} || $CRLF;
47 my $parts = $self->make_parts( $opts );
48 return( $self->pass_error ) if( !defined( $parts ) );
49 my $res = $self->new_scalar;
50 for( @$parts )
51 {
52 my $part = $_->as_string( $eol ) . $eol;
53 return( $self->pass_error( $_->error ) ) if( !defined( $part ) );
54 $$res .= "--${boundary}" . $eol . $part;
55 }
56 $res .= "--${boundary}--${eol}" if( $res->length );
57 return( $res );
58 }
59  
60 sub as_urlencoded
61 {
62 my $self = shift( @_ );
63 my $hash = {};
64 my $keys = $self->keys->sort;
65 my $process = sub
66 {
67 my( $n, $v ) = @_;
68 if( $self->_is_a( $v => 'HTTP::Promise::Body::Form::Field' ) )
69 {
70 my $this = $v;
71 $v = $this->as_string( binmode => 'utf-8' );
72 return( $self->pass_error( $this->error ) ) if( !defined( $v ) );
73 }
74 if( exists( $hash->{ $n } ) )
75 {
76 $hash->{ $n } = [$hash->{ $n }] if( ref( $hash->{ $n } ) ne 'ARRAY' );
77 push( @{$hash->{ $n }}, $v );
78 }
79 else
80 {
81 $hash->{ $n } = $v;
82 }
83 return(1);
84 };
85
86 foreach my $n ( @$keys )
87 {
88 my $v = $self->{ $n };
89 if( $self->_is_array( $v ) )
90 {
91 foreach my $v2 ( @$v )
92 {
93 $process->( $n, $v2 ) || return( $self->pass_error );
94 }
95 }
96 else
97 {
98 $process->( $n, $v ) || return( $self->pass_error );
99 }
100 }
101 $self->_load_class( 'HTTP::Promise::Body::Form' ) || return( $self->pass_error );
102 my $form = HTTP::Promise::Body::Form->new( $hash ) ||
103 return( $self->pass_error( HTTP::Promise::Body::Form->error ) );
104 return( $form );
105 }
106  
107 sub boundary { return( shift->_internal( 'boundary', '_set_get_scalar', @_ ) ); }
108  
109 # in HTTP::Promise::Body::Form::Data
110  
111 sub length
112 {
113 my $self = shift( @_ );
114 my $opts = $self->_get_args_as_hash( @_ );
115 my $eol = $opts->{eol} || $CRLF;
116 my $boundary = $opts->{boundary} || $self->boundary || Data::UUID->new->create_str;
117  
118 my $total = 0;
119 my $sep = '--' . $boundary . $eol;
120 my $end = '--' . $boundary . '--' . $eol;
121  
122 require bytes;
123 my $parts = $self->make_parts( $opts );
124 return( $self->pass_error ) if( !defined( $parts ) );
125  
126 foreach my $ent ( @$parts )
127 {
128 # leading boundary
129 $total += CORE::length( $sep );
130  
131 # body bytes + trailing CRLF
132 my $part = $ent->as_string( $eol );
133 return( $self->pass_error( $_->error ) ) if( !defined( $part ) );
134 # my $blen = bytes::length( $part );
135 # Ensure text parts are ASCII, use bytes::length for binary
136 my $blen = ( ref( $ent ) && $ent->is_binary ) ? bytes::length( $part ) : CORE::length( $part );
137 $total += $blen;
138 $total += CORE::length( $eol );
139 }
140  
141 # closing boundary
142 $total += CORE::length( $end );
143  
144 return( $total );
145 }
146  
147 sub make_parts
148 {
149 my $self = shift( @_ );
150 my $tie_obj = $self->_tie_object;
151 my $tie_flag = $tie_obj->enable;
152 $tie_obj->enable(1) if( !$tie_flag );
153 my $opts = $self->_get_args_as_hash( @_ );
154 my $order = $self->order;
155 my $keys = $self->_is_array( $opts->{fields} )
156 ? $self->new_array( $opts->{fields} )
157 : ( defined( $order ) && scalar( @$order ) )
158 ? $order
159 : $self->keys->sort;
160 $self->_load_class( 'HTTP::Promise::Entity' ) || return( $self->pass_error );
161 $self->_load_class( 'HTTP::Promise::Headers' ) || return( $self->pass_error );
162 my $parts = $self->new_array;
163  
164 my $process = sub
165 {
166 my( $n, $v ) = @_;
167 my( $headers, $body );
168 if( $self->_is_a( $v => 'HTTP::Promise::Body::Form::Field' ) )
169 {
170 $headers = $v->headers || HTTP::Promise::Headers->new;
171 $body = $v->body;
172 }
173 else
174 {
175 $headers = HTTP::Promise::Headers->new;
176 # $body = HTTP::Promise::Entity->new_body( string => $v ) ||
177 # return( $self->pass_error( HTTP::Promise::Entity->error ) );
178 if( $self->_is_a( $v => 'Module::Generic::File' ) )
179 {
180 $body = HTTP::Promise::Entity->new_body( file => $v );
181 }
182 else
183 {
184 $body = HTTP::Promise::Entity->new_body( string => $v );
185 }
186 if( !defined( $body ) )
187 {
188 return( $self->pass_error( HTTP::Promise::Entity->error ) );
189 }
190 }
191 my $dispo = $headers->content_disposition;
192 my $cd = $dispo
193 ? $headers->new_field( 'Content-Disposition' => $dispo )
194 : $headers->new_field( 'Content-Disposition' );
195 return( $self->pass_error( $headers->error ) ) if( !defined( $cd ) );
196 $cd->disposition( 'form-data' );
197 $cd->name( $n );
198  
199 if( $self->_is_a( $body => 'HTTP::Promise::Body::File' ) )
200 {
201 if( !$cd->filename )
202 {
203 my $basename = $body->basename;
204 $cd->filename( $basename );
205 }
206 # Set Content-Type per part when we can
207 my $raw_mime = $body->finfo->mime_type || 'application/octet-stream';
208 my $filename = $body->basename // '';
209  
210 $self->_load_class( 'HTTP::Promise::Stream' ) || return( $self->pass_error );
211 my $stream = HTTP::Promise::Stream->new( \'' ) || return( $self->pass_error( HTTP::Promise::Stream->error ) );
212  
213 # Determine encoding layers from file extensions (handles multiple encodings)
214 my $encodings = $stream->suffix2encoding( $filename );
215  
216 my $ctype;
217 if( $encodings->length )
218 {
219 my $enc_suffix = $stream->_encoding2suffix_map;
220 my %enc_suffixes = map{ $enc_suffix->{ $_ } => 1 }
221 grep{ exists( $enc_suffix->{ $_ } ) } @$encodings;
222 # Strip the encoding suffixes to find the inner format.
223 # reverse + pop removes the basename, leaving extensions outermost-first.
224 my @parts = reverse( split( /\./, $filename ) );
225 pop( @parts );
226 # Skip the encoding suffixes to reach the inner format extension
227 while( @parts && exists( $enc_suffixes{ $parts[0] } ) )
228 {
229 shift( @parts );
230 }
231 my $inner_ext = @parts ? lc( $parts[0] ) : '';
232 $ctype = ( $inner_ext eq 'tar' ) ? 'application/x-tar' : "$raw_mime";
233 $headers->header( 'Content-Encoding' => join( ', ', @$encodings ) );
234 }
235 else
236 {
237 $ctype = "$raw_mime";
238 }
239  
240 my $ctfld = $headers->new_field( 'Content-Type' ) || return( $self->pass_error( $headers->error ) );
241 $ctfld->type( $ctype );
242 $headers->content_type( "$ctfld" );
243 }
244 $headers->content_disposition( "$cd" );
245
246 my $ent = HTTP::Promise::Entity->new( headers => $headers, body => $body ) ||
247 return( $self->pass_error( HTTP::Promise::Entity->error ) );
248 $ent->name( $n );
249 return( $ent );
250 };
251  
252 foreach my $n ( @$keys )
253 {
254 my $v = $self->{ $n };
255 if( ref( $v ) eq 'ARRAY' )
256 {
257 foreach my $v2 ( @$v )
258 {
259 my $ent = $process->( $n, $v2 );
260 if( !defined( $ent ) )
261 {
262 $tie_obj->enable(0) if( !$tie_flag );
263 return( $self->pass_error );
264 }
265 $ent->name( $n );
266 $parts->push( $ent );
267 }
268 }
269 else
270 {
271 my $ent = $process->( $n, $v );
272 if( !defined( $ent ) )
273 {
274 $tie_obj->enable(0) if( !$tie_flag );
275 return( $self->pass_error );
276 }
277 $ent->name( $n );
278 $parts->push( $ent );
279 }
280 }
281 $tie_obj->enable(0) if( !$tie_flag );
282 return( $parts );
283 }
284  
285 sub new_field
286 {
287 my $self = shift( @_ );
288 $self->_load_class( 'HTTP::Promise::Body::Form::Field' ) || return( $self->pass_error );
289 my $f = HTTP::Promise::Body::Form::Field->new( @_ ) ||
290 return( $self->pass_error( HTTP::Promise::Body::Form::Field->error ) );
291 return( $f );
292 }
293  
294 sub open
295 {
296 my $self = shift( @_ );
297 my $s = $self->as_string;
298 return( $self->pass_error ) if( !defined( $s ) );
299 my $io = $s->open( @_ ) ||
300 return( $self->pass_error( $s->error ) );
301 return( $io );
302 }
303  
304 # sub order { return( shift->_set_get_array_as_object( 'order', @_ ) ); }
305 sub order { return( shift->_internal( 'order', '_set_get_array_as_object', @_ ) ); }
306 # sub order
307 # {
308 # my $self = shift( @_ );
309 # $self->_tie_object->enable(0);
310 # my $rv = $self->SUPER::_set_get_array_as_object( 'order', @_ );
311 # $self->_tie_object->enable(1);
312 # return( $rv );
313 # }
314  
315 sub print
316 {
317 my( $self, $fh ) = @_;
318 my $nread;
319 # Get output filehandle, and ensure that it's a printable object:
320 $fh ||= select;
321 return( $self->error( "Filehandle provided ($fh) is not a valid filehandle." ) ) if( !$self->_is_glob( $fh ) );
322 my $encoded = $self->as_string;
323 return( $self->pass_error ) if( !defined( $encoded ) );
324 CORE::print( $fh $$encoded ) || return( $self->error( "Unable to print on given filehandle '$fh': $!" ) );
325 return(1);
326 }
327  
328 sub size { return( shift->Module::Generic::Hash::length ); }
329  
330 sub _is_warnings_enabled { return( warnings::enabled( 'HTTP::Promise' ) ); }
331  
332 # NOTE: FREEZE is inherited
333  
334 # NOTE: STORABLE_freeze is inherited
335  
336 # NOTE: STORABLE_thaw is inherited
337  
338 # NOTE: THAW is inherited
339  
340 1;
341 # NOTE: POD
342 __END__
343  
344 =encoding utf-8
345  
346 =head1 NAME
347  
348 HTTP::Promise::Body::Form::Data - A multipart/form-data Representation Class
349  
350 =head1 SYNOPSIS
351  
352 use HTTP::Promise::Body::Form;
353 my $form = HTTP::Promise::Body::Form::Data->new;
354 my $form = HTTP::Promise::Body::Form::Data->new({
355 fullname => 'Jigoro Kano',
356 location => HTTP::Promise::Body::Form::Data->new_field(
357 name => 'location',
358 value => 'Tokyo',
359 ),
360 picture => HTTP::Promise::Body::Form::Data->new_field(
361 name => 'picture',
362 file => '/some/where/file.txt',
363 ),
364 });
365 my $form = HTTP::Promise::Body::Form::Data->new( $hash_ref );
366 my $form = HTTP::Promise::Body::Form::Data->new( q{e%3Dmc2} );
367 die( HTTP::Promise::Body::Form->error, "\n" ) if( !defined( $form ) );
368  
369 =head1 VERSION
370  
371 v0.2.1
372  
373 =head1 DESCRIPTION
374  
375 This class represents a C<form-data> content as key-value pairs and is designed to make construction and manipulation of C<multipart/form-data> easier. It inherits from L<HTTP::Promise::Body::Form>
376  
377 For C<x-www-form-urlencoded>, use L<HTTP::Promise::Body::Form> instead.
378  
379 Each key represents a C<form-data> field and its value can either be a simple string or a C<HTTP::Promise::Body::Form::Field> object.
380  
381 C<multipart/form-data> is the only valid Content-Type for sending multiple data. L<rfc7578 in section 4.3|https://tools.ietf.org/html/rfc7578#section-4.3> states: "[RFC2388] suggested that multiple files for a single form field be transmitted using a nested "multipart/mixed" part. This usage is deprecated."
382  
383 See also this L<Stackoverflow discussion|https://stackoverflow.com/questions/36674161/http-multipart-form-data-multiple-files-in-one-input/41204533#41204533> and L<this one too|https://stackoverflow.com/questions/51575746/http-header-content-type-multipart-mixed-causes-400-bad-request>
384  
385 =head1 CONSTRUCTOR
386  
387 =head2 new
388  
389 This takes an optional data, and some options and returns a new L<HTTP::Promise::Body::Form> object.
390  
391 Acceptable data are:
392  
393 =over 4
394  
395 =item An hash reference
396  
397 =item An url encoded string
398  
399 =back
400  
401 If a string is provided, it will be automatically decoded into an hash of name-value pairs. When a name is found more than once, its values are added as an array reference.
402  
403 my $form = HTTP::Promise::Body->new( 'name=John+Doe&foo=bar&foo=baz&foo=' );
404  
405 Would result in a C<HTTP::Promise::Body::Form> object containing:
406  
407 name => 'John Doe', foo => ['bar', 'baz', '']
408  
409 =head1 METHODS
410  
411 L<HTTP::Promise::Body::Form> inherits all the methods from L<Module::Generic::Hash>, and adds or override the following ones.
412  
413 =head2 as_string
414  
415 Provided with an hash or hash reference of options and this returns a L<scalar object|Module::Generic::Scalar> of the C<form-data> properly formatted as multipart elements.
416  
417 Be mindful of the size of the parts and that this is not cached, so each time this is called, it creates the parts.
418  
419 Supported options are:
420  
421 =over 4
422  
423 =item * C<boundary>
424  
425 A string used as a part delimiter. Note, however, that even if you provide this value, it will not replace the C<boundary> value of a C<HTTP::Promise::Body::Form::Field> C<Content-Disposition> field if it is set.
426  
427 If this is not provided, it will use the value set with L</boundary>, or in the last resort, a new one will be automatically generated using L<Data::UUID/create_str>
428  
429 =item * C<eol>
430  
431 The end-of-line terminator. This defaults to C<\015\012>
432  
433 =item * C<fields>
434  
435 An array reference of form field names. This is used to set the order of appearance.
436  
437 If not provided, it will default to alphabetic order.
438  
439 =back
440  
441 =head2 as_urlencoded
442  
443 This returns a new L<HTTP::Promise::Body::Form> object based on the current data, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
444  
445 =head2 boundary
446  
447 Sets or gets a boundary delimiter, used to separate parts in a C<multiparts/form-data>
448  
449 =head2 length
450  
451 Returns the size in bytes of this multipart form data. This is used to compute the total body size of the HTTP request.
452  
453 This is not to be confused with L</size>, which is used to get the number of parts in this object.
454  
455 =head2 make_parts
456  
457 Provided with an hash or hash reference of options and this returns an L<array object|Module::Generic::Array> of L<parts|HTTP::Promise::Entity>
458  
459 Note that at this point, the body is not encoded and the C<Content-Length> is not added. You can use L<HTTP::Promise::Entity/encode_body> on each part to encode a form part value.
460  
461 Supported options are:
462  
463 =over 4
464  
465 =item * C<boundary>
466  
467 A string used as a part delimiter. Note, however, that even if you provide this value, it will not replace the C<boundary> value of a C<HTTP::Promise::Body::Form::Field> C<Content-Disposition> field if it is set.
468  
469 If this is not provided, a new one will be automatically generated using L<Data::UUID/create_str>
470  
471 =item * C<fields>
472  
473 An array reference of form field names. This is used to set the order of appearance.
474  
475 If not provided, it will default to alphabetic order.
476  
477 =back
478  
479 =head2 new_field
480  
481 This takes an hash or hash reference of options and returns the new C<HTTP::Promise::Body::Form::Data> object, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
482  
483 Supported options are:
484  
485 =over 4
486  
487 =item * C<headers>
488  
489 This is optional. Either as L<HTTP::Promise::Headers> object or as an array reference.
490  
491 =item * C<name>
492  
493 Field name
494  
495 =item * C<value>
496  
497 Field value as a string, scalar reference or a L<file object|Module::Generic::File>
498  
499 =back
500  
501 =head2 open
502  
503 This transform all the C<form-data> elements into a proper C<multipart/form-data> using L</as_string> and returns a new L<Module::Generic::Scalar::IO> object.
504  
505 It then opens the scalar passing L<Module::Generic::Scalar/open> whatever arguments were provided and returns an L<Module::Generic::Scalar::IO> object.
506  
507 =head2 order
508  
509 Sets or gets an L<array object|Module::Generic::Array> of form fields in the desired order of appearance when stringified.
510  
511 =head2 print
512  
513 Provided with a valid filehandle, and this print the C<form-data> representation of the form fields and their values, to the given filehandle, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>
514  
515 =head2 size
516  
517 Returns the number of parts in this object.
518  
519 This is not to be confused with L</length>, which is used to get the size in bytes of the multipart form-data.
520  
521 =head1 THREAD-SAFETY
522  
523 L<HTTP::Promise::Body::Form::Data> is thread-safe for all operations, as it operates on per-object state and uses thread-safe external libraries.
524  
525 =head1 AUTHOR
526  
527 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
528  
529 =head1 SEE ALSO
530  
531 L<HTTP::Promise>, L<HTTP::Promise::Request>, L<HTTP::Promise::Response>, L<HTTP::Promise::Message>, L<HTTP::Promise::Entity>, L<HTTP::Promise::Headers>, L<HTTP::Promise::Body>, L<HTTP::Promise::Body::Form>, L<HTTP::Promise::Body::Form::Data>, L<HTTP::Promise::Body::Form::Field>, L<HTTP::Promise::Status>, L<HTTP::Promise::MIME>, L<HTTP::Promise::Parser>, L<HTTP::Promise::IO>, L<HTTP::Promise::Stream>, L<HTTP::Promise::Exception>
532  
533 L<Module::Generic::Scalar>
534  
535 =head1 COPYRIGHT & LICENSE
536  
537 Copyright(c) 2022 DEGUEST Pte. Ltd.
538  
539 All rights reserved.
540  
541 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
542  
543 =cut