lib/Geo/Address/Formatter.pm

filter: Statementstmt 87.9% 538 / 612 Branchbran 76.6% 213 / 278 Conditioncond 72.1% 57 / 79 MC/DCmcdc 46.3% 19 / 41 Subroutinesub 89.3% 42 / 47 Podpod 100% 4 / 4 totaltotal 82.2% 873 / 1061 CC 206 SCAR 31.3
CC
206
Cov
83%
format_address
77.1
_apply_replacements
25.2
_determine_country_code
19.3
CRAP 22.9
« blib/lib/Geo/Address/Formatter.pm ↑ Summary
1 package Geo::Address::Formatter;
2 7 $Geo::Address::Formatter::VERSION = '1.9993';
3 # ABSTRACT: take structured address data and format it according to the various global/country rules
4  
5 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use feature qw(say);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use Clone qw(clone);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 $Data::Dumper::Sortkeys = 1;
11 7 ▶use File::Basename qw(dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use Ref::Util qw(is_hashref);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 7 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 7 ▶use Text::Hogan::Compiler;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 7 ▶use Try::Catch;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 7 ▶use YAML::XS qw(LoadFile);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 7 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 7 my $THC = Text::Hogan::Compiler->new;
20  
21 # optional params
22 7 my $show_warnings = 1;
23 7 my $debug = 0;
24 7 my $only_address = 0;
25  
26  
27  
28  
29 7 my $instance;
30  
31 sub instance {
32 0 ▶ my ($class, %params) = @_;
Subroutine instance: not called CC=3 SCAR=24.8
Pod documented
33
34 0 ▶ unless ($instance) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($instance) 0 0 0
35 0 $instance = $class->new(%params);
36 }
37  
38 0 ▶ say STDERR "************* in Geo::Address::Formatter::instance ***" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 0 0
39
40 # clear these fields that change on each run
41 0 $instance->{final_components} = undef;
42 0 $instance->{set_district_alias} = {};
43  
44 0 return $instance;
45 }
46  
47 sub new {
48 20 ▶ my ($class, %params) = @_;
Subroutine new: called CC=10 SCAR=23.8
Pod documented
49  
50 20 my $self = {};
51 20 ▶ my $conf_path = $params{conf_path} || die "no conf_path set";
Condition50%1/2
$params{'conf_path'} || die('no conf_path set')
l!l
200
MC/DC0%0/1
$params{'conf_path'} || die('no conf_path set')
$params{'conf_path'}
Truth table50%1/2
A
A= $params{'conf_path'}
Aresult
11
00
52  
53 # optional params
54 20 ▶ if ( defined($params{no_warnings}) && ($params{no_warnings})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params{"no_warnings"} and $params{"no_warnings"}) 1 19 20
Condition66%2/3
defined $params{"no_warnings"} and $params{"no_warnings"}
!ll&&!rl&&r
1901
MC/DC50%1/2
defined $params{"no_warnings"} and $params{"no_warnings"}
defined $params{"no_warnings"} $params{"no_warnings"}
Truth table66%2/3
A and B
A= defined $params{"no_warnings"}B= $params{"no_warnings"}
ABresult
0X0
100
111
55 1 $show_warnings = 0;
56 }
57 20 ▶ $only_address = (defined($params{only_address}) && $params{only_address}) // 0;
Condition60%3/5
defined $params{"only_address"} && $params{"only_address"} // 0
l!l
200
defined $params{"only_address"} and $params{"only_address"}
!ll&&!rl&&r
1802
MC/DC50%1/2
defined $params{"only_address"} && $params{"only_address"} // 0
defined $params{"only_address"} $params{"only_address"}
Truth table66%2/3
A and B
A= defined $params{"only_address"}B= $params{"only_address"}
ABresult
111
0X0
100
58 20 ▶ $debug = (defined($params{debug}) && $params{debug}) // 0;
Condition60%3/5
defined $params{"debug"} && $params{"debug"} // 0
l!l
200
defined $params{"debug"} and $params{"debug"}
!ll&&!rl&&r
1505
MC/DC50%1/2
defined $params{"debug"} && $params{"debug"} // 0
defined $params{"debug"} $params{"debug"}
Truth table66%2/3
A and B
A= defined $params{"debug"}B= $params{"debug"}
ABresult
111
0X0
100
59  
60 20 $self->{final_components} = undef;
61 20 $self->{set_district_alias} = {};
62  
63 20 bless($self, $class);
64  
65 20 ▶ say STDERR "************* in Geo::Address::Formatter::new ***" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 20 20
66  
67 # is slow because lots of conf, and pre-compiling
68 20 ▶ if ($self->_read_configuration($conf_path)){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_read_configuration($conf_path)) 19 1 20
69 19 return $self;
70 }
71 1 die 'unable to read configuration';
72 }
73  
74 sub _read_configuration {
75 20 ▶ my $self = shift;
Subroutine _read_configuration: called CC=12 SCAR=25.5
76 20 my $path = shift;
77  
78 20 ▶ return if (! -e $path);
Branch: 1 branch
BranchTrueFalseTotal
unless -e $path 0 20 20
79 # components file
80 20 my $compyaml = $path . '/components.yaml';
81 20 ▶ return if (! -e $compyaml);
Branch: 1 branch
BranchTrueFalseTotal
unless -e $compyaml 1 19 20
82  
83 19 $self->{templates} = {};
84 19 $self->{component_aliases} = {};
85 19 $self->{component2type} = {};
86 19 $self->{ordered_components} = [];
87  
88 # read the config file(s)
89 19 my $loaded = 0;
90  
91 19 my $wwfile = $path . '/countries/worldwide.yaml';
92 19 ▶ say STDERR "loading templates $wwfile" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 19 19
93  
94 19 ▶ return if (! -e $wwfile);
Branch: 1 branch
BranchTrueFalseTotal
unless -e $wwfile 0 19 19
95  
96 try {
97 19 ▶ my $rh_templates = LoadFile($wwfile);
Subroutine __ANON__: called CC=2 SCAR=6.9
98 19 foreach (keys %$rh_templates) {
99 3855 $self->{templates}{$_} = $rh_templates->{$_};
100 3855 $loaded = 1;
101 }
102 } catch {
103 0 ▶ warn "error parsing country configuration in $wwfile";
Subroutine __ANON__: not called CC=1 SCAR=6.9
104 0 return;
105 19 };
106 19 ▶ return if ($loaded == 0); # no templates
Branch: 1 branch
BranchTrueFalseTotal
if $loaded == 0 0 19 19
107  
108 # see if we can load the components
109 try {
110 19 ▶ say STDERR "loading components" if ($debug);
Subroutine __ANON__: called CC=10 SCAR=24.1
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 19 19
111 19 my @c = LoadFile($compyaml);
112  
113 19 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 19 19
114 0 say STDERR Dumper \@c;
115 }
116  
117 19 foreach my $rh_c (@c) {
118 304 ▶ if (defined($rh_c->{name})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_c->{"name"}) 304 0 304
119 304 ▶ if (defined($rh_c->{aliases})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_c->{'aliases'}) { } 187 117 304
120 187 $self->{component_aliases}{$rh_c->{name}} = $rh_c->{aliases};
121 } else {
122 117 $self->{component_aliases}{$rh_c->{name}} = [];
123 }
124 }
125 }
126  
127 19 foreach my $rh_c (@c) {
128 304 push(@{$self->{ordered_components}}, $rh_c->{name});
129 304 $self->{component2type}->{$rh_c->{name}} = $rh_c->{name};
130  
131 304 ▶ if (defined($rh_c->{aliases})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_c->{"aliases"}) 187 117 304
132 187 foreach my $alias (@{$rh_c->{aliases}}) {
133 638 push(@{$self->{ordered_components}}, $alias);
134 638 $self->{component2type}->{$alias} = $rh_c->{name};
135 }
136 }
137 }
138 19 my %h_known = map { $_ => 1 } @{$self->{ordered_components}};
139 19 $self->{h_known} = \%h_known;
140  
141 19 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 19 19
142 0 say STDERR 'component_aliases';
143 0 say STDERR Dumper $self->{component_aliases};
144 0 say STDERR 'component2type';
145 0 say STDERR Dumper $self->{component2type};
146 }
147 } catch {
148 0 ▶ warn "error parsing component configuration: $_";
Subroutine __ANON__: not called CC=1 SCAR=6.9
149 19 };
150  
151 # get the county and state codes and country2lang conf
152 19 my @conf_files = qw(county_codes state_codes country2lang);
153 19 foreach my $cfile (@conf_files) {
154 57 $self->{$cfile} = {};
155 57 my $yfile = $path . '/' . $cfile . '.yaml';
156 57 ▶ if (-e $yfile) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $yfile) 51 6 57
157 try {
158 51 ▶ $self->{$cfile} = LoadFile($yfile);
Subroutine __ANON__: called CC=1 SCAR=0.0
159 } catch {
160 0 ▶ warn "error parsing $cfile configuration: $_";
Subroutine __ANON__: not called CC=1 SCAR=6.9
161 51 };
162 }
163 }
164  
165 19 my $abbrvdir = $path . '/abbreviations';
166  
167 19 ▶ if (-d $abbrvdir){
Branch: 1 branch
BranchTrueFalseTotal
if (-d $abbrvdir) 15 4 19
168 15 ▶ opendir my $dh, $abbrvdir
Branch: 1 branch
BranchTrueFalseTotal
opendir my $dh, $abbrvdir or die "Could not open '${abbrvdir}' for read: $!\n" 0 15 15
169 or die "Could not open '$abbrvdir' for read: $!\n";
170  
171 15 ▶ while (my $file = readdir $dh) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $file = readdir $dh)) 361 15 376
172 # say STDERR "file: $file";
173 361 ▶ if ($file =~ m/^(\w\w)\.yaml$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ /^(\w\w)\.yaml$/) 331 30 361
174 331 my $lang = $1; # two letter lang code like 'en'
175 331 my $abbrvfile = $abbrvdir . '/' . $file;
176 try {
177 331 ▶ $self->{abbreviations}->{$lang} = LoadFile($abbrvfile);
Subroutine __ANON__: called CC=1 SCAR=0.0
178 } catch {
179 0 ▶ warn "error parsing abbrv conf in $abbrvfile: $_";
Subroutine __ANON__: not called CC=1 SCAR=6.9
180 331 };
181 }
182 }
183 15 closedir $dh;
184 }
185  
186 #say Dumper $self->{abbreviations};
187 #say Dumper $self->{country2lang};
188  
189 19 $self->_precompile_rules();
190 19 $self->_build_code_lookups();
191 19 $self->_precompile_abbreviations();
192  
193 19 return 1;
194 }
195  
196 sub _precompile_rules {
197 19 ▶ my $self = shift;
Subroutine _precompile_rules: called CC=11 SCAR=24.4
198  
199 19 foreach my $cc (keys %{$self->{templates}}) {
200 3855 my $tpl = $self->{templates}{$cc};
201 3855 ▶ next unless is_hashref($tpl);
Branch: 1 branch
BranchTrueFalseTotal
unless is_hashref($tpl) 355 3500 3855
202  
203 # Pre-compile replace rules
204 3500 ▶ if (defined($tpl->{replace})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tpl->{"replace"}) 251 3249 3500
205 251 my @compiled;
206 251 foreach my $ra_fromto (@{$tpl->{replace}}) {
207 853 my $pattern = $ra_fromto->[0];
208 853 my $replacement = $ra_fromto->[1];
209 853 my ($comp_name, $exact_match, $re);
210  
211 # detect component-specific rules like "state=Some Value"
212 853 ▶ if ($pattern =~ m/^(\w+)=(.+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pattern =~ /^(\w+)=(.+)$/) { } 208 645 853
213 208 $comp_name = $1;
214 208 my $rest = $2;
215 # try to compile as regex; if it fails, it's an exact match
216 208 eval { $re = qr/$rest/i };
217 208 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 208 208
218 0 warn "invalid replacement regex '$rest' for $cc, skipping";
219 0 next;
220 }
221 208 $exact_match = $rest;
222 } else {
223 645 eval { $re = qr/$pattern/i };
224 645 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 645 645
225 0 warn "invalid replacement regex '$pattern' for $cc, skipping";
226 0 next;
227 }
228 }
229 853 push @compiled, {
230 component => $comp_name,
231 exact_match => $exact_match,
232 re => $re,
233 replacement => $replacement,
234 };
235 }
236 251 $tpl->{_compiled_replace} = \@compiled;
237 }
238  
239 # Pre-compile postformat_replace rules
240 3500 ▶ if (defined($tpl->{postformat_replace})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tpl->{"postformat_replace"}) 461 3039 3500
241 461 my @compiled;
242 461 foreach my $ra_fromto (@{$tpl->{postformat_replace}}) {
243 801 my $pattern = $ra_fromto->[0];
244 801 my $replacement = $ra_fromto->[1];
245 801 my $re;
246 801 eval { $re = qr/$pattern/ };
247 801 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 801 801
248 0 warn "invalid postformat regex '$pattern' for $cc, skipping";
249 0 next;
250 }
251 801 push @compiled, {
252 re => $re,
253 replacement => $replacement,
254 };
255 }
256 461 $tpl->{_compiled_postformat} = \@compiled;
257 }
258 }
259 19 return;
260 }
261  
262 sub _build_code_lookups {
263 19 ▶ my $self = shift;
Subroutine _build_code_lookups: called CC=8 SCAR=20.8
264  
265 19 foreach my $type (qw(state_codes county_codes)) {
266 38 my $reverse_key = $type . '_reverse';
267 38 my $name_key = $type . '_name';
268 38 $self->{$reverse_key} = {};
269 38 $self->{$name_key} = {};
270  
271 38 ▶ my $data = $self->{$type} // next;
Condition50%1/2
$self->{$type} // (next)
l!l
380
MC/DC0%0/1
$self->{$type} // (next)
$self->{$type}
Truth table50%1/2
A
A= $self->{$type}
Aresult
11
00
272 38 foreach my $cc (keys %$data) {
273 1593 my $mapping = $data->{$cc};
274 1593 my $rev = {};
275 1593 my $name = {};
276  
277 1593 foreach my $code (keys %$mapping) {
278 33864 my $val = $mapping->{$code};
279 33864 ▶ if (is_hashref($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (is_hashref($val)) { } 5676 28188 33864
280 # hash with default, alt, alt_XX keys
281 5676 my $default_name = $val->{default};
282 5676 ▶ $name->{$code} = $default_name if defined $default_name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $default_name 5676 0 5676
283 5676 foreach my $v (values %$val) {
284 12223 $rev->{uc($v)} = $code;
285 }
286 } else {
287 # simple string value
288 28188 $name->{$code} = $val;
289 28188 $rev->{uc($val)} = $code;
290 }
291 # code-to-code identity lookup
292 33864 $rev->{$code} = $code;
293 }
294 1593 $self->{$reverse_key}{$cc} = $rev;
295 1593 $self->{$name_key}{$cc} = $name;
296 }
297 }
298 19 return;
299 }
300  
301 sub _precompile_abbreviations {
302 19 ▶ my $self = shift;
Subroutine _precompile_abbreviations: called CC=5 SCAR=16.1
303 19 ▶ my $abbr = $self->{abbreviations} // return;
Condition100%2/2
$self->{"abbreviations"} // (return)
l!l
154
MC/DC100%1/1
$self->{"abbreviations"} // (return)
$self->{"abbreviations"}
Truth table100%2/2
A
A= $self->{"abbreviations"}
Aresult
11
00
304  
305 15 foreach my $lang (keys %$abbr) {
306 331 foreach my $comp_name (keys %{$abbr->{$lang}}) {
307 424 my $rh_pairs = $abbr->{$lang}{$comp_name};
308 424 my @compiled;
309 424 foreach my $long (keys %$rh_pairs) {
310 push @compiled, {
311 re => qr/(^|\s)\Q$long\E\b/,
312 5715 short => $rh_pairs->{$long},
313 };
314 }
315 424 $self->{compiled_abbreviations}{$lang}{$comp_name} = \@compiled;
316 }
317 }
318 15 return;
319 }
320  
321  
322 sub final_components {
323 6 ▶ my $self = shift;
Subroutine final_components: called CC=3 SCAR=11.0
Pod documented
324 6 ▶ if (defined($self->{final_components})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"final_components"}) 5 1 6
325 5 return $self->{final_components};
326 }
327 1 ▶ warn 'final_components not yet set' if ($show_warnings);
Branch: 1 branch
BranchTrueFalseTotal
if $show_warnings 1 0 1
328 1 return;
329 }
330  
331  
332 sub format_address {
333 490 ▶ my $self = shift;
Subroutine format_address: called CC=45 SCAR=43.5
Pod documented
334 490 ▶ my $rh_components = clone(shift) || return;
Condition50%1/2
&clone(shift()) || (return)
l!l
4900
MC/DC0%0/1
&clone(shift()) || (return)
&clone(shift())
Truth table50%1/2
A
A= &clone(shift())
Aresult
11
00
335 490 ▶ my $rh_options = shift || {};
Condition100%2/2
shift() || {}
l!l
15475
MC/DC100%1/1
shift() || {}
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
336  
337 # 1. make sure empty at the beginning
338 490 $self->{final_components} = undef;
339  
340 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
341 0 say STDERR "*** in format_address ***";
342 0 say STDERR Dumper $rh_options;
343 0 say STDERR Dumper $rh_components;
344 }
345  
346 # 2. deal with the options
347  
348 490 foreach (grep { ! /^[a-z0-9_]+$/ } keys %$rh_components) {
349 7 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 7 7
350 0 say STDERR "Skipping compontent $_";
351 }
352 7 delete $rh_components->{$_};
353 }
354  
355 # 2a. which country format will we use?
356 # might have been specified in options
357 # otherwise look at components
358 my $cc = $rh_options->{country}
359 490 ▶ || $self->_determine_country_code($rh_components)
Condition100%5/5
$rh_options->{'country'} || $self->_determine_country_code($rh_components) || ''
l!l
4864
$rh_options->{"country"} or $self->_determine_country_code($rh_components)
l!l&&r!l&&!r
14854
MC/DC100%2/2
$rh_options->{'country'} || $self->_determine_country_code($rh_components) || ''
$rh_options->{"country"} $self->_determine_country_code($rh_components)
Truth table100%3/3
A or B
A= $rh_options->{"country"}B= $self->_determine_country_code($rh_components)
ABresult
1X1
011
000
360 || '';
361  
362 490 ▶ if ($cc) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cc) 486 4 490
363 486 $rh_components->{country_code} = $cc;
364 486 $self->_set_district_alias($cc);
365 }
366  
367 # 2b. should we abbreviate?
368 490 ▶ my $abbrv = $rh_options->{abbreviate} // 0;
Condition100%2/2
$rh_options->{"abbreviate"} // 0
l!l
10480
MC/DC100%1/1
$rh_options->{"abbreviate"} // 0
$rh_options->{"abbreviate"}
Truth table100%2/2
A
A= $rh_options->{"abbreviate"}
Aresult
11
00
369  
370 # 2c. was only_address set at the formatting level
371 490 my $oa = $only_address;
372 490 ▶ if (defined($rh_options->{only_address})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_options->{"only_address"}) 2 488 490
373 2 $oa = $rh_options->{only_address};
374 }
375  
376 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
377 0 say STDERR "component_aliases";
378 0 say STDERR Dumper $self->{component_aliases};
379 }
380 # done with the options
381  
382 # 3. deal wtih terrible inputs
383 490 $self->_sanity_cleaning($rh_components);
384 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
385 0 say STDERR "after sanity_cleaning applied";
386 0 say STDERR Dumper $rh_components;
387 }
388  
389 # 4. set the aliases, unless this would overwrite something
390 # need to do this in the right order (as defined in the components file)
391 # For example:
392 # both 'city_district' and 'suburb' are aliases of 'neighbourhood'
393 # so which one should we use if both are present?
394 # We should use the one defined first in the list
395  
396 490 my $rhh_p2a;
397 490 foreach my $c (keys %$rh_components){
398  
399 # might not need an alias as it is a primary type
400 3812 ▶ next if (defined($self->{component_aliases}{$c}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"component_aliases"}{$c} 3043 769 3812
401  
402 # it is not a primary type
403 # is there an alias?
404 769 ▶ if (defined($self->{component2type}{$c})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"component2type"}{$c}) 530 239 769
405 530 my $ptype = $self->{component2type}{$c};
406 # but is it already set?
407 530 ▶ if (! defined($rh_components->{$ptype}) ){
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rh_components->{$ptype}) 417 113 530
408 # no, we will set it later
409 417 $rhh_p2a->{$ptype}{$c} = 1;
410  
411 }
412 }
413 }
414  
415 # now we know which primary types have aliases
416 490 foreach my $ptype (keys %$rhh_p2a){
417 # is there more than one?
418 376 my @aliases = keys %{$rhh_p2a->{$ptype}};
419 376 ▶ if (scalar @aliases == 1){
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @aliases == 1) 336 40 376
420 336 $rh_components->{$ptype} = $rh_components->{$aliases[0]};
421 336 next; # we are done with this ptype
422 }
423  
424 # if there is more than one we need to go through the list
425 # so we do them in the right order
426 40 foreach my $c (@{$self->{component_aliases}->{$ptype}}){
427 45 ▶ if (defined($rh_components->{$c})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_components->{$c}) 40 5 45
428 40 $rh_components->{$ptype} = $rh_components->{$c};
429 40 last; # we are done with this ptype
430 }
431 }
432 }
433  
434 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
435 0 say STDERR "after component_aliases applied";
436 0 say STDERR Dumper $rh_components;
437 }
438  
439 # 5. determine the template
440 490 my $template_text;
441 490 ▶ my $rh_config = $self->{templates}{uc($cc)} || $self->{templates}{default};
Condition66%2/3
$self->{'templates'}{uc $cc} || $self->{'templates'}{'default'}
l!l&&r!l&&!r
48460
MC/DC0%0/2
$self->{'templates'}{uc $cc} || $self->{'templates'}{'default'}
$self->{'templates'}{uc $cc} $self->{'templates'}{'default'}
Truth table66%2/3
A || B
A= $self->{'templates'}{uc $cc}B= $self->{'templates'}{'default'}
ABresult
1X1
011
000
442
443 490 ▶ if (defined($rh_options->{address_template})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_options->{'address_template'}) { } 2 488 490
444 2 $template_text = $rh_options->{address_template};
445 }
446 else {
447  
448 488 ▶ if (defined($rh_config->{address_template})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $rh_config->{'address_template'}) { } 486 2 488
elsif (defined $self->{'templates'}{'default'}{'address_template'}) { } 2 0 2
449 486 $template_text = $rh_config->{address_template};
450 } elsif (defined($self->{templates}{default}{address_template})) {
451 2 $template_text = $self->{templates}{default}{address_template};
452 }
453
454 # do we have the minimal components for an address?
455 # or should we instead use the fallback template?
456 488 ▶ if (!$self->_minimal_components($rh_components)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_minimal_components($rh_components)) 57 431 488
457 57 ▶ say STDERR "using fallback" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 57 57
458 57 ▶ if (defined($rh_config->{fallback_template})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $rh_config->{'fallback_template'}) { } 42 15 57
elsif (defined $self->{'templates'}{'default'}{'fallback_template'}) { } 14 1 15
459 42 $template_text = $rh_config->{fallback_template};
460 } elsif (defined($self->{templates}{default}{fallback_template})) {
461 14 $template_text = $self->{templates}{default}{fallback_template};
462 }
463 # no fallback
464 }
465  
466 }
467  
468 490 ▶ say STDERR 'template text: ' . $template_text if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 490 490
469  
470 # 6. clean up the components, possibly add codes
471 490 $self->_fix_country($rh_components);
472 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
473 0 say STDERR "after fix_country";
474 0 say STDERR Dumper $rh_components;
475 }
476  
477 # apply replacements if we have any
478 490 ▶ if (defined($rh_config->{_compiled_replace})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_config->{"_compiled_replace"}) 160 330 490
479 160 $self->_apply_replacements($rh_components, $rh_config->{_compiled_replace});
480 160 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 160 160
481 0 say STDERR "after applying_replacements applied";
482 0 say STDERR Dumper $rh_components;
483 }
484 }
485  
486 490 $self->_add_state_code($rh_components);
487 490 $self->_add_county_code($rh_components);
488 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
489 0 say STDERR "after adding codes";
490 0 say STDERR Dumper $rh_components;
491 }
492  
493 # 7. add the attention, if needed
494 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
495 0 say STDERR "object level only_address: $only_address";
496 0 say STDERR "formatting level only_address: $oa";
497 }
498  
499 490 ▶ if ($oa){
Branch: 1 branch
BranchTrueFalseTotal
if ($oa) { } 3 487 490
500 3 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 3 3
501 0 say STDERR "not looking for unknown_components";
502 0 say STDERR "only_address was specified";
503 }
504 }
505 else {
506 487 my $ra_unknown = $self->_find_unknown_components($rh_components);
507 487 ▶ if (scalar(@$ra_unknown)){
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @$ra_unknown) 230 257 487
508 230 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 230 230
509 0 say STDERR "unknown_components:";
510 0 say STDERR Dumper $ra_unknown;
511 }
512 # need to sort for consistency
513 # FIXME - add better sorting based on meaning of the values
514 $rh_components->{attention} =
515 230 join(', ', map { $rh_components->{$_} } sort @$ra_unknown);
516 230 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 230 230
517 0 say STDERR "putting unknown_components in 'attention'";
518 }
519 }
520 }
521  
522 # 8. abbreviate, if needed
523 490 ▶ if ($abbrv) {
Branch: 1 branch
BranchTrueFalseTotal
if ($abbrv) 10 480 490
524 10 $rh_components = $self->_abbreviate($rh_components);
525 }
526  
527 # 9. prepare the template
528 490 $template_text = $self->_replace_template_lambdas($template_text);
529  
530 # 10. compiled the template
531 490 ▶ my $compiled_template = $self->{compiled_template_cache}{$template_text}
Condition66%2/3
$self->{"compiled_template_cache"}{$template_text} //= $THC->compile($template_text, {"numeric_string_as_string", 1})
l!l&&r!l&&!r
3651250
MC/DC0%0/2
$self->{"compiled_template_cache"}{$template_text} //= $THC->compile($template_text, {"numeric_string_as_string", 1})
$self->{"compiled_template_cache"}{$template_text} $THC->compile($template_text, {"numeric_string_as_string", 1})
Truth table66%2/3
A //= B
A= $self->{"compiled_template_cache"}{$template_text}B= $THC->compile($template_text, {"numeric_string_as_string", 1})
ABresult
1X1
011
000
532 //= $THC->compile($template_text, {'numeric_string_as_string' => 1});
533  
534 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
535 0 say STDERR "before _render_template";
536 0 say STDERR Dumper $rh_components;
537 0 say STDERR "template: ";
538 0 say STDERR Dumper $compiled_template;
539 }
540  
541  
542 # 11. render the template
543 490 my $text = $self->_render_template($compiled_template, $rh_components);
544 490 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 490 490
545 0 say STDERR "text after _render_template $text";
546 }
547  
548 # 12. postformatting
549 490 $text = $self->_postformat($text, $rh_config->{_compiled_postformat});
550  
551 # 13. clean again
552 490 $text = $self->_clean($text);
553  
554 # 14. set final components (so we can get them later)
555 490 $self->{final_components} = $rh_components;
556  
557 # all done
558 490 return $text;
559 }
560  
561 # remove duplicates ("Berlin, Berlin"), do replacements and similar
562 sub _postformat {
563 492 ▶ my $self = shift;
Subroutine _postformat: called CC=8 SCAR=20.8
564 492 my $text = shift;
565 492 my $raa_rules = shift;
566  
567 492 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 492 492
568 0 say STDERR "entering _postformat: $text";
569 0 say STDERR Dumper $raa_rules;
570 }
571  
572 # remove duplicates
573 492 my @before_pieces = split(/, /, $text);
574 492 my %seen;
575 my @after_pieces;
576 492 foreach my $piece (@before_pieces) {
577 610 $piece =~ s/^\s+//g;
578 610 $seen{$piece}++;
579 610 ▶ if (lc($piece) ne 'new york') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $piece ne "new york") 606 4 610
580 606 ▶ next if ($seen{$piece} > 1);
Branch: 1 branch
BranchTrueFalseTotal
if $seen{$piece} > 1 1 605 606
581 }
582 609 push(@after_pieces, $piece);
583 }
584 492 $text = join(', ', @after_pieces);
585  
586 # do any country specific rules
587 492 foreach my $rule (@$raa_rules) {
588 554 my $regexp = $rule->{re};
589 554 my $replacement = $rule->{replacement};
590  
591 # ultra hack to do substitution
592 # limited to $1 and $2, should really be a while loop
593 # doing every substitution
594  
595 554 ▶ if ($replacement =~ m/\$\d/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($replacement =~ /\$\d/) 50 504 554
596 50 ▶ if ($text =~ m/$regexp/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /$regexp/) 21 29 50
597 21 my $tmp1 = $1;
598 21 my $tmp2 = $2;
599 21 my $tmp3 = $3;
600 21 $replacement =~ s/\$1/$tmp1/;
601 21 $replacement =~ s/\$2/$tmp2/;
602 21 $replacement =~ s/\$3/$tmp3/;
603 }
604 }
605 554 $text =~ s/$regexp/$replacement/;
606 }
607 492 return $text;
608 }
609  
610 sub _sanity_cleaning {
611 491 ▶ my $self = shift;
Subroutine _sanity_cleaning: called CC=10 SCAR=23.1
612 491 ▶ my $rh_components = shift || return;
Condition50%1/2
shift() || (return)
l!l
4910
MC/DC0%0/1
shift() || (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
613  
614 # catch insane postcodes
615 491 ▶ if (defined($rh_components->{'postcode'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_components->{"postcode"}) 334 157 491
616 334 ▶ if (length($rh_components->{'postcode'}) > 20) {
Branch: 3 branches
BranchTrueFalseTotal
if (length $rh_components->{'postcode'} > 20) { } 1 333 334
elsif ($rh_components->{'postcode'} =~ /\d+;\d+/) { } 1 332 333
elsif ($rh_components->{'postcode'} =~ /^(\d{5}),\d{5}/) { } 1 331 332
617 1 delete $rh_components->{'postcode'};
618 } elsif ($rh_components->{'postcode'} =~ m/\d+;\d+/) {
619 # sometimes OSM has postcode ranges
620 1 delete $rh_components->{'postcode'};
621 } elsif ($rh_components->{'postcode'} =~ m/^(\d{5}),\d{5}/) {
622 1 $rh_components->{'postcode'} = $1;
623 }
624 }
625  
626 # remove things that might be empty
627 491 foreach my $c (keys %$rh_components) {
628 # catch empty values
629 3815 ▶ if (!defined($rh_components->{$c})) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $rh_components->{$c}) { } 0 3815 3815
elsif (not $rh_components->{$c} =~ /\w/) { } 1 3814 3815
elsif ($rh_components->{$c} =~ m[https?://]) { } 1 3813 3814
630 0 delete $rh_components->{$c};
631 }
632 # no chars
633 elsif ($rh_components->{$c} !~ m/\w/) {
634 1 delete $rh_components->{$c};
635 }
636 # catch values containing URLs
637 elsif ($rh_components->{$c} =~ m|https?://|) {
638 1 delete $rh_components->{$c};
639 }
640 }
641 491 return;
642 }
643  
644 sub _minimal_components {
645 488 ▶ my $self = shift;
Subroutine _minimal_components: called CC=5 SCAR=16.1
646 488 ▶ my $rh_components = shift || return;
Condition50%1/2
shift() || (return)
l!l
4880
MC/DC0%0/1
shift() || (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
647 488 my @required_components = qw(road postcode); #FIXME - should be in conf
648 488 my $missing = 0; # num required components that are missing
649  
650 488 my $minimal_threshold = 2;
651 488 foreach my $c (@required_components) {
652 976 ▶ $missing++ if (!defined($rh_components->{$c}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rh_components->{$c} 235 741 976
653 976 ▶ return 0 if ($missing == $minimal_threshold);
Branch: 1 branch
BranchTrueFalseTotal
if $missing == $minimal_threshold 57 919 976
654 }
655 431 return 1;
656 }
657  
658 7 my %valid_replacement_components = ('state' => 1,);
659  
660 # determines which country code to use
661 # may also override other configuration if we are dealing with
662 # a dependent territory
663 sub _determine_country_code {
664 491 ▶ my $self = shift;
Subroutine _determine_country_code: called CC=18 SCAR=29.6
665 491 ▶ my $rh_components = shift || return;
Condition50%1/2
shift() || (return)
l!l
4910
MC/DC0%0/1
shift() || (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
666  
667 # FIXME - validate it is a valid country
668 491 ▶ return if (!defined($rh_components->{country_code}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rh_components->{"country_code"} 4 487 491
669  
670 487 ▶ if (my $cc = lc($rh_components->{country_code})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cc = lc $rh_components->{"country_code"}) 487 0 487
671  
672 # is it two letters long?
673 487 ▶ return if (length($cc) != 2);
Branch: 1 branch
BranchTrueFalseTotal
if length $cc != 2 0 487 487
674 487 ▶ return 'GB' if ($cc eq 'uk');
Branch: 1 branch
BranchTrueFalseTotal
if $cc eq "uk" 0 487 487
675  
676 487 $cc = uc($cc);
677  
678 # check if the configuration tells us to use
679 # the configuration of another country
680 # used in cases of dependent territories like
681 # American Samoa (AS) and Puerto Rico (PR)
682 487 ▶ if ( defined($self->{templates}{$cc})
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"templates"}{$cc} and defined $self->{"templates"}{$cc}{"use_country"}) 46 441 487
Condition100%3/3
defined $self->{"templates"}{$cc} and defined $self->{"templates"}{$cc}{"use_country"}
!ll&&!rl&&r
243946
MC/DC100%2/2
defined $self->{"templates"}{$cc} and defined $self->{"templates"}{$cc}{"use_country"}
defined $self->{"templates"}{$cc} defined $self->{"templates"}{$cc}{"use_country"}
Truth table100%3/3
A and B
A= defined $self->{"templates"}{$cc}B= defined $self->{"templates"}{$cc}{"use_country"}
ABresult
0X0
100
111
683 && defined($self->{templates}{$cc}{use_country}))
684 {
685 46 my $old_cc = $cc;
686 46 $cc = $self->{templates}{$cc}{use_country};
687 46 ▶ if (defined($self->{templates}{$old_cc}{change_country})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"templates"}{$old_cc}{"change_country"}) 35 11 46
688  
689 35 my $new_country = $self->{templates}{$old_cc}{change_country};
690 35 ▶ if ($new_country =~ m/\$(\w*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_country =~ /\$(\w*)/) 2 33 35
691 2 my $component = $1;
692 2 ▶ if (defined($rh_components->{$component})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_components->{$component}) { } 2 0 2
693 2 $new_country =~ s/\$$component/$rh_components->{$component}/;
694 } else {
695 0 $new_country =~ s/\$$component//;
696 }
697 }
698 35 $rh_components->{country} = $new_country;
699 }
700 46 ▶ if (defined($self->{templates}{$old_cc}{add_component})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"templates"}{$old_cc}{"add_component"}) 10 36 46
701 10 my $tmp = $self->{templates}{$old_cc}{add_component};
702 10 my ($k, $v) = split(/=/, $tmp);
703 # check whitelist of valid replacement components
704 10 ▶ if (defined($valid_replacement_components{$k})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $valid_replacement_components{$k}) 9 1 10
705 9 $rh_components->{$k} = $v;
706 }
707 }
708 }
709  
710 487 ▶ if ($cc eq 'NL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cc eq "NL") 5 482 487
711 5 ▶ if (defined($rh_components->{state})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_components->{"state"}) 5 0 5
712 5 ▶ if ($rh_components->{state} eq 'Curaçao') {
Branch: 3 branches
BranchTrueFalseTotal
if ($rh_components->{'state'} eq "Cura\347ao") { } 1 4 5
elsif ($rh_components->{'state'} =~ /^sint maarten/i) { } 0 4 4
elsif ($rh_components->{'state'} =~ /^Aruba/i) { } 1 3 4
713 1 $cc = 'CW';
714 1 $rh_components->{country} = 'Curaçao';
715 } elsif ($rh_components->{state} =~ m/^sint maarten/i) {
716 0 $cc = 'SX';
717 0 $rh_components->{country} = 'Sint Maarten';
718 } elsif ($rh_components->{state} =~ m/^Aruba/i) {
719 1 $cc = 'AW';
720 1 $rh_components->{country} = 'Aruba';
721 }
722 }
723 }
724 487 return $cc;
725 }
726 0 return;
727 }
728  
729 # hacks for bad country data
730 sub _fix_country {
731 490 ▶ my $self = shift;
Subroutine _fix_country: called CC=5 SCAR=16.1
732 490 ▶ my $rh_c = shift || return;
Condition50%1/2
shift() || (return)
l!l
4900
MC/DC0%0/1
shift() || (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
733  
734 # is the country a number?
735 # if so, and there is a state, use state as country
736 490 ▶ if (defined($rh_c->{country}) && defined($rh_c->{state})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_c->{"country"} and defined $rh_c->{"state"}) 388 102 490
Condition100%3/3
defined $rh_c->{"country"} and defined $rh_c->{"state"}
!ll&&!rl&&r
894388
MC/DC100%2/2
defined $rh_c->{"country"} and defined $rh_c->{"state"}
defined $rh_c->{"country"} defined $rh_c->{"state"}
Truth table100%3/3
A and B
A= defined $rh_c->{"country"}B= defined $rh_c->{"state"}
ABresult
0X0
100
111
737 388 ▶ if (looks_like_number($rh_c->{country})){
Branch: 1 branch
BranchTrueFalseTotal
if (&looks_like_number($rh_c->{"country"})) 1 387 388
738 1 $rh_c->{country} = delete $rh_c->{state};
739 }
740 }
741 490 return;
742 }
743  
744 # sets and returns a state code
745 # note may also set other values in some odd edge cases
746 sub _add_state_code {
747 495 ▶ my $self = shift;
Subroutine _add_state_code: called CC=3 SCAR=11.0
748 495 ▶ my $rh_components = shift // return;
Condition50%1/2
shift() // (return)
l!l
4950
MC/DC0%0/1
shift() // (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
749 495 ▶ if (defined($rh_components->{state})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_components->{"state"}) 393 102 495
750 393 return $self->_add_code('state', $rh_components);
751 }
752 102 return;
753 }
754  
755 sub _add_county_code {
756 494 ▶ my $self = shift;
Subroutine _add_county_code: called CC=3 SCAR=11.0
757 494 ▶ my $rh_components = shift // return;
Condition50%1/2
shift() // (return)
l!l
4940
MC/DC0%0/1
shift() // (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
758 494 ▶ if (defined($rh_components->{county})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_components->{"county"}) 216 278 494
759 216 return $self->_add_code('county', $rh_components);
760 }
761 278 return;
762 }
763  
764 sub _add_code {
765 609 ▶ my $self = shift;
Subroutine _add_code: called CC=16 SCAR=28.8
766 609 ▶ my $keyname = shift // return;
Condition50%1/2
shift() // (return)
l!l
6090
MC/DC0%0/1
shift() // (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
767 609 my $rh_components = shift;
768 609 ▶ return if !$rh_components->{country_code}; # do we know country?
Branch: 1 branch
BranchTrueFalseTotal
unless $rh_components->{"country_code"} 4 605 609
769 605 ▶ return if !$rh_components->{$keyname}; # do we know state/county?
Branch: 1 branch
BranchTrueFalseTotal
unless $rh_components->{$keyname} 0 605 605
770  
771 605 my $code = $keyname . '_code';
772  
773 605 ▶ if (defined($rh_components->{$code})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_components->{$code}) 32 573 605
774 # do we already have code?
775 # we could have situation where code and long name are same
776 # so we want to corrent
777 32 ▶ return if ($rh_components->{$code} ne $rh_components->{$keyname});
Branch: 1 branch
BranchTrueFalseTotal
if $rh_components->{$code} ne $rh_components->{$keyname} 31 1 32
778 }
779  
780 # ensure country_code is uppercase as we use it as conf key
781 574 my $cc = uc($rh_components->{country_code});
782  
783 574 my $reverse_key = $code . 's_reverse';
784 574 my $name_key = $code . 's_name';
785  
786 574 ▶ if (my $rev = $self->{$reverse_key}{$cc}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rev = $self->{$reverse_key}{$cc}) 306 268 574
787 306 my $name = $rh_components->{$keyname};
788 306 my $uc_name = uc($name);
789  
790 306 ▶ if (my $found_code = $rev->{$uc_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $found_code = $rev->{$uc_name}) 204 102 306
791 # matched a name -> code
792 204 $rh_components->{$code} = $found_code;
793 # if input was a code (e.g. state => 'NC'), set keyname to full name
794 204 ▶ if ($uc_name eq $found_code) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uc_name eq $found_code) 6 198 204
795 6 my $full_name = $self->{$name_key}{$cc}{$found_code};
796 6 ▶ $rh_components->{$keyname} = $full_name if defined $full_name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $full_name 6 0 6
797 }
798 }
799  
800 # US-specific edge cases
801 306 ▶ if ($cc eq 'US' && $keyname eq 'state' && !defined($rh_components->{state_code})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cc eq "US" and $keyname eq "state" and not defined $rh_components->{"state_code"}) 2 304 306
Condition83%5/6
$cc eq "US" and $keyname eq "state" and not defined $rh_components->{"state_code"}
!ll&&!rl&&r
280242
$cc eq "US" and $keyname eq "state"
!ll&&!rl&&r
280026
MC/DC66%2/3
$cc eq "US" and $keyname eq "state" and not defined $rh_components->{"state_code"}
$cc eq "US" $keyname eq "state" not defined $rh_components->{"state_code"}
Truth table75%3/4
A and B and not(C)
A= $cc eq "US"B= $keyname eq "state"C= not defined $rh_components->{"state_code"}
ABCresult
0XX0
10X0
1100
1111
802 2 ▶ if ($rh_components->{state} =~ m/^united states/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh_components->{"state"} =~ /^united states/i) 0 2 2
803 0 my $state = $rh_components->{state};
804 0 $state =~ s/^United States/US/i;
805 0 ▶ if (my $fc = $rev->{uc($state)}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $fc = $$rev{uc $state}) 0 0 0
806 0 $rh_components->{state_code} = $fc;
807 }
808 }
809 2 ▶ if ($rh_components->{state} =~ m/^washington,? d\.?c\.?/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh_components->{"state"} =~ /^washington,? d\.?c\.?/i) 2 0 2
810 2 $rh_components->{state_code} = 'DC';
811 2 $rh_components->{state} = 'District of Columbia';
812 2 $rh_components->{city} = 'Washington';
813 }
814 }
815 }
816 574 return $rh_components->{$code};
817 }
818  
819 sub _apply_replacements {
820 163 ▶ my $self = shift;
Subroutine _apply_replacements: called CC=20 SCAR=32.3
821 163 my $rh_components = shift;
822 163 ▶ my $ra_rules = shift // return; # bail out if no rules
Condition50%1/2
shift() // (return)
l!l
1630
MC/DC0%0/1
shift() // (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
823  
824 163 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 163 163
825 0 say STDERR "in _apply_replacements";
826 0 say STDERR Dumper $ra_rules;
827 }
828  
829 # support legacy raw array-of-arrays format (used by tests)
830 163 ▶ if (ref($ra_rules) eq 'ARRAY' && @$ra_rules && ref($ra_rules->[0]) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ra_rules eq "ARRAY" and @$ra_rules and ref $ra_rules->[0] eq "ARRAY") 2 161 163
Condition83%5/6
ref $ra_rules eq "ARRAY" and @$ra_rules and ref $ra_rules->[0] eq "ARRAY"
!ll&&!rl&&r
11602
ref $ra_rules eq "ARRAY" and @$ra_rules
!ll&&!rl&&r
01162
MC/DC66%2/3
ref $ra_rules eq "ARRAY" and @$ra_rules and ref $ra_rules->[0] eq "ARRAY"
ref $ra_rules eq "ARRAY" @$ra_rules ref $ra_rules->[0] eq "ARRAY"
Truth table75%3/4
A and B and C
A= ref $ra_rules eq "ARRAY"B= @$ra_rulesC= ref $ra_rules->[0] eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
831 2 foreach my $component (keys %$rh_components) {
832 2 ▶ next if ($component eq 'country_code');
Branch: 1 branch
BranchTrueFalseTotal
if $component eq "country_code" 0 2 2
833 2 ▶ next if ($component eq 'house_number');
Branch: 1 branch
BranchTrueFalseTotal
if $component eq "house_number" 0 2 2
834 2 foreach my $ra_fromto (@$ra_rules) {
835 3 my $regexp;
836 3 ▶ if ($ra_fromto->[0] =~ m/^$component=/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ra_fromto->[0] =~ /^$component=/) { } 0 3 3
837 0 my $from = $ra_fromto->[0];
838 0 $from =~ s/^$component=//;
839 0 ▶ if ($rh_components->{$component} eq $from) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh_components->{$component} eq $from) { } 0 0 0
840 0 $rh_components->{$component} = $ra_fromto->[1];
841 } else {
842 0 $regexp = $from;
843 }
844 } else {
845 3 $regexp = $ra_fromto->[0];
846 }
847 3 ▶ if (defined($regexp)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $regexp) 3 0 3
848 try {
849 3 ▶ my $re = qr/$regexp/i;
Subroutine __ANON__: called CC=1 SCAR=0.0
850 2 $rh_components->{$component} =~ s/$re/$ra_fromto->[1]/;
851 } catch {
852 1 ▶ warn "invalid replacement: " . join(', ', @$ra_fromto);
Subroutine __ANON__: called CC=1 SCAR=0.0
853 3 };
854 }
855 }
856 }
857 2 return $rh_components;
858 }
859  
860 161 foreach my $component (keys %$rh_components) {
861 # some components dont need replacements
862 1362 ▶ next if ($component eq 'country_code');
Branch: 1 branch
BranchTrueFalseTotal
if $component eq "country_code" 160 1202 1362
863 1202 ▶ next if ($component eq 'house_number');
Branch: 1 branch
BranchTrueFalseTotal
if $component eq "house_number" 61 1141 1202
864 1141 foreach my $rule (@$ra_rules) {
865 7937 ▶ if (defined($rule->{component})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rule->{'component'}) { } 1990 5947 7937
866 # component-specific rule: only applies to matching component
867 1990 ▶ next if ($rule->{component} ne $component);
Branch: 1 branch
BranchTrueFalseTotal
if $rule->{"component"} ne $component 1793 197 1990
868 197 ▶ if ($rh_components->{$component} eq $rule->{exact_match}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh_components->{$component} eq $rule->{'exact_match'}) { } 4 193 197
869 4 $rh_components->{$component} = $rule->{replacement};
870 } else {
871 193 $rh_components->{$component} =~ s/$rule->{re}/$rule->{replacement}/;
872 }
873 } else {
874 5947 $rh_components->{$component} =~ s/$rule->{re}/$rule->{replacement}/;
875 }
876 }
877 }
878 161 return $rh_components;
879 }
880  
881 sub _abbreviate {
882 12 ▶ my $self = shift;
Subroutine _abbreviate: called CC=11 SCAR=24.0
883 12 ▶ my $rh_comp = shift // return;
Condition50%1/2
shift() // (return)
l!l
120
MC/DC0%0/1
shift() // (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
884  
885 # do we know the country?
886 12 ▶ if (!defined($rh_comp->{country_code})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rh_comp->{"country_code"}) 2 10 12
887 2 ▶ if ($show_warnings){
Branch: 1 branch
BranchTrueFalseTotal
if ($show_warnings) 1 1 2
888 1 my $error_msg = 'no country_code, unable to abbreviate';
889 1 ▶ if (defined($rh_comp->{country})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rh_comp->{"country"}) 1 0 1
890 1 $error_msg .= ' - country: ' . $rh_comp->{country};
891 }
892 1 warn $error_msg
893 }
894 2 return;
895 }
896  
897 # do we have abbreviations for this country?
898 10 my $cc = uc($rh_comp->{country_code});
899  
900 # 1. which languages?
901 10 ▶ if (defined($self->{country2lang}{$cc})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"country2lang"}{$cc}) 10 0 10
902  
903 10 my @langs = split(/,/, $self->{country2lang}{$cc});
904  
905 10 foreach my $lang (@langs) {
906 # do we have compiled abbrv for this lang?
907 14 ▶ if (defined($self->{compiled_abbreviations}{$lang})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'compiled_abbreviations'}{$lang}) { } 11 3 14
908 11 my $rh_compiled = $self->{compiled_abbreviations}{$lang};
909  
910 11 foreach my $comp_name (keys %$rh_compiled) {
911 16 ▶ next if (!defined($rh_comp->{$comp_name}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rh_comp->{$comp_name} 1 15 16
912 15 foreach my $rule (@{$rh_compiled->{$comp_name}}) {
913 111 $rh_comp->{$comp_name} =~ s/$rule->{re}/$1$rule->{short}/;
914 }
915 }
916 } else {
917 #warn "no abbreviations defined for lang $lang";
918 }
919 }
920 }
921 10 return $rh_comp;
922 }
923  
924 # " abc,,def , ghi " => 'abc, def, ghi'
925 sub _clean {
926 986 ▶ my $self = shift;
Subroutine _clean: called CC=9 SCAR=22.0
927 986 ▶ my $out = shift // return;
Condition100%2/2
shift() // (return)
l!l
9851
MC/DC100%1/1
shift() // (return)
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
928 985 ▶ if ($debug){
Branch: 1 branch
BranchTrueFalseTotal
if ($debug) 0 985 985
929 0 say STDERR "entering _clean \n$out";
930 }
931  
932 985 $out =~ s/\&#39\;/'/g;
933  
934 985 $out =~ s/[\},\s]+$//;
935 985 $out =~ s/^[,\s]+//;
936  
937 985 $out =~ s/^- //; # line starting with dash due to a parameter missing
938  
939 985 $out =~ s/,\s*,/, /g; # multiple commas to one
940 985 $out =~ s/\h+,\h+/, /g; # one horiz whitespace behind comma
941 985 $out =~ s/\h\h+/ /g; # multiple horiz whitespace to one
942 985 $out =~ s/\h\n/\n/g; # horiz whitespace, newline to newline
943 985 $out =~ s/\n,/\n/g; # newline comma to just newline
944 985 $out =~ s/,,+/,/g; # multiple commas to one
945 985 $out =~ s/,\n/\n/g; # comma newline to just newline
946 985 $out =~ s/\n\h+/\n/g; # newline plus space to newline
947 985 $out =~ s/\n\n+/\n/g; # multiple newline to one
948  
949 # final dedupe across and within lines
950 985 my @before_pieces = split(/\n/, $out);
951 985 my %seen_lines;
952 my @after_pieces;
953 985 foreach my $line (@before_pieces) {
954 3740 $line =~ s/^\h+//g;
955 3740 $line =~ s/\h+$//g;
956 3740 $seen_lines{$line}++;
957 3740 ▶ next if ($seen_lines{$line} > 1);
Branch: 1 branch
BranchTrueFalseTotal
if $seen_lines{$line} > 1 19 3721 3740
958 # now dedupe within the line
959 3721 my @before_words = split(/,/, $line);
960 3721 my %seen_words;
961 my @after_words;
962 3721 foreach my $w (@before_words) {
963 3944 $w =~ s/^\h+//g;
964 3944 $w =~ s/\h+$//g;
965 3944 ▶ if (lc($w) ne 'new york') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $w ne "new york") 3934 10 3944
966 3934 $seen_words{$w}++;
967 }
968 3944 ▶ next if ((defined($seen_words{$w})) && ($seen_words{$w} > 1));
Branch: 1 branch
BranchTrueFalseTotal
if defined $seen_words{$w} and $seen_words{$w} > 1 2 3942 3944
Condition100%3/3
defined $seen_words{$w} and $seen_words{$w} > 1
!ll&&!rl&&r
1039322
MC/DC100%2/2
defined $seen_words{$w} and $seen_words{$w} > 1
defined $seen_words{$w} $seen_words{$w} > 1
Truth table100%3/3
A and B
A= defined $seen_words{$w}B= $seen_words{$w} > 1
ABresult
0X0
100
111
969 3942 push(@after_words, $w);
970 }
971 3721 $line = join(', ', @after_words);
972 3721 push(@after_pieces, $line);
973 }
974 985 $out = join("\n", @after_pieces);
975  
976 985 $out =~ s/^\s+//; # remove leading whitespace
977 985 $out =~ s/\s+$//; # remove end whitespace
978  
979 985 $out .= "\n"; # add final newline
980 985 return $out; # we are done
981 }
982  
983 sub _render_template {
984 491 ▶ my $self = shift;
Subroutine _render_template: called CC=6 SCAR=21.0
985 491 my $thtemplate = shift;
986 491 my $components = shift;
987  
988 # Mustache calls it context
989 491 my $context = $components;
990 491 ▶ say STDERR 'context: ' . Dumper $context if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 491 491
991 491 my $output = $thtemplate->render($context);
992  
993 491 $output = $self->_evaluate_template_lamdas($output);
994  
995 491 ▶ say STDERR "in _render before _clean: $output" if ($debug);
Branch: 1 branch
BranchTrueFalseTotal
if $debug 0 491 491
996 491 $output = $self->_clean($output);
997  
998 # is it empty?
999 491 ▶ if (length($output) == 0){
Branch: 1 branch
BranchTrueFalseTotal
if (length $output == 0) 0 491 491
1000 # if yes and there is only one component then just use that one
1001 0 my @comps = keys %$components;
1002 0 ▶ if (scalar(@comps) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @comps == 1) 0 0 0
1003 0 foreach my $k (@comps) {
1004 0 $output = $components->{$k};
1005 }
1006 } # FIXME what if more than one?
1007 }
1008 491 return $output;
1009 }
1010  
1011 # Text::Hogan apparently caches lambdas when rendering templates. In the past
1012 # we needed our lambda 'first', example
1013 # {{#first}} {{{city}}} || {{{town}}} {{/first}}
1014 # to evaluate the components. Whenever the lambda was called with different
1015 # component values it consumed memory. Now replace with a simpler implementation
1016 #
1017 sub _replace_template_lambdas {
1018 491 ▶ my $self = shift;
Subroutine _replace_template_lambdas: called CC=1 SCAR=0.0
1019 491 my $template_text = shift;
1020 491 $template_text =~ s!\Q{{#first}}\E(.+?)\Q{{/first}}\E!FIRSTSTART${1}FIRSTEND!g;
1021 491 return $template_text;
1022 }
1023  
1024 # We only use a lambda named 'first'
1025 sub _evaluate_template_lamdas {
1026 491 ▶ my $self = shift;
Subroutine _evaluate_template_lamdas: called CC=1 SCAR=0.0
1027 491 my $text = shift;
1028 491 $text =~ s!FIRSTSTART\s*(.+?)\s*FIRSTEND!_select_first($1)!seg;
1029 491 return $text;
1030 }
1031  
1032 # '|| val1 || || val3' => 'val1'
1033 sub _select_first {
1034 924 ▶ my $text = shift;
Subroutine _select_first: called CC=2 SCAR=6.9
1035 924 my @a_parts = grep { length($_) } split(/\s*\|\|\s*/, $text);
1036 924 ▶ return scalar(@a_parts) ? $a_parts[0] : '';
Branch: 1 branch
BranchTrueFalseTotal
scalar @a_parts ? : 799 125 924
1037 }
1038  
1039 7 my %small_district = (
1040 'BR' => 1,
1041 'CR' => 1,
1042 'ES' => 1,
1043 'NI' => 1,
1044 'PY' => 1,
1045 'RO' => 1,
1046 'TG' => 1,
1047 'TM' => 1,
1048 'XK' => 1,
1049 );
1050  
1051 # correct the alias for "district"
1052 # in OSM some countries use district to mean "city_district"
1053 # others to mean "state_district"
1054 sub _set_district_alias {
1055 486 ▶ my $self = shift;
Subroutine _set_district_alias: called CC=4 SCAR=13.9
1056 486 ▶ my $cc = shift // return;
Condition50%1/2
shift() // (return)
l!l
4860
MC/DC0%0/1
shift() // (return)
shift()
Truth table50%1/2
A
A= shift()
Aresult
11
00
1057  
1058 486 my $ucc = uc($cc);
1059  
1060 # this may get called repeatedly
1061 # no need to do the work again
1062 486 ▶ return if (defined($self->{set_district_alias}{$ucc}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"set_district_alias"}{$ucc} 252 234 486
1063  
1064 # note that we are here so don't do this work again
1065 234 $self->{set_district_alias}{$ucc} = 1;
1066  
1067 234 my $oldalias;
1068 234 ▶ if (defined($small_district{$ucc})){
Branch: 1 branch
BranchTrueFalseTotal
if (defined $small_district{$ucc}) { } 11 223 234
1069 11 $self->{component2type}{district} = 'neighbourhood';
1070 11 $oldalias = 'state_district';
1071  
1072 # add to the neighbourhood alias list
1073 # though of course we are just sticking it at the end
1074 11 push(@{$self->{component_aliases}{'neighbourhood'}}, 'district');
1075  
1076 } else {
1077 # set 'district' to be type 'state_district'
1078 223 $self->{component2type}{district} = 'state_district';
1079 223 $oldalias = 'neighbourhood';
1080  
1081 # add to the state_district alias list
1082 223 push(@{$self->{component_aliases}{'state_district'}}, 'district');
1083 }
1084  
1085 # remove from the old alias list
1086 3075 my @temp = grep { $_ ne 'district' }
1087 234 @{$self->{component_aliases}{$oldalias}};
1088
1089 234 $self->{component_aliases}{$oldalias} = \@temp;
1090 234 return;
1091 }
1092  
1093  
1094 # returns []
1095 sub _find_unknown_components {
1096 488 ▶ my $self = shift;
Subroutine _find_unknown_components: called CC=1 SCAR=0.0
1097 488 my $rh_comp = shift;
1098  
1099 488 my @a_unknown = grep { !exists($self->{h_known}->{$_}) } keys %$rh_comp;
1100 488 return \@a_unknown;
1101 }
1102  
1103  
1104 7 1;
1105  
1106 __END__
1107  
1108 =pod
1109  
1110 =encoding UTF-8
1111  
1112 =head1 NAME
1113  
1114 Geo::Address::Formatter - take structured address data and format it according to the various global/country rules
1115  
1116 =head1 VERSION
1117  
1118 version 1.9993
1119  
1120 =head1 SYNOPSIS
1121  
1122 #
1123 # get the templates (or use your own)
1124 # git clone git@github.com:OpenCageData/address-formatting.git
1125 #
1126 my $GAF = Geo::Address::Formatter->new( conf_path => '/path/to/templates' );
1127  
1128 my $components = { ... }
1129 my $text = $GAF->format_address($components, { country => 'FR' } );
1130 my $rh_final_components = $GAF->final_components();
1131 #
1132 # or if we want shorter output
1133 #
1134 my $short_text = $GAF->format_address($components, { country => 'FR', abbreviate => 1, });
1135  
1136 =head2 new
1137  
1138 my $GAF = Geo::Address::Formatter->new( conf_path => '/path/to/templates' );
1139  
1140 Returns new object. The I<conf_path> is required.
1141  
1142 Optional parameters are:
1143  
1144 =over
1145  
1146 =item * I<debug>
1147  
1148 Prints tons of debugging info for use in development.
1149  
1150 =item * I<no_warnings>
1151  
1152 Turns off a few warnings if configuration is not optimal.
1153  
1154 =item * I<only_address>
1155  
1156 Formatted output will only contain known address components (will not
1157 include POI names). Can be overridden per-call via the I<only_address>
1158 option to L</format_address>.
1159  
1160 =back
1161  
1162 =head2 instance
1163  
1164 my $GAF = Geo::Address::Formatter->instance( conf_path => '/path/to/templates' );
1165  
1166 Returns new instance (potentially re-used) The I<conf_path> is required.
1167  
1168 Optional parameters are as in the B<new> method.
1169  
1170 =head2 final_components
1171  
1172 my $rh_components = $GAF->final_components();
1173  
1174 Returns a reference to a hash of the final components that were set during
1175 the most recent call to B<format_address>. Returns C<undef> if called
1176 before B<format_address> has been called. Warns in that case unless
1177 I<no_warnings> was set at object creation.
1178  
1179 =head2 format_address
1180  
1181 my $text = $GAF->format_address(\%components, \%options );
1182  
1183 Given structured address components (hashref) and options (hashref) returns a
1184 formatted address as a multiline string with a trailing newline.
1185  
1186 Possible options are:
1187  
1188 =over
1189  
1190 =item * I<abbreviate>
1191  
1192 If true, common abbreviations are applied to the resulting output.
1193  
1194 =item * I<address_template>
1195  
1196 A Mustache-format template to be used instead of the template defined in
1197 the configuration.
1198  
1199 =item * I<country>
1200  
1201 An uppercase ISO 3166-1 alpha-2 code, e.g. C<'GB'> for Great Britain,
1202 C<'DE'> for Germany, etc. If omitted the country is determined from
1203 the address components.
1204  
1205 =item * I<only_address>
1206  
1207 Same as the I<only_address> constructor option but applied per-call.
1208  
1209 =back
1210  
1211 =head1 DESCRIPTION
1212  
1213 You have a structured postal address (hash) and need to convert it into a
1214 readable address based on the format of the address country.
1215  
1216 For example, you have:
1217  
1218 {
1219 house_number => 12,
1220 street => 'Avenue Road',
1221 postcode => 45678,
1222 city => 'Deville'
1223 }
1224  
1225 you need:
1226  
1227 Great Britain: 12 Avenue Road, Deville 45678
1228 France: 12 Avenue Road, 45678 Deville
1229 Germany: Avenue Road 12, 45678 Deville
1230 Latvia: Avenue Road 12, Deville, 45678
1231  
1232 It gets more complicated with 200+ countries and territories and dozens more
1233 address components to consider.
1234  
1235 This module comes with a minimal configuration to run tests. Instead of
1236 developing your own configuration please use (and contribute to)
1237 those in https://github.com/OpenCageData/address-formatting
1238 which includes test cases.
1239  
1240 Together we can address the world!
1241  
1242 =head1 SEE ALSO
1243  
1244 L<https://github.com/OpenCageData/address-formatting> - the address
1245 formatting template configuration used by this module.
1246  
1247 L<https://opencagedata.com> - OpenCage geocoder.
1248  
1249 =head1 AUTHOR
1250  
1251 Ed Freyfogle
1252  
1253 =head1 COPYRIGHT AND LICENSE
1254  
1255 This software is copyright (c) 2026 by Opencage GmbH.
1256  
1257 This is free software; you can redistribute it and/or modify it under
1258 the same terms as the Perl 5 programming language system itself.
1259  
1260 =cut
« blib/lib/Geo/Address/Formatter.pm ↑ Summary