blib/lib/URI/Query.pm

filter: Statementstmt 97.1% 136 / 140 Branchbran 75.0% 42 / 56 Conditioncond 88.8% 24 / 27 MC/DCmcdc 80.0% 12 / 15 Subroutinesub 100% 24 / 24 Podpod 92.3% 12 / 13 totaltotal 90.9% 250 / 275 SCAR 39.7
CC
51
Cov
91%
strip_like
9.3
_deepcopy
8.7
_init_from_arrayref
7.0
CRAP 53.2
↑ Summary
1 #
2 # Class providing URI query string manipulation
3 #
4  
5 package URI::Query;
6  
7 8 ▶use 5.00503;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 8 ▶use URI::Escape qw(uri_escape_utf8 uri_unescape);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 use overload
14 '""' => \&stringify,
15 2 ▶ 'eq' => sub { $_[0]->stringify eq $_[1]->stringify },
Subroutine __ANON__: called CC=1 SCAR=0.0
16 8 ▶ 'ne' => sub { $_[0]->stringify ne $_[1]->stringify };
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
17  
18 8 ▶use vars q($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
19 8 $VERSION = '0.11';
20  
21 # -------------------------------------------------------------------------
22 # Remove all occurrences of the given parameters
23 sub strip
24 {
25 4 ▶ my $self = shift;
Subroutine strip: called CC=3 SCAR=11.0
Pod documented
26 4 foreach (@_) {
27 7 ▶ delete $self->{qq}->{$_} and $self->{changed}++;
Branch: 1 branch
BranchTrueFalseTotal
delete $self->{"qq"}{$_} and ++$self->{"changed"} 6 1 7
28 }
29 4 $self;
30 }
31  
32 # Remove all parameters except those given
33 sub strip_except
34 {
35 3 ▶ my $self = shift;
Subroutine strip_except: called CC=4 SCAR=13.9
Pod documented
36 3 my %keep = map { $_ => 1 } @_;
37 3 foreach (keys %{$self->{qq}}) {
38 13 ▶ next if $keep{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $keep{$_} 8 5 13
39 5 ▶ delete $self->{qq}->{$_} and $self->{changed}++;
Branch: 1 branch
BranchTrueFalseTotal
delete $self->{"qq"}{$_} and ++$self->{"changed"} 5 0 5
40 }
41 3 $self;
42 }
43  
44 # Remove all empty/undefined parameters
45 sub strip_null
46 {
47 2 ▶ my $self = shift;
Subroutine strip_null: called CC=4 SCAR=13.9
Pod documented
48 2 foreach (keys %{$self->{qq}}) {
49 9 ▶ next if @{$self->{qq}->{$_}};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->{"qq"}{$_};} 6 3 9
50 3 ▶ delete $self->{qq}->{$_} and $self->{changed}++;
Branch: 1 branch
BranchTrueFalseTotal
delete $self->{"qq"}{$_} and ++$self->{"changed"} 3 0 3
51 }
52 2 $self;
53 }
54  
55 # Remove all parameters matching $re
56 sub strip_like
57 {
58 3 ▶ my $self = shift;
Subroutine strip_like: called CC=8 SCAR=22.3
Pod documented
59 3 ▶ my $re = shift or croak "Missing regex param to strip_like";
Branch: 1 branch
BranchTrueFalseTotal
my $re = shift() or croak("Missing regex param to strip_like") 0 3 3
60 3 ▶ croak "Invalid param '$re' to strip_like - must be regex" if ! ref $re || ref $re ne 'Regexp';
Branch: 1 branch
BranchTrueFalseTotal
if not ref $re or ref $re ne "Regexp" 0 3 3
Condition33%1/3
not ref $re or ref $re ne "Regexp"
l!l&&r!l&&!r
003
MC/DC0%0/2
not ref $re or ref $re ne "Regexp"
not ref $re ref $re ne "Regexp"
Truth table33%1/3
not(A) or B
A= not ref $reB= ref $re ne "Regexp"
ABresult
1X1
011
000
61 3 ▶ croak "Too many params to strip_like - only one permitted" if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 3 3
62  
63 3 foreach (keys %{$self->{qq}}) {
64 10 ▶ next if $_ !~ $re;
Branch: 1 branch
BranchTrueFalseTotal
unless $_ =~ /$re/ 7 3 10
65 3 ▶ delete $self->{qq}->{$_} and $self->{changed}++;
Branch: 1 branch
BranchTrueFalseTotal
delete $self->{"qq"}{$_} and ++$self->{"changed"} 3 0 3
66 }
67  
68 3 $self;
69 }
70  
71 # Replace all occurrences of the given parameters
72 sub replace
73 {
74 2 ▶ my $self = shift;
Subroutine replace: called CC=4 SCAR=13.9
Pod documented
75 2 my %arg = @_;
76 2 for my $key (keys %arg) {
77 5 $self->{qq}->{$key} = [];
78 5 ▶ if (ref $arg{$key} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arg{$key} eq 'ARRAY') { } 1 4 5
79 1 push @{$self->{qq}->{$key}}, $_ foreach @{$arg{$key}};
80 }
81 else {
82 4 push @{$self->{qq}->{$key}}, $arg{$key};
83 }
84 5 $self->{changed}++;
85 }
86 2 $self;
87 }
88  
89 # Return the stringified qq hash
90 sub stringify
91 {
92 83 ▶ my $self = shift;
Subroutine stringify: called CC=5 SCAR=16.1
Pod documented
93 83 ▶ my $sep = shift || $self->{sep} || '&';
Condition100%5/5
shift() || $self->{'sep'} || '&'
l!l
281
shift() or $self->{"sep"}
l!l&&r!l&&!r
1181
MC/DC100%2/2
shift() || $self->{'sep'} || '&'
shift() $self->{"sep"}
Truth table100%3/3
A or B
A= shift()B= $self->{"sep"}
ABresult
1X1
011
000
94 83 my @out = ();
95 83 for my $key (sort keys %{$self->{qq}}) {
96 233 for my $value (@{$self->{qq}->{$key}}) {
97 337 push @out, sprintf("%s=%s", uri_escape_utf8($key), uri_escape_utf8($value));
98 }
99 }
100 83 join $sep, @out;
101 }
102  
103 sub revert
104 {
105 4 ▶ my $self = shift;
Subroutine revert: called CC=1 SCAR=0.0
Pod documented
106 # Revert qq to the qq_orig hashref
107 4 $self->{qq} = $self->_deepcopy($self->{qq_orig});
108 4 $self->{changed} = 0;
109 4 $self;
110 }
111  
112 sub has_changed {
113 9 ▶ my $self = shift;
Subroutine has_changed: called CC=2 SCAR=6.9
Pod documented
114 9 ▶ $self->{changed} > 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'changed'} > 0 ? : 3 6 9
115 }
116  
117 # -------------------------------------------------------------------------
118 # Convenience methods
119  
120 # Return the current qq hash(ref) with one-elt arrays flattened
121 sub hash
122 {
123 4 ▶ my $self = shift;
Subroutine hash: called CC=4 SCAR=13.9
Pod documented
124 4 my %qq = %{$self->{qq}};
125 # Flatten one element arrays
126 4 for (sort keys %qq) {
127 10 ▶ $qq{$_} = $qq{$_}->[0] if @{$qq{$_}} == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @{$qq{$_};} == 1 8 2 10
128 }
129 4 ▶ return wantarray ? %qq : \%qq;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 4 4
130 }
131  
132 # Return the current qq hash(ref) with all elements as arrayrefs
133 sub hash_arrayref
134 {
135 1 ▶ my $self = shift;
Subroutine hash_arrayref: called CC=2 SCAR=7.0
Pod documented
136 1 my %qq = %{$self->{qq}};
137 # (Don't flatten one element arrays)
138 1 ▶ return wantarray ? %qq : \%qq;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 1 1
139 }
140  
141 # Return the current query as a string of html hidden input tags
142 sub hidden
143 {
144 1 ▶ my $self = shift;
Subroutine hidden: called CC=3 SCAR=11.0
Pod documented
145 1 my $str = '';
146 1 for my $key (sort keys %{$self->{qq}}) {
147 4 for my $value (@{$self->{qq}->{$key}}) {
148 6 $str .= qq(<input type="hidden" name="$key" value="$value" />\n);
149 }
150 }
151 1 return $str;
152 }
153  
154 # -------------------------------------------------------------------------
155 # Set the output separator to use by default
156 sub separator
157 {
158 1 ▶ my $self = shift;
Subroutine separator: called CC=1 SCAR=0.0
Pod documented
159 1 $self->{sep} = shift;
160 }
161  
162 # Deep copy routine, originally swiped from a Randal Schwartz column
163 sub _deepcopy
164 {
165 220 ▶ my ($self, $this) = @_;
Subroutine _deepcopy: called CC=6 SCAR=21.6
166 220 ▶ if (! ref $this) {
Branch: 5 branches
BranchTrueFalseTotal
if (not ref $this) { } 110 110 220
elsif (ref $this eq 'ARRAY') { } 81 29 110
elsif (ref $this eq 'HASH') { } 29 0 29
elsif (ref $this eq 'CODE') { } 0 0 0
elsif (sprintf $this) { } 0 0 0
167 110 return $this;
168 } elsif (ref $this eq "ARRAY") {
169 81 return [map $self->_deepcopy($_), @$this];
170 } elsif (ref $this eq "HASH") {
171 29 return {map { $_ => $self->_deepcopy($this->{$_}) } keys %$this};
172 } elsif (ref $this eq "CODE") {
173 0 return $this;
174 } elsif (sprintf $this) {
175 # Object! As a last resort, try copying the stringification value
176 0 return sprintf $this;
177 } else {
178 0 die "what type is $_? (" . ref($this) . ")";
179 }
180 }
181  
182 # Parse query string, storing as hash (qq) of key => arrayref pairs
183 sub _parse_qs
184 {
185 14 ▶ my $self = shift;
Subroutine _parse_qs: called CC=5 SCAR=16.1
186 14 my $qs = shift;
187 14 for (split /[&;]/, $qs) {
188 64 my ($key, $value) = map { uri_unescape($_) } split /=/, $_, 2;
189 64 ▶ $self->{qq}->{$key} ||= [];
Condition100%2/2
$self->{"qq"}{$key} ||= []
l!l
2044
MC/DC100%1/1
$self->{"qq"}{$key} ||= []
$self->{"qq"}{$key}
Truth table100%2/2
A
A= $self->{"qq"}{$key}
Aresult
11
00
190 64 ▶ push @{$self->{qq}->{$key}}, $value if defined $value && $value ne '';
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and $value ne "" 63 1 64
Condition66%2/3
defined $value and $value ne ""
!ll&&!rl&&r
0163
MC/DC50%1/2
defined $value and $value ne ""
defined $value $value ne ""
Truth table66%2/3
A and B
A= defined $valueB= $value ne ""
ABresult
0X0
100
111
191 }
192 $self
193 14 }
194  
195 # Process arrayref arguments into hash (qq) of key => arrayref pairs
196 sub _init_from_arrayref
197 {
198 6 ▶ my ($self, $arrayref) = @_;
Subroutine _init_from_arrayref: called CC=7 SCAR=19.5
199 6 ▶ while (@$arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$arrayref) 24 6 30
200 24 my $key = shift @$arrayref;
201 24 my $value = shift @$arrayref;
202 24 my $key_unesc = uri_unescape($key);
203  
204 24 ▶ $self->{qq}->{$key_unesc} ||= [];
Condition100%2/2
$self->{"qq"}{$key_unesc} ||= []
l!l
321
MC/DC100%1/1
$self->{"qq"}{$key_unesc} ||= []
$self->{"qq"}{$key_unesc}
Truth table100%2/2
A
A= $self->{"qq"}{$key_unesc}
Aresult
11
00
205 24 ▶ if (defined $value && $value ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value and $value ne "") 22 2 24
Condition100%3/3
defined $value and $value ne ""
!ll&&!rl&&r
1122
MC/DC100%2/2
defined $value and $value ne ""
defined $value $value ne ""
Truth table100%3/3
A and B
A= defined $valueB= $value ne ""
ABresult
0X0
100
111
206 22 my @values;
207 22 ▶ if (! ref $value) {
Branch: 2 branches
BranchTrueFalseTotal
if (not ref $value) { } 20 2 22
elsif (ref $value eq 'ARRAY') { } 2 0 2
208 20 @values = split "\0", $value;
209 }
210 elsif (ref $value eq 'ARRAY') {
211 2 @values = @$value;
212 }
213 else {
214 0 die "Invalid value found: $value. Not string or arrayref!";
215 }
216 22 push @{$self->{qq}->{$key_unesc}}, map { uri_unescape($_) } @values;
217 }
218 }
219 }
220  
221 # Constructor - either new($qs) where $qs is a scalar query string or a
222 # a hashref of key => value pairs, or new(key => val, key => val);
223 # In the array form, keys can repeat, and/or values can be arrayrefs.
224 sub new
225 {
226 25 ▶ my $class = shift;
Subroutine new: called CC=7 SCAR=19.5
Pod undocumented
227 25 my $self = bless { qq => {} }, $class;
228 25 ▶ if (@_ == 1 && ! ref $_[0] && $_[0]) {
Branch: 3 branches
BranchTrueFalseTotal
if (@_ == 1 and not ref $_[0] and $_[0]) { } 14 11 25
elsif (@_ == 1 and ref $_[0] eq 'HASH') { } 3 8 11
elsif (scalar(@_) % 2 == 0) { } 3 5 8
Condition100%6/6
@_ == 1 and not ref $_[0] and $_[0]
!ll&&!rl&&r
9214
@_ == 1 and not ref $_[0]
!ll&&!rl&&r
3616
MC/DC100%3/3
@_ == 1 and not ref $_[0] and $_[0]
@_ == 1 not ref $_[0] $_[0]
Truth table100%4/4
A and not(B) and C
A= @_ == 1B= not ref $_[0]C= $_[0]
ABCresult
0XX0
10X0
1100
1111
229 14 $self->_parse_qs($_[0]);
230 }
231 ▶ elsif (@_ == 1 && ref $_[0] eq 'HASH') {
Condition100%3/3
@_ == 1 and ref $_[0] eq "HASH"
!ll&&!rl&&r
353
MC/DC100%2/2
@_ == 1 and ref $_[0] eq "HASH"
@_ == 1 ref $_[0] eq "HASH"
Truth table100%3/3
A and B
A= @_ == 1B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
232 3 $self->_init_from_arrayref([ %{$_[0]} ]);
233 }
234 elsif (scalar(@_) % 2 == 0) {
235 3 $self->_init_from_arrayref(\@_);
236 }
237  
238 # Clone the qq hashref to allow reversion
239 25 $self->{qq_orig} = $self->_deepcopy($self->{qq});
240  
241 # Changed flag
242 25 $self->{changed} = 0;
243  
244 25 return $self;
245 }
246 # -------------------------------------------------------------------------
247  
248 8 1;
249  
250 =head1 NAME
251  
252 URI::Query - class providing URI query string manipulation
253  
254 =head1 SYNOPSIS
255  
256 # Constructor - using a GET query string
257 $qq = URI::Query->new($query_string);
258 # OR Constructor - using a hashref of key => value parameters
259 $qq = URI::Query->new($cgi->Vars);
260 # OR Constructor - using an array of successive keys and values
261 $qq = URI::Query->new(@params);
262  
263 # Revert back to the initial constructor state (to do it all again)
264 $qq->revert;
265  
266 # Remove all occurrences of the given parameters
267 $qq->strip('page', 'next');
268  
269 # Remove all parameters except the given ones
270 $qq->strip_except('pagesize', 'order');
271  
272 # Remove all empty/undefined parameters
273 $qq->strip_null;
274  
275 # Replace all occurrences of the given parameters
276 $qq->replace(page => $page, foo => 'bar');
277  
278 # Set the argument separator to use for output (default: unescaped '&')
279 $qq->separator(';');
280  
281 # Output the current query string
282 print "$qq"; # OR $qq->stringify;
283 # Stringify with explicit argument separator
284 $qq->stringify(';');
285  
286 # Get a flattened hash/hashref of the current parameters
287 # (single item parameters as scalars, multiples as an arrayref)
288 my %qq = $qq->hash;
289  
290 # Get a non-flattened hash/hashref of the current parameters
291 # (parameter => arrayref of values)
292 my %qq = $qq->hash_arrayref;
293  
294 # Get the current query string as a set of hidden input tags
295 print $qq->hidden;
296  
297 # Check whether the query has changed since construction
298 if ($qq->has_changed) {
299 print "changed version: $qq\n";
300 }
301  
302  
303 =head1 DESCRIPTION
304  
305 URI::Query provides simple URI query string manipulation, allowing you
306 to create and manipulate URI query strings from GET and POST requests in
307 web applications. This is primarily useful for creating links where you
308 wish to preserve some subset of the parameters to the current request,
309 and potentially add or replace others. Given a query string this is
310 doable with regexes, of course, but making sure you get the anchoring
311 and escaping right is tedious and error-prone - this module is simpler.
312  
313 =head2 CONSTRUCTOR
314  
315 URI::Query objects can be constructed from scalar query strings
316 ('foo=1&bar=2&bar=3'), from a hashref which has parameters as keys, and
317 values either as scalars or arrayrefs of scalars (to handle the case of
318 parameters with multiple values e.g. { foo => '1', bar => [ '2', '3' ] }),
319 or arrays composed of successive parameters-value pairs
320 e.g. ('foo', '1', 'bar', '2', 'bar', '3'). For instance:
321  
322 # Constructor - using a GET query string
323 $qq = URI::Query->new($query_string);
324  
325 # Constructor - using an array of successive keys and values
326 $qq = URI::Query->new(@params);
327  
328 # Constructor - using a hashref of key => value parameters,
329 # where values are either scalars or arrayrefs of scalars
330 $qq = URI::Query->new($cgi->Vars);
331  
332 URI::Query also handles L<CGI.pm>-style hashrefs, where multiple
333 values are packed into a single string, separated by the "\0" (null)
334 character.
335  
336 All keys and values are URI unescaped at construction time, and are
337 stored and referenced unescaped. So a query string like:
338  
339 group=prod%2Cinfra%2Ctest&op%3Aset=x%3Dy
340  
341 is stored as:
342  
343 'group' => 'prod,infra,test'
344 'op:set' => 'x=y'
345  
346 You should always use the unescaped/normal variants in methods i.e.
347  
348 $qq->replace('op:set' => 'x=z');
349  
350 NOT:
351  
352 $qq->replace('op%3Aset' => 'x%3Dz');
353  
354  
355 =head2 MODIFIER METHODS
356  
357 All modifier methods change the state of the URI::Query object in some
358 way, and return $self, so they can be used in chained style e.g.
359  
360 $qq->revert->strip('foo')->replace(bar => 123);
361  
362 Note that URI::Query stashes a copy of the parameter set that existed
363 at construction time, so that any changes made by these methods can be
364 rolled back using 'revert()'. So you don't (usually) need to keep
365 multiple copies around to handle incompatible changes.
366  
367 =over 4
368  
369 =item revert()
370  
371 Revert the current parameter set back to that originally given at
372 construction time i.e. discard all changes made since construction.
373  
374 =item strip($param1, $param2, ...)
375  
376 Remove all occurrences of the given parameters and their values from
377 the current parameter set.
378  
379 =item strip_except($param1, $param2, ...)
380  
381 Remove all parameters EXCEPT those given from the current parameter
382 set.
383  
384 =item strip_null()
385  
386 Remove all parameters that have a value of undef from the current
387 parameter set.
388  
389 =item replace($param1 => $value1, $param2, $value2, ...)
390  
391 Replace the values of the given parameters in the current parameter set
392 with these new ones. Parameter names must be scalars, but values can be
393 either scalars or arrayrefs of scalars, when multiple values are desired.
394  
395 Note that 'replace' can also be used to add or append, since there's
396 no requirement that the parameters already exist in the current parameter
397 set.
398  
399 =item strip_like($regex)
400  
401 Remove all parameters whose names match the given (qr-quoted) regex e.g.
402  
403 $qq->strip_like(qr/^utm/)
404  
405 Does NOT match against parameter values.
406  
407 =item separator($separator)
408  
409 Set the argument separator to use for output. Default: '&'.
410  
411 =back
412  
413 =head2 ACCESSOR METHODS
414  
415 =over 4
416  
417 =item has_changed()
418  
419 If the query is actually changed by any of the modifier methods (strip,
420 strip_except, strip_null, strip_like, or replace) it sets an internal
421 changed flag which can be access by:
422  
423 $qq->has_changed
424  
425 revert() resets the has_changed flag to false.
426  
427 =back
428  
429 =head2 OUTPUT METHODS
430  
431 =over 4
432  
433 =item "$qq", stringify(), stringify($separator)
434  
435 Return the current parameter set as a conventional param=value query
436 string, using $separator as the separator if given. e.g.
437  
438 foo=1&bar=2&bar=3
439  
440 Note that all parameters and values are URI escaped by stringify(), so
441 that query-string reserved characters do not occur within elements. For
442 instance, a parameter set of:
443  
444 'group' => 'prod,infra,test'
445 'op:set' => 'x=y'
446  
447 will be stringified as:
448  
449 group=prod%2Cinfra%2Ctest&op%3Aset=x%3Dy
450  
451 =item hash()
452  
453 Return a hash (in list context) or hashref (in scalar context) of the
454 current parameter set. Single-item parameters have scalar values, while
455 while multiple-item parameters have arrayref values e.g.
456  
457 {
458 foo => 1,
459 bar => [ 2, 3 ],
460 }
461  
462 =item hash_arrayref()
463  
464 Return a hash (in list context) or hashref (in scalar context) of the
465 current parameter set. All values are returned as arrayrefs, including
466 those with single values e.g.
467  
468 {
469 foo => [ 1 ],
470 bar => [ 2, 3 ],
471 }
472  
473 =item hidden()
474  
475 Returns the current parameter set as a concatenated string of hidden
476 input tags, one per parameter-value e.g.
477  
478 <input type="hidden" name="foo" value="1" />
479 <input type="hidden" name="bar" value="2" />
480 <input type="hidden" name="bar" value="3" />
481  
482 =back
483  
484 =head1 BUGS AND CAVEATS
485  
486 Please report bugs and/or feature requests to
487 C<bug-uri-query at rt.cpan.org>, or through
488 the web interface at
489 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=URI-Query>.
490  
491 Should allow unescaping of input to be turned off, for situations in
492 which it's already been done. Please let me know if you find you
493 actually need this.
494  
495 I don't think it makes sense on the output side though, since you need
496 to understand the structure of the query to escape elements correctly.
497  
498  
499 =head1 PATCHES
500  
501 URI::Query code lives at L<https://github.com/gavincarr/URI-Query>.
502 Patches / pull requests welcome!
503  
504  
505 =head1 AUTHOR
506  
507 Gavin Carr <gavin@openfusion.com.au>
508  
509  
510 =head1 COPYRIGHT
511  
512 Copyright 2004-2015, Gavin Carr.
513  
514 This program is free software. You may copy or redistribute it under the
515 same terms as perl itself.
516  
517 =cut
518  
519 =for Pod::Coverage new
520  
521 # vim:sw=4:et
↑ Summary