Sisyphus repository
Last update: 1 october 2023 | SRPMs: 18631 | Visits: 37825844
en ru br
ALT Linux repos
S:2.05-alt1

Group :: Development/Perl
RPM: perl-CGI-Expand

 Main   Changelog   Spec   Patches   Sources   Download   Gear   Bugs and FR  Repocop 

CGI-Expand-2.04/000075500000000000000000000000001222430454000132505ustar00rootroot00000000000000CGI-Expand-2.04/Changes000064400000000000000000000017551222430454000145530ustar00rootroot00000000000000Revision history for Perl extension CGI::Expand.

1.01 Thu Jan 8 15:22:08 2004
- Renamed and published to CPAN

1.02 Thu Jan 8 23:00:56 EST 2004
- Fixed bad README

1.03 Mon Jan 12 14:38:47 EST 2004
- Ignore /.[xy]$/ cgi parameters for image submits
- Add collapse_hash

1.06 Wed Dec 21 23:14:01 CET 2005
- Reworked the internals to be OO-ish for customization while keeping
the procedural interface.
- Deprecated the package variables $Max_reray && $Separator
and added warnings if they are used.
- The missing versions were unreleased

2.01 Wed Jan 18 12:53:27 CET 2006
- Avoid expanding tabs in Makefile.PL (RT#17125)
- Bump major version as 1.06 was quite different to 1.03

2.02 Mon Apr 10 15:02:26 CEST 2006
- Only write Makefile postamble on linux (caused trouble under Windows)

2.03 Fri Mar 25 13:35:30 EST 2011
- Documentation fix #56170 and tweaks (RJBS)

2.04 Mon Sep 23 10:22:11 EST 2013
- Add COPYRIGHT and LICENSE clarification
CGI-Expand-2.04/Expand.pm000064400000000000000000000314751222430454000150370ustar00rootroot00000000000000package CGI::Expand;
$VERSION = '2.04';
use strict;
use warnings;

# NOTE: Exporter is not actually used
our @EXPORT = qw(expand_cgi);
our @EXPORT_OK = qw(expand_hash collapse_hash);
my %is_exported = map { $_ => 1 } @EXPORT, @EXPORT_OK;

use Carp qw(croak carp);

sub import {
my $from_pkg = shift;
my $to_pkg = caller;

if(@_) {
for my $sub (@_) {
croak "Can't export symbol $sub" unless $is_exported{$sub};
}
} else {
@_ = @EXPORT;
}

_export_curried($from_pkg, $to_pkg, @_);
}

sub _export_curried {
my $from_pkg = shift;
my $to_pkg = shift;

no strict 'refs';
for my $sub (@_) {
# export requested subs with class arg curried
*{$to_pkg.'::'.$sub} = sub { $from_pkg->$sub(@_) };
# get inherited implementation with interface backward compatibility
}
}

sub separator {
if( defined $CGI::Expand::Separator ) {
carp '$CGI::Expand::Separator is deprecated'
unless $CGI::Expand::BackCompat;
return $CGI::Expand::Separator;
}
return '.';
}

sub max_array {
if( defined $CGI::Expand::Max_Array ) {
carp '$CGI::Expand::Max_Array is deprecated'
unless $CGI::Expand::BackCompat;
return $CGI::Expand::Max_Array;
}
return 100;
}

sub expand_cgi {
my $class = shift;
my $cgi = shift; # CGI or Apache::Request
my %args;

# permit multiple values CGI style
for ($cgi->param) {
next if (/\.[xy]$/); # img_submit=val & img_submit.x=20 -> clash
my @vals = $cgi->param($_);
$args{$_} = @vals > 1 ? \@vals : $vals[0];
}
return $class->expand_hash(\%args);
}

sub split_name {
my $class = shift;
my $name = shift;
my $sep = $class->separator();
$sep = "\Q$sep";

# These next two regexes are the escaping aware equivalent
# to the following:
# my ($first, @segments) = split(/\./, $name, -1);

# m// splits on unescaped '.' chars. Can't fail b/c \G on next
# non ./ * -> escaped anything -> non ./ *
$name =~ m/^ ( [^\\$sep]* (?: \\(?:.|$) [^\\$sep]* )* ) /gx;
my $first = $1;
$first =~ s/\\(.)/$1/g; # remove escaping

my (@segments) = $name =~
# . -> ( non ./ * -> escaped anything -> non ./ * )
m/\G (?:[$sep]) ( [^\\$sep]* (?: \\(?:.|$) [^\\$sep]* )* ) /gx;
# Escapes removed later, can be used to avoid using as array index

return ($first, @segments);
}

sub expand_hash {
my $class = shift;
my $flat = shift;
my $deep = {};
my $sep = $class->separator;

for my $name (keys %$flat) {

my ($first, @segments) = $class->split_name($name);

my $box_ref = \$deep->{$first};
for (@segments) {
if($class->max_array && /^(0|[1-9]\d*)$/) {
croak "CGI param array limit exceeded $1 for $name=$_"
if($1 >= $class->max_array);
$$box_ref = [] unless defined $$box_ref;
croak "CGI param clash for $name=$_"
unless ref $$box_ref eq 'ARRAY';
$box_ref = \($$box_ref->[$1]);
} else {
s/\\(.)/$1/g if $sep; # remove escaping
$$box_ref = {} unless defined $$box_ref;
croak "CGI param clash for $name=$_"
unless ref $$box_ref eq 'HASH';
$box_ref = \($$box_ref->{$_});
}
}
croak "CGI param clash for $name value $flat->{$name}"
if defined $$box_ref;
$$box_ref = $flat->{$name};
}
return $deep;
}

{

sub collapse_hash {
my $class = shift;
my $deep = shift;
my $flat = {};

$class->_collapse_hash($deep, $flat, () );
return $flat;
}

sub join_name {
my $class = shift;
my $sep = substr($class->separator, 0, 1);
return join $sep, @_;
}

sub _collapse_hash {
my $class = shift;
my $deep = shift;
my $flat = shift;
# @_ is now segments

if(! ref $deep) {
my $name = $class->join_name(@_);
$flat->{$name} = $deep;
} elsif(ref $deep eq 'HASH') {
for (keys %$deep) {
# escape \ and separator chars (once only, at this level)
my $name = $_;
if (defined (my $sep = $class->separator)) {
$sep = "\Q$sep";
$name =~ s/([\\$sep])/\\$1/g
}
$class->_collapse_hash($deep->{$_}, $flat, @_, $name);
}
} elsif(ref $deep eq 'ARRAY') {
croak "CGI param array limit exceeded $#$deep for ",
$class->join_name(@_)
if($#$deep+1 >= $class->max_array);

for (0 .. $#$deep) {
$class->_collapse_hash($deep->[$_], $flat, @_, $_)
if defined $deep->[$_];
}
} else {
croak "Unknown reference type for ",$class->join_name(@_),":",ref $deep;
}
}

}

1;
__END__

=pod

=head1 NAME

CGI::Expand - convert flat hash to nested data using TT2's dot convention

=head1 SYNOPSIS

use CGI::Expand ();
use CGI; # or Apache::Request, etc.

$args = CGI::Expand->expand_cgi( CGI->new('a.0=3&a.2=4&b.c.0=x') );

Or, as an imported function for convenience:

use CGI::Expand;
use CGI; # or Apache::Request, etc.

$args = expand_cgi( CGI->new('a.0=3&a.2=4&b.c.0=x') );
# $args = { a => [3,undef,4], b => { c => ['x'] }, }

# Or to catch exceptions:
eval {
$args = expand_cgi( CGI->new('a.0=3&a.2=4&b.c.0=x') );
} or log_and_exit( $@ );

#-----
use CGI::Expand qw(expand_hash);

$args = expand_hash({'a.0'=>77}); # $args = { a => [ 77 ] }

=head1 DESCRIPTION

Converts a CGI query into structured data using a dotted name
convention similar to TT2.

C<expand_cgi> works with CGI.pm, Apache::Request or anything with an
appropriate "param" method. Or you can use C<expand_hash> directly.

If you prefer to use a different flattening convention then CGI::Expand
can be subclassed.

=head1 MOTIVATION

The Common Gateway Interface restricts parameters to name=value pairs,
but often we'd like to use more structured data. This module
uses a name encoding convention to rebuild a hash of hashes, arrays
and values. Arrays can either be indexed explicitly or from CGI's
multi-valued parameter handling.

The generic nature of this process means that the core components
of your system can remain CGI ignorant and operate on structured data.
Better for modularity, better for testing.

=head1 DOT CONVENTION

The key-value pair "a.b.1=hi" expands to the perl structure:

{ a => { b => [ undef, "hi" ] }

The key ("a.b.1") specifies the location at which the value
("hi") is stored. The key is split on '.' characters, the
first segment ("a") is a key in the top level hash,
subsequent segments may be keys in sub-hashes or
indices in sub-arrays. Integer segments are treated
as array indices, others as hash keys.

Array size is limited to 100 by default. The limit can be altered
by subclassing or using the deprecated $Max_Array package variable.
See below.

The backslash '\' escapes the next character in cgi parameter names
allowing '.' , '\' and digits in hash keys. The escaping
'\' is removed. Values are not altered.

=head2 Key-Value Examples

# HoHoL
a.b.1=hi ---> { a => { b => [ undef, "hi" ] }

# HoLoH
a.1.b=hi ---> { a => [ undef, { b => "hi" } ] }

# top level always a hash
9.0=hi ---> { "9" => [ "hi" ] }

# can backslash escape to treat digits hash as keys
a.\0=hi ---> { "a" => { 0 => "hi"} }

# or to put . and \ literals in keys
a\\b\.c=hi --- { 'a\\b\.c' => "hi" }

=head1 METHODS / FUNCTIONS

The routines listed below are all methods, but can be imported to be called as
functions. In other words, you can call C<< CGI::Expand->expand_hash(...) >>
or you can import C<expand_hash> and then call C<expand_hash(...)> without
using method invocation syntax.

C<expand_cgi> is exported by default. C<expand_hash> and C<collapse_hash> are
exported upon request.

=over 4

=item expand_cgi

my $deep_hash = expand_cgi ( $CGI_object_or_similar );

Takes a CGI object and returns a hashref for the expanded
data structure (or dies, see L<"EXCEPTIONS">).

Wrapper around expand_hash that uses the "param" method of
the CGI object to collect the names and values.

Handles multivalued parameters as array refs
(although they can't be mixed with indexed arrays and
will have an undefined ordering).

$query = 'a.0=3&a.2=4&b.c.0=x&c.0=2&c.1=3&d=&e=1&e=2';

$args = expand_cgi( CGI->new($query) );

# result:
# $args = {
# a => [3,undef,4],
# b => { c => ['x'] },
# c => ['2','3'],
# d => '',
# e => ['1','2'], # order depends on CGI/etc
# };

=item expand_hash

my $deep_hash = expand_hash( $flat_hash );

Expands the keys of the parameter hash according
to the dot convention (or dies, see L<"EXCEPTIONS">).

$args = expand_hash({ 'a.b.1' => [1,2] });
# $args = { a => { b => [undef, [1,2] ] } }

=item collapse_hash

my $flat_hash = collapse_hash( $deep_hash );

The inverse of expand_hash. Converts the $deep_hash data structure
back into a flat hash.

$flat = collapse_hash({ a => { b => [undef, [1,2] ] } });
# $flat = { 'a.b.1.0' => 1, 'a.b.1.1' => 2 }

=back

=head1 EXCEPTIONS

B<WARNING>: The I<users> of your site can cause these exceptions
so you must decide how they are handled (possibly by letting
the process die).

=over 4

=item "CGI param array limit exceeded..."

If an array index exceeds the array limit (default: 100)
then an exception is thrown.

=item "CGI param clash for..."

A cgi query like "a=1&a.b=1" would require the value of $args->{a}
to be both 1 and { b => 1 }. Such type inconsistencies
are reported as exceptions. (See test.pl for for examples)

=back

=head1 SUBCLASSING

Subclassing in now the preferred way to change the behaviour and
defaults. (Previously package variables were used, see test.pl).

The methods which may be overriden by subclasses are separator,
max_array, split_name and join_name.

=over 4

=item max_array

$subclass->max_Array;

The limit for the array size, defaults to 100. The value 0 can be
used to disable the use of arrays, everthing is a hash key.

=item separator

$subclass->separator;

Returns the separator charaters used to split the keys of the flat hash.
The default is '.' but multiple characters are allowed. The default
join will use the first character.

If there is no separator then '\' escaping does not occur.
This is for use with split_name and join_name below.

=item split_name

my @segments = $subclass->split_name($name);

The split_name method must break $name in to key segments for the
nested data structure. The default version just splits on the
separator characters with a bit of fiddling to handle escaping.

=item join_name

my $name = $subclass->join_name(@segments);

The inverse of split_name, joins the segments back to the key for
the flat hash. The default version uses the first character of the
string returned by the separator method.

=back

=head1 DEPRECATIONS

$CGI::Expand::Separator and $CGI::Expand::Max_Array are deprecated.
They still work for now but emit a warning (supressed with
$CGI::Expand::BackCompat = 1)

Using the functions by their fully qualified names ceased to work
at around version 1.04. They're now class methods so just replace
the last :: with ->.

=head1 LIMITATIONS

The top level is always a hash. Consequently, any digit only names
will be keys in this hash rather than array indices.

Image inputs with name.x, name.y coordinates are ignored as they
will class with the value for name.

=head1 TODO

Thing about ways to keep $cgi and the expanded version in sync

Glob style parameters (with SCALAR, ARRAY and HASH slots)
would resolve the type clashes, probably no fun to use.
Look at using L<Template::Plugin::StringTree> to avoid path clashes

=head1 SEE ALSO

=over 4

=item *

L<HTTP::Rollup> - Replaces CGI.pm completely, no list ordering.

=item *

L<CGI::State> - Tied to CGI.pm, unclear error checking

=item *

L<Template::Plugin::StringTree>

=item *

L<Hash::Flatten> - Pick your delimiters

=item *

http://template-toolkit.org/pipermail/templates/2002-January/002368.html

=item *

There's a tiny and beautiful reduce solution somewhere on perlmonks.

=back

=head1 AUTHOR

Brad Bowman E<lt>cgi-expand@bereft.netE<gt>

Pod corrections: Ricardo Signes

=head1 COPYRIGHT

Copyright (C) 2004-2013, Brad Bowman.

=head1 LICENSE

CGI::Expand is free software; you can redistribute it and/or modify it under
the terms of either:

a) the L<GNU General Public License|perlgpl> as published by the Free
Software Foundation; either version 1, or (at your option) any
later version, or

b) the L<"Artistic License"|perlartistic> which comes with Perl.

For more details, see the full text of the licenses at
<http://www.perlfoundation.org/artistic_license_1_0>,
and <http://www.gnu.org/licenses/gpl-1.0.html>.

=cut
CGI-Expand-2.04/MANIFEST000064400000000000000000000003311222430454000143760ustar00rootroot00000000000000Changes
Expand.pm
MANIFEST
Makefile.PL
README
test.pl
META.yml Module meta-data (added by MakeMaker)
META.json Module JSON meta-data (added by MakeMaker)
CGI-Expand-2.04/META.json000064400000000000000000000016611222430454000146750ustar00rootroot00000000000000{
"abstract" : "convert flat hash to nested data using TT2's dot convention",
"author" : [
"Brad Bowman <cgi-expand@bereft.net>"
],
"dynamic_config" : 1,
"generated_by" : "ExtUtils::MakeMaker version 6.66, CPAN::Meta::Converter version 2.120921",
"license" : [
"perl_5"
],
"meta-spec" : {
"url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec",
"version" : "2"
},
"name" : "CGI-Expand",
"no_index" : {
"directory" : [
"t",
"inc"
]
},
"prereqs" : {
"build" : {
"requires" : {
"ExtUtils::MakeMaker" : "0"
}
},
"configure" : {
"requires" : {
"ExtUtils::MakeMaker" : "0"
}
},
"runtime" : {
"requires" : {
"Test::Exception" : "0",
"Test::More" : "0"
}
}
},
"release_status" : "stable",
"version" : "2.04"
}
CGI-Expand-2.04/META.yml000064400000000000000000000010351222430454000145200ustar00rootroot00000000000000---
abstract: "convert flat hash to nested data using TT2's dot convention"
author:
- 'Brad Bowman <cgi-expand@bereft.net>'
build_requires:
ExtUtils::MakeMaker: 0
configure_requires:
ExtUtils::MakeMaker: 0
dynamic_config: 1
generated_by: 'ExtUtils::MakeMaker version 6.66, CPAN::Meta::Converter version 2.120921'
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: 1.4
name: CGI-Expand
no_index:
directory:
- t
- inc
requires:
Test::Exception: 0
Test::More: 0
version: 2.04
CGI-Expand-2.04/Makefile.PL000064400000000000000000000017161222430454000152270ustar00rootroot00000000000000use ExtUtils::MakeMaker;
# See lib/ExtUtils/MakeMaker.pm for details of how to influence
# the contents of the Makefile that is written.

BEGIN {
*MY::postamble = \&postamble if $^O =~ /^linux/i;
}

WriteMakefile(
'NAME' => 'CGI::Expand',
'VERSION_FROM' => 'Expand.pm', # finds $VERSION
'PREREQ_PM' => {
'Test::Exception' => 0,
'Test::More' => 0,
}, # e.g., Module::Name => 1.1
LICENSE => 'perl',

($] >= 5.005 ? ## Add these new keywords supported since 5.005
(ABSTRACT_FROM => 'Expand.pm', # retrieve abstract from module
AUTHOR => 'Brad Bowman <cgi-expand@bereft.net>') : ()),

);

# Appended to the end of the Makefile for linux (debian) only
sub postamble {
return <<'POSTAMBLE';
DEBVNAME = $(shell $(PERLRUN) -le 'print lc(shift)' $(DISTVNAME))
deb : debdir
-cd $(DEBVNAME) && debuild -us -uc

debdir : distdir
$(RM_RF) $(DEBVNAME)
$(MV) $(DISTVNAME) $(DEBVNAME)
$(CP) -r debian $(DEBVNAME)

POSTAMBLE
}

CGI-Expand-2.04/README000064400000000000000000000161521222430454000141350ustar00rootroot00000000000000NAME
CGI::Expand - convert flat hash to nested data using TT2's dot
convention

SYNOPSIS
use CGI::Expand;
use CGI; # or Apache::Request, etc.

$args = expand_cgi( CGI->new('a.0=3&a.2=4&b.c.0=x') );
# $args = { a => [3,undef,4], b => { c => ['x'] }, }

# Or to catch exceptions:
eval {
$args = expand_cgi( CGI->new('a.0=3&a.2=4&b.c.0=x') );
} or log_and_exit( $@ );

#-----
use CGI::Expand qw(expand_hash);

$args = expand_hash({'a.0'=>77}); # $args = { a => [ 77 ] }

DESCRIPTION
Converts a CGI query into structured data using a dotted name convention
similar to TT2.

"expand_cgi" works with CGI.pm, Apache::Request or anything with an
appropriate "param" method. Or you can use "expand_hash" directly.

If you prefer to use a different flattening convention then CGI::Expand
can be subclassed.

Motivation
The Common Gateway Interface restricts parameters to name=value pairs,
but often we'd like to use more structured data. This module uses a name
encoding convention to rebuild a hash of hashes, arrays and values.
Arrays can either be indexed explicitly or from CGI's multi-valued
parameter handling.

The generic nature of this process means that the core components of
your system can remain CGI ignorant and operate on structured data.
Better for modularity, better for testing.

DOT CONVENTION
The key-value pair "a.b.1=hi" expands to the perl structure:

{ a => { b => [ undef, "hi" ] }

The key ("a.b.1") specifies the location at which the value ("hi") is
stored. The key is split on '.' characters, the first segment ("a") is a
key in the top level hash, subsequent segments may be keys in sub-hashes
or indices in sub-arrays. Integer segments are treated as array indices,
others as hash keys.

Array size is limited to 100 by default. The limit can be altered by
subclassing or using the deprecated $Max_Array package variable. See
below.

The backslash '\' escapes the next character in cgi parameter names
allowing '.' , '\' and digits in hash keys. The escaping '\' is removed.
Values are not altered.

Key-Value Examples
# HoHoL
a.b.1=hi ---> { a => { b => [ undef, "hi" ] }

# HoLoH
a.1.b=hi ---> { a => [ undef, { b => "hi" } ] }

# top level always a hash
9.0=hi ---> { "9" => [ "hi" ] }

# can backslash escape to treat digits hash as keys
a.\0=hi ---> { "a" => { 0 => "hi"} }

# or to put . and \ literals in keys
a\\b\.c=hi --- { 'a\\b\.c' => "hi" }

EXPORTS
"expand_cgi" by default, "expand_hash" and "collapse_hash" upon request.

FUNCTIONS
" $deep_hash = expand_cgi ( $CGI_object_or_similar ) "
Takes a CGI object and returns a hashref for the expanded data
structure (or dies, see "EXCEPTIONS").

Wrapper around expand_hash that uses the "param" method of the CGI
object to collect the names and values.

Handles multivalued parameters as array refs (although they can't be
mixed with indexed arrays and will have an undefined ordering).

$query = 'a.0=3&a.2=4&b.c.0=x&c.0=2&c.1=3&d=&e=1&e=2';

$args = expand_cgi( CGI->new($query) );

# result:
# $args = {
# a => [3,undef,4],
# b => { c => ['x'] },
# c => ['2','3'],
# d => '',
# e => ['1','2'], # order depends on CGI/etc
# };

" $deep_hash = expand_hash ( $flat_hash ) "
Expands the keys of the parameter hash according to the dot
convention (or dies, see "EXCEPTIONS").

$args = expand_hash({ 'a.b.1' => [1,2] });
# $args = { a => { b => [undef, [1,2] ] } }

" $flat_hash = collapse_hash ( $deep_hash ) "
The inverse of expand_hash. Converts the $deep_hash data structure
back into a flat hash.

$flat = collapse_hash({ a => { b => [undef, [1,2] ] } });
# $flat = { 'a.b.1.0' => 1, 'a.b.1.1' => 2 }

EXCEPTIONS
WARNING the USERs of your site can cause these exceptions so you must
decide how they are handled (possibly by letting the process die).

"CGI param array limit exceeded..."
If an array index exceeds the array limit (default: 100) then an
exception is thrown.

"CGI param clash for..."
A cgi query like "a=1&a.b=1" would require the value of $args->{a}
to be both 1 and { b => 1 }. Such type inconsistencies are reported
as exceptions. (See test.pl for for examples)

SUBCLASSING
Subclassing in now the preferred way to change the behaviour and
defaults. (Previously package variables were used, see test.pl).

The methods which may be overriden by subclasses are separator,
max_array, split_name and join_name.

$subclass->max_array()
The limit for the array size, defaults to 100. The value 0 can be
used to disable the use of arrays, everthing is a hash key.

$subclass->separator()
Returns the separator charaters used to split the keys of the flat
hash. The default is '.' but multiple characters are allowed. The
default join will use the first character.

If there is no separator then '\' escaping does not occur. This is
for use with split_name and join_name below.

@segments = $subclass->split_name($name)
The split_name method must break $name in to key segments for the
nested data structure. The default version just splits on the
separator characters with a bit of fiddling to handle escaping.

$name = $subclass->join_name(@segments)
The inverse of split_name, joins the segments back to the key for
the flat hash. The default version uses the first character of the
string returned by the separator method.

DEPRECATIONS
$CGI::Expand::Separator and $CGI::Expand::Max_Array are deprecated. They
still work for now but emit a warning (supressed with
$CGI::Expand::BackCompat = 1)

Using the functions by their fully qualified names ceased to work at
around version 1.04. They're now class methods so just replace the last
:: with ->.

LIMITATIONS
The top level is always a hash. Consequently, any digit only names will
be keys in this hash rather than array indices.

Image inputs with name.x, name.y coordinates are ignored as they will
class with the value for name.

TODO
Thing about ways to keep $cgi and the expanded version in sync

Glob style parameters (with SCALAR, ARRAY and HASH slots) would resolve
the type clashes, probably no fun to use. Look at using
Template::Plugin::StringTree to avoid path clashes

SEE ALSO
* HTTP::Rollup - Replaces CGI.pm completely, no list ordering.

* CGI::State - Tied to CGI.pm, unclear error checking

* Template::Plugin::StringTree

* Hash::Flatten - Pick your delimiters

* http://template-toolkit.org/pipermail/templates/2002-January/002368.
html

* There's a tiny and beautiful reduce solution somewhere on perlmonks.

AUTHOR
Brad Bowman <cgi-expand@bereft.net>

CGI-Expand-2.04/test.pl000064400000000000000000000163251222430454000145730ustar00rootroot00000000000000#!/usr/bin/perl -w

use strict;
use Test::More tests => 59;
use Test::Exception;

BEGIN { use_ok( 'CGI::Expand' ); }

my $query = 'a.0=3&a.2=4&b.c.0=x&c.0=2&c.1=3&d=';
my $flat = {
'a.0' => 3, 'a.2' => 4, 'b.c.0' => "x", 'c.0' => 2, 'c.1' => 3, d => '',
};
my $deep = {
a => [3,undef,4],
b => { c => ['x'] },
c => ['2','3'],
d => '',
};
my $pipe_flat = {
'a|0' => 3, 'a|2' => 4, 'b|c|0' => "x", 'c|0' => 2, 'c|1' => 3, d => '',
};
my $deep_hash_only = {
a => { 0 => 3, 2 => 4 },
b => { c => { 0 => 'x' } },
c => { 0 => '2', 1 => '3'},
d => '',
};

#use Data::Dumper;
#diag Dumper(CGI::Expand->collapse_hash($deep));
#diag Dumper($flat);

sub Fake::param {
shift;
return keys %$flat unless @_;
return $flat->{$_[0]};
}

# only uses param interface
is_deeply( expand_cgi(bless []=>'Fake'), $deep, 'param interface');

CGI::Expand->import('expand_hash','collapse_hash');
is_deeply( expand_hash($flat), $deep, 'expand_hash');
is_deeply( collapse_hash($deep), $flat, 'collapse_hash');

isa_ok(expand_hash({1,2}), 'HASH');
is_deeply(expand_hash({'1.0',2}), {1=>[2]}, 'top level always hash (digits)');
is_deeply(expand_hash(), {}, 'top level always hash (empty)');

my @array_99;
$array_99[99] = 1;

is_deeply(expand_hash({'a.99',1}), {a=>\@array_99}, ' < 100 array' );
throws_ok { expand_hash({'a.100',1}) } qr/^CGI param array limit exceeded/;
is_deeply(expand_hash({'a.\\100',1}), {a=>{100=>1}}, ' \100 hash' );

{
# Limit adjustable
local $CGI::Expand::Max_Array = 200;
local $CGI::Expand::BackCompat = 1;
my @array_199;
$array_199[199] = 1;

is_deeply(expand_hash({'a.199',1}), {a=>\@array_199}, ' < 200 array' );
throws_ok { expand_hash({'a.200',1}) } qr/^CGI param array limit exceeded/;
is_deeply(expand_hash({'a.\200',1}), {a=>{200=>1}}, ' \200 hash' );
}

throws_ok { expand_hash($_) } qr/^CGI param clash/
for ( {'a.1',1,'a.b',1},
{'a.1',1,'a',1},
{'a.b',1,'a',1},
);

# escaping and weird cases
my $ds = "\\\\";
is_deeply(expand_hash({'a.\0'=>1}), {a=>{0=>1}}, '\digit' );
is_deeply(expand_hash({'a.\0\\'=>1}), {a=>{'0\\'=>1}}, '\ at end' );
is_deeply(expand_hash({'a\.0'=>1}), {'a.0'=>1}, '\dot' );
is_deeply(expand_hash({'\a.0'=>1}), {'a'=>[1]}, '\ first alpha' );
is_deeply(expand_hash({'a\a.0'=>1}), {'aa'=>[1]}, '\ other alpha' );
is_deeply(expand_hash({"$ds.0"=>1}), {'\\'=>[1]}, '\ only first' );
is_deeply(expand_hash({"a.$ds.0"=>1}), {a=>{'\\'=>[1]}}, '\ only other' );
is_deeply(expand_hash({"${ds}a"=>1}), {'\\a'=>1}, 'double \ to one' );
is_deeply(expand_hash({"a$ds.0"=>1}), {'a\\'=>[1]}, 'double \ dot to one' );
is_deeply(expand_hash({'.a.'=>1}), {''=>{a=>{''=>1}}}, 'dot start end' );
is_deeply(expand_hash({'a..0'=>1}), {a=>{''=>[1]}}, 'dot dot middle' );
is_deeply(expand_hash({'a..'=>1}), {a=>{''=>{''=>1}}}, 'dot dot end' );
is_deeply(expand_hash({'.'=>1}), {''=>{''=>1}}, 'dot only' );
is_deeply(expand_hash({''=>1}), {''=>1}, 'empty key' );


SKIP: {
skip "No CGI module", 10 unless eval 'use CGI; 1';

is_deeply( expand_cgi(CGI->new($query)), $deep, 'expand_cgi');
is_deeply( expand_cgi(CGI->new("$query&c.x=20&c.y=30")), $deep,
'expand_cgi ignores .x .y');

ok(eq_set( ( expand_cgi(CGI->new('a=1&a=2')) )->{a}, [2, 1]),
'cgi multivals');

throws_ok { expand_cgi(CGI->new($_)) } qr/^CGI param clash/
for (
'a.0=3&a.c=4',
'a.c=3&a.0=4',
'a.0=3&a=b',
'a.a=3&a=b',
'a=3&a.0=b',
'a=3&a.a=b',
'a=3&a=4&a.b=1',
);
}

{
# Disable Array, treat everything as a hash
local $CGI::Expand::Max_Array = 0;
local $CGI::Expand::BackCompat = 1;
# $flat from above

is_deeply( expand_hash($flat), $deep_hash_only, 'expand hash only');
is_deeply( collapse_hash($deep_hash_only), $flat, 'collapse hash only');
is_deeply( expand_hash(collapse_hash($deep_hash_only)), $deep_hash_only,
'round trip hash only');
}
{
local $CGI::Expand::Separator = '|'; # Another regex metacharacter
local $CGI::Expand::BackCompat = 1;

is_deeply( CGI::Expand->expand_hash($pipe_flat), $deep,
'expand sep | with class method');
is_deeply( CGI::Expand->collapse_hash($deep), $pipe_flat,
'collapse sep | with class method');
}

{
package Subclass::Empty;
our @ISA = qw(CGI::Expand);

package Subclass::Empty::main;
use Test::More;

Subclass::Empty->import();
is_deeply( expand_cgi(bless []=>'Fake'), $deep, 'subclass param interface');

Subclass::Empty->import('expand_hash', 'collapse_hash');
is_deeply( expand_hash($flat), $deep, 'subclass expand_hash');
is_deeply( collapse_hash($deep), $flat, 'subclass collapse_hash');
}

{
package Subclass::Pipe;
our @ISA = qw(CGI::Expand);
sub separator { '.|' }

package Subclass::Pipe::main;
use Test::More;

Subclass::Pipe->import();
is_deeply( expand_cgi(bless []=>'Fake'), $deep, 'subclass param interface');

Subclass::Pipe->import('expand_hash', 'collapse_hash');
is_deeply( expand_hash($flat), $deep, 'pipe subclass expand_hash');
is_deeply( expand_hash($pipe_flat), $deep,'pipe subclass hash pipe :)');
is_deeply( collapse_hash($deep), $flat, 'pipe subclass collapse_hash');
}

{
package Subclass::NoArray;
our @ISA = qw(CGI::Expand);
sub max_array { 0 }

package Subclass::NoArray::main;
use Test::More;

Subclass::NoArray->import();
is_deeply( expand_cgi(bless []=>'Fake'), $deep_hash_only,
'subclass param hash only');

Subclass::NoArray->import('expand_hash', 'collapse_hash');
is_deeply( expand_hash($flat), $deep_hash_only,'subclass expand hash only');
is_deeply( collapse_hash($deep_hash_only), $flat,
'subclass collapse hash only');
is_deeply( expand_hash(collapse_hash($deep_hash_only)), $deep_hash_only,
'subclass round trip hash only');
}

{
package Subclass::Rails;
our @ISA = qw(CGI::Expand);
sub max_array { 0 }
sub separator { '.[]' }
sub split_name {
my $class = shift;
my $name = shift;
$name =~ /^ ([^\[\]\.]+) /xg;
my @segs = $1;
push @segs, ($name =~ / \G (?: \[ ([^\[\]\.]+) \] ) /xg);
return @segs;
}
sub join_name {
my $class = shift;
my ($first, @segs) = @_;
return $first unless @segs;
return "$first\[".join('][',@segs)."]";
}

package Subclass::Rails::main;
use Test::More;

Subclass::Rails->import('expand_hash', 'collapse_hash');

my $rails_flat = { 'a' => 1, 'b[c]' => 2, 'b[d][e]' => undef, 'b[2]' => 3 };
my $rails_deep = {
a => '1', b => { c => 2, d => { e => undef }, '2' => 3 }
};
is_deeply( expand_hash($rails_flat), $rails_deep,
'[] convention expands');
is_deeply( collapse_hash($rails_deep), $rails_flat,
'[] convention collapses');
is_deeply( expand_hash(collapse_hash($rails_deep)), $rails_deep,
'[] convention round trips');
}

#my $mix_flat = { 'a' => 1, 'b[c]' => 2, 'b.d.e' => undef };
#my $mix_deep = {
# a => '1', b => { c => 2, d => { e => undef } }
# };
#is_deeply( expand_hash($mix_flat), $mix_deep, '[] convention expands');
#is_deeply( collapse_hash($mix_deep), $mix_flat, '[] convention collapses');
 
design & coding: Vladimir Lettiev aka crux © 2004-2005, Andrew Avramenko aka liks © 2007-2008
current maintainer: Michael Shigorin