blib/lib/URI/Fast.pm

filter: Statementstmt 97.0% 166 / 171 Branchbran 86.0% 86 / 100 Conditioncond 69.7% 23 / 33 MC/DCmcdc 37.5% 6 / 16 Subroutinesub 92.5% 25 / 27 Podpod 100% 13 / 13 totaltotal 88.6% 319 / 360 CC 73 SCAR 21.4
CC
73
Cov
90%
compare
15.3
_walk
14.4
relative
10.0
CRAP 8.5
↑ Summary blib/lib/URI/Fast/IRI.pm »
1 package URI::Fast;
2  
3 19 our $XS_VERSION = our $VERSION = '0.55';
4 19 $VERSION =~ tr/_//;
5  
6 19 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 19 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 19 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 19 ▶no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 19 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 19 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 19 ▶use Scalar::Util qw(refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 19 require XSLoader;
16 19 XSLoader::load('URI::Fast', $XS_VERSION);
17  
18 19 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 19 our @EXPORT_OK = qw(
21 uri_split
22 uri
23 iri
24 abs_uri
25 html_url
26 encode uri_encode url_encode
27 decode uri_decode url_decode
28 );
29  
30 19 require URI::Fast::IRI;
31  
32 0 ▶use overload 'eq' => sub{ $_[0]->compare($_[1]) };
Subroutine BEGIN: called CC=1 SCAR=0.2
Subroutine __ANON__: not called CC=1 SCAR=0.2
33  
34 29 ▶sub auth {
Subroutine auth: called CC=8 SCAR=21.2
Pod documented
35 29 my ($self, $val) = @_;
36  
37 29 ▶ if (@_ == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2) 12 17 29
38 12 ▶ if (ref $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val) { } 1 11 12
39 1 ▶ $self->usr($val->{usr} || '');
Condition50%1/2
$val->{'usr'} || ''
l!l
10
MC/DC0%0/1
$val->{'usr'} || ''
$val->{'usr'}
Truth table50%1/2
A
A= $val->{'usr'}
Aresult
11
00
40 1 ▶ $self->pwd($val->{pwd} || '');
Condition50%1/2
$val->{'pwd'} || ''
l!l
10
MC/DC0%0/1
$val->{'pwd'} || ''
$val->{'pwd'}
Truth table50%1/2
A
A= $val->{'pwd'}
Aresult
11
00
41 1 ▶ $self->host($val->{host} || '');
Condition50%1/2
$val->{'host'} || ''
l!l
10
MC/DC0%0/1
$val->{'host'} || ''
$val->{'host'}
Truth table50%1/2
A
A= $val->{'host'}
Aresult
11
00
42 1 ▶ $self->port($val->{port} || '');
Condition50%1/2
$val->{'port'} || ''
l!l
10
MC/DC0%0/1
$val->{'port'} || ''
$val->{'port'}
Truth table50%1/2
A
A= $val->{'port'}
Aresult
11
00
43 }
44 else {
45 11 $self->set_auth($val);
46 }
47 }
48  
49 29 ▶ return $self->get_auth
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 20 9 29
50 if defined wantarray;
51 }
52  
53 # Path is slightly more complicated as it can parse the path
54 150 ▶sub path {
Subroutine path: called CC=5 SCAR=16.1
Pod documented
55 150 my ($self, $val) = @_;
56  
57 150 ▶ if (@_ == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2) 33 117 150
58 33 ▶ if (ref $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val) { } 11 22 33
59 11 $self->set_path_array($val);
60 } else {
61 22 $self->set_path($val);
62 }
63 }
64  
65 150 ▶ if (wantarray) {
Branch: 2 branches
BranchTrueFalseTotal
if (wantarray) { } 98 52 150
elsif (defined wantarray) { } 22 30 52
66 98 @{ $self->split_path };
67 } elsif (defined wantarray) {
68 22 $self->get_path;
69 }
70 }
71  
72 # Queries may be set with either a string or a hash ref
73 66 ▶sub query {
Subroutine query: called CC=6 SCAR=17.9
Pod documented
74 66 my ($self, $val, $sep) = @_;
75  
76 66 ▶ if (@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 12 54 66
77 12 ▶ if (ref $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val) { } 4 8 12
78 4 $self->clear_query;
79 $self->param($_, $val->{$_}, $sep)
80 4 foreach keys %$val;
81 }
82 else {
83 8 $self->set_query($val);
84 }
85 }
86  
87 66 ▶ return unless defined(wantarray); # void context
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray 9 57 66
88 57 ▶ return $self->get_query unless wantarray; # scalar context
Branch: 1 branch
BranchTrueFalseTotal
unless wantarray 48 9 57
89 9 return %{ $self->query_hash }; # list context
90 }
91  
92 66 ▶sub query_hash {
Subroutine query_hash: called CC=2 SCAR=7.1
Pod documented
93 66 my $self = shift;
94 66 ▶ $self->query(@_) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 0 66 66
95 66 $self->get_query_hash;
96 }
97  
98 13 ▶sub query_keys {
Subroutine query_keys: called CC=1 SCAR=0.0
Pod documented
99 13 keys %{ $_[0]->get_query_keys };
100 }
101  
102 116 ▶sub param {
Subroutine param: called CC=10 SCAR=23.0
Pod documented
103 116 my ($self, $key, $val, $sep) = @_;
104 116 ▶ $sep ||= '&';
Condition100%2/2
$sep ||= "&"
l!l
2294
MC/DC100%1/1
$sep ||= "&"
$sep
Truth table100%2/2
A
A= $sep
Aresult
11
00
105  
106 116 ▶ if (@_ > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 2) 59 57 116
107 59 ▶ $val = ref $val ? $val
Branch: 2 branches
BranchTrueFalseTotal
ref $val ? : 20 39 59
defined $val ? : 31 8 39
108 : defined $val ? [$val]
109 : [];
110  
111 59 $self->set_param($key, $val, $sep);
112 }
113  
114 # No return value in void context
115 116 ▶ return unless defined(wantarray) && $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined wantarray and $key 46 70 116
Condition66%2/3
defined wantarray and $key
!ll&&!rl&&r
46070
MC/DC50%1/2
defined wantarray and $key
defined wantarray $key
Truth table66%2/3
A and B
A= defined wantarrayB= $key
ABresult
0X0
100
111
116  
117 70 my $params = $self->get_param($key);
118 70 ▶ return unless @$params;
Branch: 1 branch
BranchTrueFalseTotal
unless @$params 12 58 70
119  
120 58 ▶ return wantarray ? @$params
Branch: 2 branches
BranchTrueFalseTotal
wantarray ? : 17 41 58
@$params == 1 ? : 39 2 41
121 : @$params == 1 ? $params->[0]
122 : croak("param: multiple values encountered for query parameter '$key' when called in SCALAR context");
123 }
124  
125 9 ▶sub add_param {
Subroutine add_param: called CC=1 SCAR=0.0
Pod documented
126 9 my ($self, $key, $val, $sep) = @_;
127 9 $self->param($key, [$self->param($key), $val], $sep);
128 }
129  
130 1 ▶sub append {
Subroutine append: called CC=6 SCAR=17.9
Pod documented
131 1 my $self = shift;
132  
133 1 foreach my $segment (@_) {
134 5 ▶ if ($segment =~ /^\?/) {
Branch: 2 branches
BranchTrueFalseTotal
if ($segment =~ /^\?/) { } 1 4 5
elsif (my($frag) = $segment =~ /^#(.*)$/) { } 1 3 4
135 1 my $q = uri($segment)->query_hash;
136  
137 1 foreach my $key (keys %$q) {
138 $self->add_param($key => $_)
139 1 foreach @{ $q->{$key} };
140 }
141 }
142 elsif (my ($frag) = $segment =~ /^#(.*)$/) {
143 1 $self->frag($frag);
144 }
145 else {
146 3 my @segments = ($self->path, split('/', $segment));
147 3 $self->path(\@segments);
148 }
149 }
150  
151 1 return $self;
152 }
153  
154 273 ▶sub _cmp ($$) {
Subroutine _cmp: called CC=5 SCAR=18.6
155 273 ▶ if (defined $_[0]) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $_[0]) { } 273 0 273
elsif (defined $_[1]) { } 0 0 0
156 273 ▶ return if !defined $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[1] 0 273 273
157 273 ▶ return if $_[0] ne $_[1];
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] ne $_[1] 26 247 273
158 }
159 elsif (defined $_[1]) {
160 0 return;
161 }
162  
163 247 return 1;
164 }
165  
166 52 ▶sub compare {
Subroutine compare: called CC=15 SCAR=27.3
Pod documented
167 52 my ($self, $other) = @_;
168 52 $other = uri($other);
169  
170 52 ▶ return unless _cmp($self->scheme, $other->scheme)
Branch: 1 branch
BranchTrueFalseTotal
unless &_cmp(scalar $self->scheme, scalar $other->scheme) and &_cmp(scalar $self->usr, scalar $other->usr) and &_cmp(scalar $self->pwd, scalar $other->pwd) and &_cmp(scalar $self->host, scalar $other->host) and &_cmp(scalar $self->port, scalar $other->port) and &_cmp(scalar $self->frag, scalar $other->frag) 18 34 52
Condition73%11/15
&_cmp(scalar $self->scheme, scalar $other->scheme) and &_cmp(scalar $self->usr, scalar $other->usr) and &_cmp(scalar $self->pwd, scalar $other->pwd) and &_cmp(scalar $self->host, scalar $other->host) and &_cmp(scalar $self->port, scalar $other->port) and &_cmp(scalar $self->frag, scalar $other->frag)
!ll&&!rl&&r
13534
&_cmp(scalar $self->scheme, scalar $other->scheme) and &_cmp(scalar $self->usr, scalar $other->usr) and &_cmp(scalar $self->pwd, scalar $other->pwd) and &_cmp(scalar $self->host, scalar $other->host) and &_cmp(scalar $self->port, scalar $other->port)
!ll&&!rl&&r
13039
&_cmp(scalar $self->scheme, scalar $other->scheme) and &_cmp(scalar $self->usr, scalar $other->usr) and &_cmp(scalar $self->pwd, scalar $other->pwd) and &_cmp(scalar $self->host, scalar $other->host)
!ll&&!rl&&r
13039
&_cmp(scalar $self->scheme, scalar $other->scheme) and &_cmp(scalar $self->usr, scalar $other->usr) and &_cmp(scalar $self->pwd, scalar $other->pwd)
!ll&&!rl&&r
13039
&_cmp(scalar $self->scheme, scalar $other->scheme) and &_cmp(scalar $self->usr, scalar $other->usr)
!ll&&!rl&&r
13039
MC/DC33%2/6
&_cmp(scalar $self->scheme, scalar $other->scheme) and &_cmp(scalar $self->usr, scalar $other->usr) and &_cmp(scalar $self->pwd, scalar $other->pwd) and &_cmp(scalar $self->host, scalar $other->host) and &_cmp(scalar $self->port, scalar $other->port) and &_cmp(scalar $self->frag, scalar $other->frag)
&_cmp(scalar $self->scheme, scalar $other->scheme) &_cmp(scalar $self->usr, scalar $other->usr) &_cmp(scalar $self->pwd, scalar $other->pwd) &_cmp(scalar $self->host, scalar $other->host) &_cmp(scalar $self->port, scalar $other->port) &_cmp(scalar $self->frag, scalar $other->frag)
Truth table42%3/7
A and B and C and D and E and F
A= &_cmp(scalar $self->scheme, scalar $other->scheme)B= &_cmp(scalar $self->usr, scalar $other->usr)C= &_cmp(scalar $self->pwd, scalar $other->pwd)D= &_cmp(scalar $self->host, scalar $other->host)E= &_cmp(scalar $self->port, scalar $other->port)F= &_cmp(scalar $self->frag, scalar $other->frag)
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
171 && _cmp($self->usr, $other->usr)
172 && _cmp($self->pwd, $other->pwd)
173 && _cmp($self->host, $other->host)
174 && _cmp($self->port, $other->port)
175 && _cmp($self->frag, $other->frag);
176  
177 34 my @spath = $self->path;
178 34 my @opath = $other->path;
179 34 ▶ return unless @spath == @opath;
Branch: 1 branch
BranchTrueFalseTotal
unless @spath == @opath 12 22 34
180  
181 22 foreach (0 .. $#spath) {
182 17 ▶ return unless _cmp($spath[$_], $opath[$_]);
Branch: 1 branch
BranchTrueFalseTotal
unless &_cmp($spath[$_], $opath[$_]) 7 10 17
183 }
184  
185 15 my $sparam = $self->query_hash;
186 15 my $oparam = $other->query_hash;
187  
188 15 foreach my $k (keys %$sparam) {
189 12 ▶ return unless exists $oparam->{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $oparam->{$k} 3 9 12
190 9 ▶ return unless @{$sparam->{$k}} == @{$oparam->{$k}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$sparam->{$k};} == @{$oparam->{$k};} 0 9 9
191  
192 9 foreach (0 .. $#{$sparam->{$k}}) {
193 9 ▶ return unless _cmp($sparam->{$k}[$_], $oparam->{$k}[$_]);
Branch: 1 branch
BranchTrueFalseTotal
unless &_cmp($sparam->{$k}[$_], $oparam->{$k}[$_]) 1 8 9
194 }
195 }
196  
197 11 return 1;
198 }
199  
200 #-------------------------------------------------------------------------------
201 # Relativism
202 #-------------------------------------------------------------------------------
203 7 ▶sub relative {
Subroutine relative: called CC=10 SCAR=23.1
Pod documented
204 7 my ($self, $base) = @_;
205 7 my $rel = (ref $self)->new("$self");
206  
207 7 my $rpath = $self->path;
208 7 ($_, $_, my $bpath) = uri_split("$base");
209  
210 7 ▶ if ($bpath =~ m|/$| && $rpath eq $bpath) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bpath =~ m[/$] and $rpath eq $bpath) { } 3 4 7
Condition100%3/3
$bpath =~ m[/$] and $rpath eq $bpath
!ll&&!rl&&r
313
MC/DC100%2/2
$bpath =~ m[/$] and $rpath eq $bpath
$bpath =~ m[/$] $rpath eq $bpath
Truth table100%3/3
A and B
A= $bpath =~ m[/$]B= $rpath eq $bpath
ABresult
0X0
100
111
211 3 $rel->path('./');
212 }
213 else {
214 # Ensure both paths begin with '/'
215 4 ▶ $rpath = "/$rpath" unless $rpath =~ m|^/|;
Branch: 1 branch
BranchTrueFalseTotal
unless $rpath =~ m[^/] 0 4 4
216 4 ▶ $bpath = "/$bpath" unless $bpath =~ m|^/|;
Branch: 1 branch
BranchTrueFalseTotal
unless $bpath =~ m[^/] 0 4 4
217  
218 # Remove common leading path segments
219 4 my ($idx, $brk) = (1, 0);
220  
221 # Scan for matching segments
222 4 while (1) {
223 # Locate the next delimiter
224 5 $brk = index($rpath, '/', $idx);
225  
226 5 ▶ last if $brk < 0; # not found
Branch: 1 branch
BranchTrueFalseTotal
if $brk < 0 1 4 5
227 4 ▶ last if $brk != index($bpath, '/', $idx); # no match: different segment lengths
Branch: 1 branch
BranchTrueFalseTotal
if $brk != index($bpath, "/", $idx) 2 2 4
228 2 ▶ last if substr($rpath, $idx, $brk - $idx) # no match: segments have different string values
Branch: 1 branch
BranchTrueFalseTotal
if substr($rpath, $idx, $brk - $idx) ne substr($bpath, $idx, $brk - $idx) 1 1 2
229 ne substr($bpath, $idx, $brk - $idx);
230  
231 1 $idx = $brk + 1; # move past delimiter
232 }
233  
234 # $idx now matches the slash after the common prefix; remove path contents
235 # up to that point.
236 4 substr($rpath, 0, $idx) = '';
237 4 substr($bpath, 0, $idx) = '';
238  
239 # Add ../ for each remaining base path segment
240 4 ▶ while ($bpath =~ m|/|gc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bpath =~ m[/]cg) 2 4 6
241 2 $rpath = "../$rpath";
242 }
243  
244 # An empty path becomes ./
245 4 ▶ $rpath ||= './';
Condition50%1/2
$rpath ||= "./"
l!l
40
MC/DC0%0/1
$rpath ||= "./"
$rpath
Truth table50%1/2
A
A= $rpath
Aresult
11
00
246  
247 4 $rel->path($rpath);
248 }
249  
250 7 $rel->clear_scheme;
251 7 $rel->clear_auth;
252  
253 7 return $rel;
254 }
255  
256 0 ▶sub rel {
Subroutine rel: not called CC=1 SCAR=6.9
Pod documented
257 0 goto \&relative;
258 }
259  
260 3 ▶sub _walk {
Subroutine _walk: called CC=13 SCAR=26.6
261 3 my ($ref, $sub) = @_;
262 3 my @stack = ($ref);
263 3 my %seen;
264  
265 3 ▶ while (my $elt = shift @stack) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $elt = shift @stack) 9 3 12
266 9 my $ref = ref $elt;
267  
268 9 ▶ if (defined $ref) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ref) 9 0 9
269 9 my $addr = refaddr $elt;
270 9 ▶ next if exists $seen{ $addr };
Branch: 1 branch
BranchTrueFalseTotal
if exists $seen{$addr} 1 8 9
271 8 $seen{ $addr } = 1;
272  
273 8 ▶ if ($ref eq 'ARRAY') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ref eq 'ARRAY') { } 2 6 8
elsif ($ref eq 'HASH') { } 6 0 6
elsif ($ref eq 'SCALAR') { } 0 0 0
274 2 for (0 .. @$elt - 1) {
275 4 ▶ if (ref $elt->[$_]) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $elt->[$_]) { } 0 4 4
elsif (defined $elt->[$_]) { } 4 0 4
276 0 push @stack, $elt->[$_];
277 }
278 elsif (defined $elt->[$_]) {
279 4 $elt->[$_] = $sub->( $elt->[$_] );
280 }
281 }
282 }
283 elsif ($ref eq 'HASH') {
284 6 foreach (keys %$elt) {
285 11 ▶ if (ref $elt->{$_}) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $elt->{$_}) { } 6 5 11
elsif (defined $elt->{$_}) { } 3 2 5
286 6 push @stack, $elt->{$_};
287 }
288 elsif (defined $elt->{$_}) {
289 3 $elt->{$_} = $sub->( $elt->{$_} );
290 }
291 }
292 }
293 elsif ($ref eq 'SCALAR') {
294 0 push @stack, $$elt;
295 }
296 }
297 }
298  
299 3 $ref;
300 }
301  
302 3 ▶sub escape_tree {
Subroutine escape_tree: called CC=2 SCAR=6.9
Pod documented
303 3 my ($ref, @args) = @_;
304 3 ▶ ref $ref || croak "escape_tree: reference expected";
Branch: 1 branch
BranchTrueFalseTotal
ref $ref or croak("escape_tree: reference expected") 2 1 3
305  
306 4 ▶ my $sub = sub{
Subroutine __ANON__: called CC=1 SCAR=0.0
307 4 push @_, @args;
308 4 goto \&encode;
309 2 };
310  
311 2 _walk($ref, $sub);
312 }
313  
314 2 ▶sub unescape_tree {
Subroutine unescape_tree: called CC=2 SCAR=6.9
Pod documented
315 2 my ($ref, @args) = @_;
316 2 ▶ ref $ref || croak "unescape_tree: reference expected";
Branch: 1 branch
BranchTrueFalseTotal
ref $ref or croak("unescape_tree: reference expected") 1 1 2
317  
318 3 ▶ my $sub = sub{
Subroutine __ANON__: called CC=1 SCAR=0.0
319 3 push @_, @args;
320 3 goto \&decode;
321 1 };
322  
323 1 _walk($ref, $sub);
324 }
325  
326 =encoding UTF8
327  
328 =head1 NAME
329  
330 URI::Fast - A fast(er) URI parser
331  
332 =head1 SYNOPSIS
333  
334 use URI::Fast qw(uri);
335  
336 my $uri = uri 'http://www.example.com/some/path?fnord=slack&foo=bar';
337  
338 if ($uri->scheme =~ /http(s)?/) {
339 my @path = $uri->path;
340 my $fnord = $uri->param('fnord');
341 my $foo = $uri->param('foo');
342 }
343  
344 if ($uri->path =~ /\/login/ && $uri->scheme ne 'https') {
345 $uri->scheme('https');
346 $uri->param('upgraded', 1);
347 }
348  
349 =head1 DESCRIPTION
350  
351 C<URI::Fast> is a faster alternative to L<URI>. It is written in C and provides
352 basic parsing and modification of a URI.
353  
354 L<URI> is an excellent module; it is battle-tested, robust, and handles many
355 edge cases. As a result, it is rather slower than it would otherwise be for
356 more trivial cases, such as inspecting the path or updating a single query
357 parameter.
358  
359 =head1 EXPORTED SUBROUTINES
360  
361 Subroutines are exported on demand.
362  
363 =head2 uri
364  
365 Accepts a URI string, minimally parses it, and returns a C<URI::Fast> object.
366  
367 Note: passing a C<URI::Fast> instance to this routine will cause the object to
368 be interpolated into a string (via L</to_string>), effectively creating a clone
369 of the original C<URI::Fast> object.
370  
371 =head2 iri
372  
373 Similar to L</uri>, but returns a C<URI::Fast::IRI> object. A C<URI::Fast::IRI>
374 differs from a C<URI::Fast> in that UTF-8 characters are permitted and will not
375 be percent-encoded when modified.
376  
377 =head2 abs_uri
378  
379 Builds a new C<URI::Fast> from a relative URI string and makes it L</absolute>
380 in relation to C<$base>.
381  
382 my $uri = abs_uri 'some/path', 'http://www.example.com/fnord';
383 $uri->to_string; # "http://www.example.com/fnord/some/path"
384  
385 =head2 html_url
386  
387 Parses a URI string, removing whitespace characters ignored in URLs found in
388 HTML documents, replacing backslashes with forward slashes, and making the
389 URL L</normalize>d.
390  
391 If a base URL is specified, the C<URI::Fast> object returned will be made
392 L</absolute> relative to that base URL.
393  
394 # Resulting URL is "https://www.slashdot.org/recent"
395 my $url = html_url '//www.slashdot.org\recent', "https://www.slashdot.org";
396  
397 =head2 uri_split
398  
399 Behaves (hopefully) identically to L<URI::Split>, but roughly twice as fast.
400  
401 =head2 encode/decode/uri_encode/uri_decode
402  
403 See L</ENCODING>.
404  
405 =head1 CONSTRUCTORS
406  
407 =head2 new
408  
409 If desired, both C<URI::Fast> and L<URI::Fast::IRI> may be instantiated using
410 the default OO-flavored constructor, C<new>.
411  
412 my $uri = URI::Fast->new('http://www.example.com');
413  
414 =head2 new_abs
415  
416 OO equivalent to L</abs_uri>.
417  
418 =head2 new_html_url
419  
420 OO equivalent to L</html_url>.
421  
422 =head1 ATTRIBUTES
423  
424 All attributes serve as full accessors, allowing the URI segment to be both
425 retrieved and modified.
426  
427 =head2 RAW ACCESSORS
428  
429 Each attribute defines a C<raw_*> method, which returns the raw, encoded string
430 value for that attribute. If a new value is passed, it will set the field to
431 the raw, unchanged value without checking it or changing it in any way.
432  
433 =head2 CLEARERS
434  
435 Each attribute further has a matching clearer method (C<clear_*>) which unsets
436 its value.
437  
438 =head2 ACCESSORS
439  
440 In general, accessors accept an I<unencoded> string and set their slot value to
441 the I<encoded> value. They return the decoded value. See L</ENCODING> for an in
442 depth description of their behavior as well as an explanation of the more
443 complex behavior of compound fields.
444  
445 =head3 scheme
446  
447 Gets or sets the scheme portion of the URI (e.g. C<http>), excluding C<://>.
448  
449 =head3 auth
450  
451 The authorization section is composed of the username, password, host name, and
452 port number:
453  
454 hostname.com
455 someone@hostname.com
456 someone:secret@hostname.com:1234
457  
458 Setting this field may be done with a string (see the note below about
459 L</ENCODING>) or a hash reference of individual field names (C<usr>, C<pwd>,
460 C<host>, and C<port>). In both cases, the existing values are completely
461 replaced by the new values and any values missing from the caller-supplied
462 input are deleted.
463  
464 =head4 usr
465  
466 The username segment of the authorization string. Updating this value alters
467 L</auth>.
468  
469 =head4 pwd
470  
471 The password segment of the authorization string. Updating this value alters
472 L</auth>.
473  
474 =head4 host
475  
476 The host name segment of the authorization string. May be a domain string or an
477 IP address. If the host is an IPV6 address, it must be surrounded by square
478 brackets (per spec), which are included in the host string. Updating this value
479 alters L</auth>.
480  
481 =head4 port
482  
483 The port number segment of the authorization string. Updating this value alters
484 L</auth>.
485  
486 =head3 path
487  
488 In scalar context, returns the entire path string. In list context, returns a
489 list of path segments, split by C</>.
490  
491 my $uri = uri '/foo/bar';
492 my $path = $uri->path; # "/foo/bar"
493 my @path = $uri->path; # ("foo", "bar")
494  
495 The path may also be updated using either a string or an array ref of segments:
496  
497 $uri->path('/foo/bar');
498 $uri->path(['foo', 'bar']);
499  
500 This differs from the behavior of L<URI/path_segments>, which considers the
501 leading slash separating the path from the authority section to be an
502 individual segment. If this behavior is desired, the lower level
503 C<split_path_compat> is available. C<split_path_compat> (and its partner,
504 C<split_path>), always return an array reference.
505  
506 my $uri = uri '/foo/bar';
507 $uri->split_path; # ['foo', 'bar'];
508 $uri->split_path_compat; # ['', 'foo', 'bar'];
509  
510 =head3 query
511  
512 In scalar context, returns the complete query string, excluding the leading
513 C<?>. The query string may be set in several ways.
514  
515 $uri->query("foo=bar&baz=bat"); # note: no percent-encoding performed
516 $uri->query({foo => 'bar', baz => 'bat'}); # foo=bar&baz=bat
517 $uri->query({foo => 'bar', baz => 'bat'}, ';'); # foo=bar;baz=bat
518  
519 In list context, returns a hash ref mapping query keys to array refs of their
520 values (see L</query_hash>).
521  
522 Both '&' and ';' are treated as separators for key/value parameters.
523  
524 =head3 frag
525  
526 The fragment section of the URI, excluding the leading C<#>.
527  
528 =head3 fragment
529  
530 An alias of L</frag>.
531  
532 =head1 METHODS
533  
534 =head2 query_keys
535  
536 Does a fast scan of the query string and returns a list of unique parameter
537 names that appear in the query string.
538  
539 Both '&' and ';' are treated as separators for key/value parameters.
540  
541 =head2 query_hash
542  
543 Scans the query string and returns a hash ref of key/value pairs. Values are
544 returned as an array ref, as keys may appear multiple times. Both '&' and ';'
545 are treated as separators for key/value parameters.
546  
547 May optionally be called with a new hash of parameters to replace the query
548 string with, in which case keys may map to scalar values or arrays of scalar
549 values. As with all query setter methods, a third parameter may be used to
550 explicitly specify the separator to use when generating the new query string.
551  
552 =head2 param
553  
554 Gets or sets a parameter value. Setting a parameter value will replace existing
555 values completely; the L</query> string will also be updated. Setting a
556 parameter to C<undef> deletes the parameter from the URI.
557  
558 $uri->param('foo', ['bar', 'baz']);
559 $uri->param('fnord', 'slack');
560  
561 my $value_scalar = $uri->param('fnord'); # fnord appears once
562 my @value_list = $uri->param('foo'); # foo appears twice
563 my $value_scalar = $uri->param('foo'); # croaks; expected single value but foo has multiple
564  
565 # Delete parameter
566 $uri->param('foo', undef); # deletes foo
567  
568 # Ambiguous cases
569 $uri->param('foo', ''); # foo=
570 $uri->param('foo', '0'); # foo=0
571 $uri->param('foo', ' '); # foo=%20
572  
573 Both '&' and ';' are treated as separators for key/value parameters when
574 parsing the query string. An optional third parameter explicitly selects the
575 character used to separate key/value pairs.
576  
577 $uri->param('foo', 'bar', ';'); # foo=bar
578 $uri->param('baz', 'bat', ';'); # foo=bar;baz=bat
579  
580 When unspecified, '&' is chosen as the default. I<In either case, all
581 separators in the query string will be normalized to the chosen separator>.
582  
583 $uri->param('foo', 'bar', ';'); # foo=bar
584 $uri->param('baz', 'bat', ';'); # foo=bar;baz=bat
585 $uri->param('fnord', 'slack'); # foo=bar&baz=bat&fnord=slack
586  
587 =head2 add_param
588  
589 Updates the query string by adding a new value for the specified key. If the
590 key already exists in the query string, the new value is appended without
591 altering the original value.
592  
593 $uri->add_param('foo', 'bar'); # foo=bar
594 $uri->add_param('foo', 'baz'); # foo=bar&foo=baz
595  
596 This method is simply sugar for calling:
597  
598 $uri->param('key', [$uri->param('key'), 'new value']);
599  
600 As with L</param>, the separator character may be specified as the final
601 parameter. The same caveats apply with regard to normalization of the query
602 string separator.
603  
604 $uri->add_param('foo', 'bar', ';'); # foo=bar
605 $uri->add_param('foo', 'baz', ';'); # foo=bar;foo=baz
606  
607 =head2 query_keyset
608  
609 Allows modification of the query string in the manner of a set, using keys
610 without C<=value>, e.g. C<foo&bar&baz>. Accepts a hash ref of keys to update.
611 A truthy value adds the key, a falsey value removes it. Any keys not mentioned
612 in the update hash are left unchanged.
613  
614 my $uri = uri '&baz&bat';
615 $uri->query_keyset({foo => 1, bar => 1}); # baz&bat&foo&bar
616 $uri->query_keyset({baz => 0, bat => 0}); # foo&bar
617  
618 If there are key-value pairs in the query string as well, the behavior of
619 this method becomes a little more complex. When a key is specified in the
620 hash update hash ref, a positive value will leave an existing key/value pair
621 untouched. A negative value will remove the key and value.
622  
623 my $uri = uri '&foo=bar&baz&bat';
624 $uri->query_keyset({foo => 1, baz => 0}); # foo=bar&bat
625  
626 An optional second parameter may be specified to control the separator
627 character used when updating the query string. The same caveats apply with
628 regard to normalization of the query string separator.
629  
630 =head2 append
631  
632 Serially appends path segments, query strings, and fragments, to the end of the
633 URI. Each argument is added in order. If the segment begins with C<?>, it is
634 assumed to be a query string and it is appended using L</add_param>. If the
635 segment begins with C<#>, it is treated as a fragment, replacing any existing
636 fragment. Otherwise, the segment is treated as a path fragment and appended to
637 the path.
638  
639 my $uri = uri 'http://www.example.com/foo?k=v';
640 $uri->append('bar', 'baz/bat', '?k=v1&k=v2', '#fnord', 'slack');
641 # 'http://www.example.com/foo/bar/baz/bat/slack?k=v&k=v1&k=v2#fnord'
642  
643  
644 =head2 to_string
645  
646 =head2 as_string
647  
648 =head2 "$uri"
649  
650 Stringifies the URI, encoding output as necessary. String interpolation is
651 overloaded.
652  
653 =head2 compare
654  
655 =head2 $uri eq $other
656  
657 Compares the URI to another, returning true if the URIs are equivalent.
658 Overloads the C<eq> operator.
659  
660 =head2 clone
661  
662 Sugar for:
663  
664 my $uri = uri '...';
665 my $clone = uri $uri;
666  
667 =head2 absolute
668  
669 Builds an absolute URI from a relative URI and a base URI string.
670 Adheres as strictly as possible to the rules for resolving a target URI in
671 L<RFC3986 section 5.2|https://www.rfc-editor.org/rfc/rfc3986.txt>. Returns a new
672 L<URI::Fast> object representing the absolute, merged URI.
673  
674 my $uri = uri('some/path')->absolute('http://www.example.com/fnord');
675 $uri->to_string; # "http://www.example.com/fnord/some/path"
676  
677 =head2 abs
678  
679 Alias of L</absolute>.
680  
681 =head2 relative
682  
683 Builds a relative URI using a second URI (either a C<URI::Fast> object or a
684 string) as a base. Unlike L<URI/rel>, ignores differences in domain and scheme
685 assumes the caller wishes to adopt the base URL's instead. Aside from that difference,
686 it's behavior should mimic L<URI/rel>'s.
687  
688 my $uri = uri('http://example.com/foo/bar')->relative('http://example.com/foo');
689 $uri->to_string; # "foo/bar"
690  
691 my $uri = uri('http://example.com/foo/bar/')->relative('http://example.com/foo');
692 $uri->to_string; # "foo/bar/"
693  
694 =head2 rel
695  
696 Alias of L</relative>.
697  
698 =head2 normalize
699  
700 Similar to L<URI/canonical>, performs a minimal normalization on the URI. Only
701 generic normalization described in the rfc is performed; no scheme-specific
702 normalization is done. Specifically, the scheme and host members are converted
703 to lower case, dot segments are collapsed in the path, and any percent-encoded
704 characters in the URI are converted to upper case.
705  
706 =head2 canonical
707  
708 Alias of L</normalize>.
709  
710 =head1 ENCODING
711  
712 C<URI::Fast> tries to do the right thing in most cases with regard to reserved
713 and non-ASCII characters. C<URI::Fast> will fully encode reserved and non-ASCII
714 characters when setting I<individual> values and return their fully decoded
715 values. However, the "right thing" is somewhat ambiguous when it comes to
716 setting compound fields like L</auth>, L</path>, and L</query>.
717  
718 When setting compound fields with a string value, reserved characters are
719 expected to be present, and are therefore accepted as-is. Any non-ASCII
720 characters will be percent-encoded (since they are unambiguous and there is no
721 risk of double-encoding them). Thus,
722  
723 $uri->auth('someone:secret@Ῥόδος.com:1234');
724 print $uri->auth; # "someone:secret@%E1%BF%AC%CF%8C%CE%B4%CE%BF%CF%82.com:1234"
725  
726 On the other hand, when setting these fields with a I<reference> value (assumed
727 to be a hash ref for L</auth> and L</query> or an array ref for L</path>; see
728 individual methods' docs for details), each field is fully percent-encoded,
729 just as if each individual simple slot's setter had been called:
730  
731 $uri->auth({usr => 'some one', host => 'somewhere.com'});
732 print $uri->auth; # "some%20one@somewhere.com"
733 print $uri->usr;; # "some one"
734  
735 The same goes for return values. For compound fields returning a string,
736 non-ASCII characters are decoded but reserved characters are not. When
737 returning a list or reference of the deconstructed field, individual values are
738 decoded of both reserved and non-ASCII characters.
739  
740 =head2 '+' vs '%20'
741  
742 Although no longer part of the standard, C<+> is commonly used as the encoded
743 space character (rather than C<%20>); it I<is> still official to the
744 C<application/x-www-form-urlencoded> type, and is treated as a space by
745 L</decode>.
746  
747 =head2 encode
748  
749 Percent-encodes a string for use in a URI. By default, both reserved and UTF-8
750 chars (C<! * ' ( ) ; : @ & = + $ , / ? # [ ] %>) are encoded.
751  
752 A second (optional) parameter provides a string containing any characters the
753 caller does not wish to be encoded. An empty string will result in the default
754 behavior described above.
755  
756 For example, to encode all characters in a query-like string I<except> for
757 those used by the query:
758  
759 my $encoded = URI::Fast::encode($some_string, '?&=');
760  
761 =head2 decode
762  
763 Decodes a percent-encoded string.
764  
765 my $decoded = URI::Fast::decode($some_string);
766  
767 =head2 uri_encode
768  
769 =head2 uri_decode
770  
771 These are aliases of L</encode> and L</decode>, respectively. They were added
772 to make L<BLUEFEET|https://metacpan.org/author/BLUEFEET> happy after he made
773 fun of me for naming L</encode> and L</decode> too generically.
774  
775 In fact, these were originally aliased as C<url_encode> and C<url_decode>, but
776 due to some pedantic whining on the part of
777 L<BGRIMM|https://metacpan.org/author/BGRIMM>, they have been renamed to
778 C<uri_encode> and C<uri_decode>.
779  
780 =head2 escape_tree
781  
782 =head2 unescape_tree
783  
784 Traverses a data structure, escaping or unescaping I<defined> scalar values in
785 place. Accepts a reference to be traversed. Any further parameters are passed
786 unchanged to L</encode> or L</decode>. Croaks if the input to escape/unescape
787 is a non-reference value.
788  
789 my $obj = {
790 foo => ['bar baz', 'bat%fnord'],
791 bar => {baz => 'bat%bat'},
792 baz => undef,
793 bat => '',
794 };
795  
796 URI::Fast::escape_tree($obj);
797  
798 # $obj is now:
799 {
800 foo => ['bar%20baz', 'bat%25fnord'],
801 bar => {baz => 'bat%25bat'},
802 baz => undef,
803 bat => '',
804 }
805  
806 URI::Fast::unescape_tree($obj); # $obj returned to original form
807  
808 URI::Fast::escape_tree($obj, '%'); # escape but allow "%"
809  
810 # $obj is now:
811 {
812 foo => ['bar%20baz', 'bat%fnord'],
813 bar => {baz => 'bat%bat'},
814 baz => undef,
815 bat => '',
816 }
817  
818 =head1 CAVEATS
819  
820 This module is designed to parse URIs according to RFC 3986. Browsers parse
821 URLs using a different (but similar) algorithm and some strings that are valid
822 URLs to browsers are not valid URIs to this module. The L</html_url> function
823 attempts to parse URLs more in line with how browsers do, but no guarantees are
824 made as HTML standards and browser implementations are an ever shifting
825 landscape.
826  
827 =head1 SPEED
828  
829 See L<URI::Fast::Benchmarks>.
830  
831 =head1 SEE ALSO
832  
833 =over
834  
835 =item L<URI>
836  
837 The de facto standard.
838  
839 =item L<RFC 3986|https://www.rfc-editor.org/rfc/rfc3986.txt>
840  
841 The official standard.
842  
843 =back
844  
845 =head1 ACKNOWLEDGEMENTS
846  
847 Thanks to L<ZipRecruiter|https://www.ziprecruiter.com> for encouraging their
848 employees to contribute back to the open source ecosystem. Without their
849 dedication to quality software development this distribution would not exist.
850  
851 =head1 CONTRIBUTORS
852  
853 The following people have contributed to this module with patches, bug reports,
854 API advice, identifying areas where the documentation is unclear, or by making
855 fun of me for naming certain methods too generically.
856  
857 =over
858  
859 =item Andy Ruder
860  
861 =item Aran Deltac (BLUEFEET)
862  
863 =item Ben Grimm (BGRIMM)
864  
865 =item Dave Hubbard (DAVEH)
866  
867 =item James Messrie
868  
869 =item Martin Locklear
870  
871 =item Randal Schwartz (MERLYN)
872  
873 =item Sara Siegal (SSIEGAL)
874  
875 =item Tim Vroom (VROOM)
876  
877 =item Des Daignault (NAWGLAN)
878  
879 =item Josh Rosenbaum
880  
881 =back
882  
883 =head1 AUTHOR
884  
885 Jeff Ober <sysread@fastmail.fm>
886  
887 =head1 COPYRIGHT AND LICENSE
888  
889 This software is copyright (c) 2018 by Jeff Ober. This is free software; you
890 can redistribute it and/or modify it under the same terms as the Perl 5
891 programming language system itself.
892  
893 =cut
894  
895 19 1;
↑ Summary blib/lib/URI/Fast/IRI.pm »