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

filter: Statementstmt 0.0% 0 / 189 Branchbran 0.0% 0 / 90 Conditioncond 0.0% 0 / 74 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 391 CC 46 SCAR 41.0
CC
46
Cov
0%
encode
156.0
as_string
110.0
as_form_data
72.0
CRAP 60.2
1 ##----------------------------------------------------------------------------
2 ## Asynchronous HTTP Request and Promise - ~/lib/HTTP/Promise/Body/Form.pm
3 ## Version v0.2.4
4 ## Copyright(c) 2025 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2022/05/18
7 ## Modified 2025/08/30
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;
15 BEGIN
16 {
17 use strict;
18 use warnings;
19 warnings::register_categories( 'HTTP::Promise' );
20 use parent qw( Module::Generic::Hash );
21 use vars qw( $VERSION );
22 # use Nice::Try;
23 use URL::Encode::XS ();
24 our $VERSION = 'v0.2.4';
25 };
26  
27 use strict;
28 use warnings;
29  
30 sub new
31 {
32 my $this = shift( @_ );
33 if( @_ )
34 {
35 if( scalar( @_ ) > 1 )
36 {
37 my $data = [@_];
38 my $ref = $this->decode_to_hash( $data ) ||
39 return( $this->pass_error );
40 return( $this->SUPER::new( $ref ) );
41 }
42 else
43 {
44 my $data = shift( @_ );
45 if( ref( $data ) eq 'HASH' )
46 {
47 return( $this->SUPER::new( $data, @_ ) );
48 }
49 elsif( !ref( $data ) ||
50 ( ref( $data ) ne 'HASH' && overload::Method( $data => '""' ) ) )
51 {
52 my $ref = $this->decode_to_hash( "${data}" ) ||
53 return( $this->pass_error );
54 return( $this->SUPER::new( $ref, @_ ) );
55 }
56 else
57 {
58 return( $this->error( "Unsupported data type '", ref( $data ), "'." ) );
59 }
60 }
61 }
62 else
63 {
64 return( $this->SUPER::new );
65 }
66 }
67  
68 sub init
69 {
70 my $self = shift( @_ );
71 $self->{_init_strict_use_sub} = 1;
72 $self->SUPER::init( @_ ) || return( $self->pass_error );
73 return( $self );
74 }
75  
76 sub as_form_data
77 {
78 my $self = shift( @_ );
79 my $hash = {};
80 my $keys = $self->keys->sort;
81 $self->_load_class( 'HTTP::Promise::Body::Form' ) || return( $self->pass_error );
82 my $form = HHTP::Promise::Body::Form->new;
83 foreach my $n ( @$keys )
84 {
85 my $v = $self->{ $n };
86 if( $self->_is_array( $v ) )
87 {
88 foreach my $v2 ( @$v )
89 {
90 my $e = $self->_is_a( $v2 => 'HTTP::Promise::Body::Form::Field' )
91 ? $v2
92 : $form->new_field(
93 name => $n,
94 body => $v2,
95 );
96 if( exists( $form->{ $n } ) )
97 {
98 $form->{ $n } = [$form->{ $n }] unless( $self->_is_array( $form->{ $n } ) );
99 push( @{$form->{ $n }}, $e );
100 }
101 else
102 {
103 $form->{ $n } = $e;
104 }
105 }
106 }
107 else
108 {
109 my $e = $self->_is_a( $v => 'HTTP::Promise::Body::Form::Field' )
110 ? $v
111 : $form->new_field(
112 name => $n,
113 body => $v,
114 );
115 if( exists( $form->{ $n } ) )
116 {
117 $form->{ $n } = [$form->{ $n }] unless( $self->_is_array( $form->{ $n } ) );
118 push( @{$form->{ $n }}, $e );
119 }
120 else
121 {
122 $form->{ $n } = $e;
123 }
124 }
125 }
126 return( $form );
127 }
128  
129 sub as_string
130 {
131 my $self = shift( @_ );
132 my $keys = [];
133 if( @_ && $self->_is_array( $_[0] ) )
134 {
135 $keys = shift( @_ );
136 }
137 else
138 {
139 $keys = $self->keys->sort;
140 }
141 my @pairs = ();
142 # try-catch
143 local $@;
144 my $obj = $self->_tie_object;
145 # We need to temporarily enable public storage access, so we force enable to true, but put it back to what it was after.
146 my $flag = $obj->enable;
147 $obj->enable(1) if( !$flag );
148 eval
149 {
150 foreach my $n ( @$keys )
151 {
152 my $v = $self->{ $n };
153 if( ref( $v ) eq 'ARRAY' )
154 {
155 foreach my $v2 ( @$v )
156 {
157 if( $self->_is_a( $v2 => 'HTTP::Promise::Body::Form::Field' ) )
158 {
159 $v2 = $v2->body->as_string( binmode => 'utf-8' );
160 }
161 warn( "Found a value, within an array for item '$n', that is a reference (", overload::StrVal( $v2 ), "), but does not stringify.\n" ) if( ref( $v2 ) && !overload::Method( $v2 => '""' ) && $self->_is_warnings_enabled );
162 push( @pairs, join( '=', $n, URL::Encode::XS::url_encode_utf8( "$v2" ) ) );
163 }
164 }
165 else
166 {
167 if( $self->_is_a( $v => 'HTTP::Promise::Body::Form::Field' ) )
168 {
169 $v = $v->body->as_string( binmode => 'utf-8' );
170 }
171 warn( "Found a value, for form item '$n', that is a reference (", overload::StrVal( $v ), "), but does not stringify.\n" ) if( ref( $v ) && !overload::Method( $v => '""' ) && $self->_is_warnings_enabled );
172 push( @pairs, join( '=', $n, URL::Encode::XS::url_encode_utf8( "$v" ) ) );
173 }
174 }
175 };
176 $obj->enable(0) if( !$flag );
177 if( $@ )
178 {
179 return( $self->error( "Error while Trying to url-encode ", scalar( @$keys ), " form elements: $@" ) );
180 }
181 return( join( '&', @pairs ) );
182 }
183  
184 sub decode { return( shift->decode_to_array( @_ ) ); }
185  
186 sub decode_string
187 {
188 my $self = shift( @_ );
189 my $data = shift( @_ );
190 warn( "No data to url-decode was provided.\n" ) if( ( !defined( $data ) || !length( "$data" ) ) && $self->_is_warnings_enabled );
191 return( $self->error( "Invalid parameter provided. You can only pass a string or an object that stringifies." ) ) if( ref( $data ) && !overload::Method( $data => '""' ) );
192 my $decoded;
193 # try-catch
194 local $@;
195 eval
196 {
197 $decoded = URL::Encode::XS::url_decode_utf8( "${data}" );
198 };
199 if( $@ )
200 {
201 return( $self->error( "Error while Trying to url-decode ", length( $data ), " bytes of data: $@" ) );
202 }
203 return( $decoded );
204 }
205  
206 sub decode_to_array
207 {
208 my $self = shift( @_ );
209 my $data = shift( @_ );
210 # warn( "No data to url-decode was provided.\n" ) if( ( !defined( $data ) || !length( "$data" ) ) && $self->_is_warnings_enabled );
211 warn( "No data to url-decode was provided.\n" ) if( ( !defined( $data ) || !length( "$data" ) ) && $self->_is_warnings_enabled );
212 return( $self->error( "Invalid parameter provided. You can only pass a string or an object that stringifies." ) ) if( ref( $data ) && !overload::Method( $data => '""' ) );
213 my $ref;
214 # try-catch
215 local $@;
216 eval
217 {
218 $ref = URL::Encode::XS::url_params_flat( "${data}" );
219 };
220 if( $@ )
221 {
222 return( $self->error( "Error while Trying to url-decode ", length( $data ), " bytes of data: $@" ) );
223 }
224 return( $ref );
225 }
226  
227 sub decode_to_hash
228 {
229 my $self = shift( @_ );
230 my $ref = $self->_is_array( $_[0] ) ? shift( @_ ) : $self->decode_to_array( @_ );
231 return( $self->pass_error ) if( !defined( $ref ) );
232 my $hash = {};
233 while( my( $n, $v ) = splice( @$ref, 0, 2 ) )
234 {
235 if( exists( $hash->{ $n } ) )
236 {
237 $hash->{ $n } = [ $hash->{ $n } ] unless( ref( $hash->{ $n } ) eq 'ARRAY' );
238 push( @{$hash->{ $n }}, $v );
239 }
240 else
241 {
242 $hash->{ $n } = $v;
243 }
244 }
245 return( $hash );
246 }
247  
248 # TODO: This is redundant with code in as_string. as_string should be revamped to call encode()
249 sub encode
250 {
251 my $self = shift( @_ );
252 my $ref = shift( @_ );
253 return( $self->error( "Invalid argument provided. I was expecting an array or an hash reference." ) ) if( ref( $ref ) ne 'ARRAY' && ref( $ref ) ne 'HASH' );
254 # Work on a copy
255 my $this = ref( $ref ) eq 'ARRAY' ? [@$ref] : [%$ref];
256 return( '' ) if( !scalar( @$this ) );
257 my $rv;
258 my @pairs = ();
259 my $obj = $self->_tie_object;
260 # We need to temporarily enable public storage access, so we force enable to true, but put it back to what it was after.
261 my $flag = $obj->enable;
262 $obj->enable(1) if( !$flag );
263 # try-catch
264 local $@;
265 eval
266 {
267 while( my( $n, $v ) = splice( @$this, 0, 2 ) )
268 {
269 if( ref( $v ) eq 'ARRAY' )
270 {
271 foreach my $v2 ( @$v )
272 {
273 if( $self->_is_a( $v2 => 'HTTP::Promise::Body::Form::Field' ) )
274 {
275 $v2 = $v2->body->as_string( binmode => 'utf-8' );
276 }
277 warn( "Found a value, within an array for item '$n', that is a reference, but does not stringifies.\n" ) if( ref( $v2 ) && !overload::Method( $v2 => '""' ) && $self->_is_warnings_enabled );
278 push( @pairs, join( '=', $n, URL::Encode::XS::url_encode_utf8( "$v2" ) ) );
279 }
280 }
281 else
282 {
283 if( $self->_is_a( $v => 'HTTP::Promise::Body::Form::Field' ) )
284 {
285 $v = $v->body->as_string( binmode => 'utf-8' );
286 }
287 warn( "Found a value, for item '$n', that is a reference, but does not stringifies.\n" ) if( ref( $v ) && !overload::Method( $v => '""' ) && $self->_is_warnings_enabled );
288 push( @pairs, join( '=', $n, URL::Encode::XS::url_encode_utf8( "$v" ) ) );
289 }
290 }
291 $rv = join( '&', @pairs );
292 };
293 $obj->enable(0) if( !$flag );
294 if( $@ )
295 {
296 return( $self->error( "Error while Trying to url-encode ", scalar( @$this ), " elements provided: $@" ) );
297 }
298 return( $rv );
299 }
300  
301 sub encode_string
302 {
303 my $self = shift( @_ );
304 my $encoded;
305 # try-catch
306 local $@;
307 eval
308 {
309 $encoded = URL::Encode::XS::url_encode_utf8( shift( @_ ) );
310 };
311 if( $@ )
312 {
313 return( $self->error( "Error while trying to url-encode: $@" ) );
314 }
315 return( $encoded );
316 }
317  
318 sub length
319 {
320 require bytes;
321 return( bytes::length( shift->as_string( @_ ) ) );
322 }
323  
324 sub open
325 {
326 my $self = shift( @_ );
327 my $encoded = $self->as_string;
328 return( $self->pass_error ) if( !defined( $encoded ) );
329 my $s = $self->new_scalar( \$encoded ) ||
330 return( $self->pass_error );
331 my $io = $s->open( @_ ) ||
332 return( $self->pass_error( $s->error ) );
333 return( $io );
334 }
335  
336 sub print
337 {
338 my( $self, $fh ) = @_;
339 my $nread;
340 # Get output filehandle, and ensure that it's a printable object:
341 $fh ||= select;
342 return( $self->error( "Filehandle provided ($fh) is not a proper filehandle and its not a HTTP::Promise::IO object." ) ) if( !$self->_is_glob( $fh ) && !$self->_is_a( $fh => 'HTTP::Promise::IO' ) );
343 my $encoded = $self->as_string;
344 return( $self->pass_error ) if( !defined( $encoded ) );
345 $fh->print( $encoded ) || return( $self->error( "Unable to print on given filehandle '$fh': $!" ) );
346 return(1);
347 }
348  
349 sub _is_warnings_enabled { return( warnings::enabled( 'HTTP::Promise' ) ); }
350  
351 # NOTE: FREEZE is inherited
352  
353 # NOTE: STORABLE_freeze is inherited
354  
355 # NOTE: STORABLE_thaw is inherited
356  
357 # NOTE: THAW is inherited
358  
359 1;
360 # NOTE: POD
361 __END__
362  
363 =encoding utf-8
364  
365 =head1 NAME
366  
367 HTTP::Promise::Body::Form - x-www-form-urlencoded Data Class
368  
369 =head1 SYNOPSIS
370  
371 use HTTP::Promise::Body::Form;
372 my $form = HTTP::Promise::Body::Form->new;
373 my $form = HTTP::Promise::Body::Form->new( $hash_ref );
374 my $form = HTTP::Promise::Body::Form->new( q{e%3Dmc2} );
375 die( HTTP::Promise::Body::Form->error, "\n" ) if( !defined( $form ) );
376  
377 =head1 VERSION
378  
379 v0.2.4
380  
381 =head1 DESCRIPTION
382  
383 This class represents C<x-www-form-urlencoded> HTTP body. It inherits from L<Module::Generic::Hash>
384  
385 This is different from a C<multipart/form-data>. For this, please check the module L<HTTP::Promise::Body::Form::Data>
386  
387 =head1 CONSTRUCTOR
388  
389 =head2 new
390  
391 This takes an optional data, and some options and returns a new L<HTTP::Promise::Body::Form> object.
392  
393 Acceptable data are:
394  
395 =over 4
396  
397 =item An hash reference
398  
399 =item An url encoded string
400  
401 =back
402  
403 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.
404  
405 my $form = HTTP::Promise::Body->new( 'name=John+Doe&foo=bar&foo=baz&foo=' );
406  
407 Would result in a C<HTTP::Promise::Body::Form> object containing:
408  
409 name => 'John Doe', foo => ['bar', 'baz', '']
410  
411 As an historical note, C<x-www-form-urlencoded> is not an rfc-defined standard, and differs from URI encoding defined by L<rfc3986|https://tools.ietf.org/html/rfc3986> in that it uses C<+> to represent whitespace. It was L<defined back then by Mosaic|https://web.archive.org/web/19961220100435/http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html> as a non-standard way of encoding form data. This also L<this historical note|http://1997.webhistory.org/www.lists/www-talk.1993q3/0812.html> and this L<Stackoverflow discussion|https://stackoverflow.com/questions/42276418/why-does-x-www-form-urlencoded-begin-with-x-www-when-other-standard-content>.
412  
413 =head1 METHODS
414  
415 L<HTTP::Promise::Body::Form> inherits all the methods from L<Module::Generic::Hash>, and adds or override the following ones.
416  
417 =head2 as_form_data
418  
419 This returns a new L<HTTP::Promise::Body::Form::Data> object based on the current data, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>.
420  
421 =head2 as_string
422  
423 This returns a properly urlencoded representation of the name-value pairs stored in this hash object.
424  
425 Each value will be encoded into utf8 before being urlencoded. This is all done fast with L<URL::Encode::XS>
426  
427 =head2 decode
428  
429 Provided with an C<x-www-form-urlencoded> string and this will return a decoded string taking under account utf8 characters.
430  
431 my $params = $form->decode( 'tengu=%E5%A4%A9%E7%8B%97' );
432 # [ 'tengu', '天狗' ]
433  
434 If an error occurs, this will set an L<error object|Module::Generic/error> and return C<undef>
435  
436 =head2 decode_string
437  
438 Provided with an url-encoded string, included utf-8 string, and this returns its corresponding decoded version.
439  
440 my $deity = $form->decode( '%E5%A4%A9%E7%8B%97' );
441  
442 results in: C<天狗>
443  
444 =head2 decode_to_array
445  
446 Takes an C<x-www-form-urlencoded> string and returns an array reference of name-value pairs. If a name is seen more than once, its value will be an array reference.
447  
448 If an error occurs, this will set an L<error object|Module::Generic/error> and return C<undef>
449  
450 =head2 decode_to_hash
451  
452 Takes an C<x-www-form-urlencoded> string or an array reference of name-value pairs and returns an hash reference of name-value pairs.
453  
454 If a name is seen more than once, its value will be an array reference.
455  
456 If an error occurs, this will set an L<error object|Module::Generic/error> and return C<undef>
457  
458 =head2 encode
459  
460 Takes an array reference or an hash reference and this returns a properly url-encoded string representation.
461  
462 If an error occurs, this will set an L<error object|Module::Generic/error> and return C<undef>
463  
464 =head2 encode_string
465  
466 Takes a string and returns an encoded string. UTF-8 strings are ok too as long as they are in L<perl's internal representation|perlunicode>.
467  
468 If an error occurs, this will set an L<error object|Module::Generic/error> and return C<undef>
469  
470 =head2 length
471  
472 Returns the number of keys currently set in this key-value pairs held in the object.
473  
474 =head2 open
475  
476 This encodes the key-pairs as C<x-www-form-urlencoded> by calling L</as_string>, which returns a new L<scalar object|Module::Generic::Scalar>, opens it, passing whatever arguments it received to L<Module::Generic::Scalar/open> and return the resulting object upon success, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>
477  
478 =for Pod::Coverage pass_error
479  
480 =head2 print
481  
482 Provided with a valid filehandle, and this print the C<x-www-form-urlencoded> representation of the key-value pairs contained in this object, to the given filehandle, or upon error, sets an L<error|Module::Generic/error> and returns C<undef>
483  
484 =head1 THREAD-SAFETY
485  
486 L<HTTP::Promise::Body::Form::Data> is thread-safe for per-object operations, with proper handling of per-object state and external libraries. It supports multi-threaded environments, but since it inherits from L<Module::Generic::Hash>, who is also thread-safe, but still care must be taken when sharing objects across threads or modifying global variables.
487  
488 Key considerations for thread-safety:
489  
490 =over 4
491  
492 =item * B<Shared Variables>
493  
494 The global variable C<$KEY_OBJECT> controls whether references can be used as hash keys. It is not shared by default, so concurrent modifications in threads may cause race conditions. Use C<local> or the L</key_object> method to set it per-object:
495  
496 use threads;
497 my $h = HTTP::Promise::Body::Form::Data->new;
498 $h->key_object(1); # Thread-safe per object
499 my $ref = [];
500 $h->{ $ref } = "array"; # Safe
501  
502 =item * B<Hash Data>
503  
504 Hash data is stored in a tied hash (L<Module::Generic::TieHash>), which is per-object and thread-safe for independent operations. Operations like L</merge>, L</json>, and L</clone> operate on local data. However, concurrent modifications to a shared object are not thread-safe without synchronisation:
505  
506 use threads;
507 my $h = HTTP::Promise::Body::Form::Data->new( first_name => "John" );
508 lock( $h ); # Synchronize access
509 my @threads = map
510 {
511 threads->create(sub
512 {
513 lock( $h );
514 $h->merge({ last_name => "Doe" }); # Thread-safe with lock
515 });
516 } 1..5;
517 $_->join for( @threads );
518  
519 For best practices, create per-thread objects to avoid shared state:
520  
521 use threads;
522 my @threads = map
523 {
524 threads->create(sub
525 {
526 my $h = HTTP::Promise::Body::Form::Data->new( first_name => "John" );
527 $h->merge({ last_name => "Doe" }); # Thread-safe
528 });
529 } 1..5;
530 $_->join for @threads;
531  
532 =item * B<Serialisation>
533  
534 Serialisation methods (L</FREEZE>, L</THAW>) operate on per-object state, making them thread-safe:
535  
536 use threads;
537 use Storable;
538 my $h = HTTP::Promise::Body::Form::Data->new( age => 30 );
539 my $frozen = Storable::freeze( $h ); # Thread-safe
540  
541 =back
542  
543 For debugging in threaded environments:
544  
545 ls -l /proc/$$/fd # List open file descriptors
546  
547 =head1 AUTHOR
548  
549 Jacques Deguest E<lt>F<jack@deguest.jp>E<gt>
550  
551 =head1 SEE ALSO
552  
553 L<Specifications|https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#url-encoded-form-data>, L<old rfc1867|https://tools.ietf.org/html/rfc1867.html>
554  
555 L<rfc7578 on multipart/form-data|https://tools.ietf.org/html/rfc7578>
556  
557 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>
558  
559 =head1 COPYRIGHT & LICENSE
560  
561 Copyright(c) 2022 DEGUEST Pte. Ltd.
562  
563 All rights reserved.
564  
565 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
566  
567 =cut