blib/lib/Geo/Coder/List.pm

filter: Statementstmt 97.8% 451 / 461 Branchbran 90.4% 264 / 292 Conditioncond 72.6% 85 / 117 MC/DCmcdc 47.3% 35 / 74 Subroutinesub 96.1% 25 / 26 Podpod 100% 7 / 7 totaltotal 88.7% 867 / 977 CC 197 SCAR 40.3
CC
197
Cov
92%
geocode
101.0
_cache
38.0
reverse_geocode
29.3
CRAP 56.5
↑ Summary
1 package Geo::Coder::List;
2  
3 # Geo::Coder::List - Aggregate and chain multiple geocoding backends
4  
5 24 ▶use 5.10.1;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 24 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 24 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 24 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 24 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 24 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 24 ▶use HTML::Entities;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 24 ▶use Object::Configure 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 24 ▶use Params::Get 0.04;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 24 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 24 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 24 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 =head1 NAME
21  
22 Geo::Coder::List - Call many Geo-Coders
23  
24 =head1 VERSION
25  
26 Version 0.38
27  
28 =cut
29  
30 24 our $VERSION = '0.38';
31  
32 # ── Module-level constants (not user-configurable) ────────────────────────────
33  
34 # Default verbosity: 0 = silent, 1 = basic trace, 2 = full Data::Dumper dumps
35 24 ▶use constant DEBUG_DEFAULT => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37 # Internal sentinel class: a cached not-found result stored in L1.
38 # Using a blessed ref lets _cache() distinguish "never looked up" from
39 # "looked up and found nothing" without requiring a special undef convention.
40 24 ▶use constant _NOT_FOUND_CLASS => __PACKAGE__ . '::_NotFound';
Subroutine BEGIN: called CC=1 SCAR=0.0
41  
42 # The singleton value stored in L1 when a location is confirmed missing
43 24 my $NOT_FOUND_SENTINEL = bless {}, _NOT_FOUND_CLASS;
44  
45 # String placed in the 'geocoder' field of a result served from cache
46 24 Readonly::Scalar my $CACHE_SOURCE => 'cache';
47  
48 # String used as the 'result' value in log entries for a geocoder miss
49 24 Readonly::Scalar my $RESULT_NONE => 'not found';
50  
51 # ── Configurable defaults ─────────────────────────────────────────────────────
52 #
53 # Any key here can be overridden at run time via an environment variable named
54 # GEO__CODER__LIST__<key>, which Object::Configure reads automatically in new().
55 # Example:
56 # export GEO__CODER__LIST__cache_hit_duration='7 days'
57  
58 24 my %config = (
59 debug => DEBUG_DEFAULT,
60 # How long a confirmed location stays in the L2 cache
61 cache_hit_duration => '1 month',
62 # How long a transient/partial failure is cached (retry tomorrow)
63 cache_part_duration => '1 day',
64 # How long a definite not-found is cached (place probably does not exist)
65 cache_miss_duration => '1 week',
66 );
67  
68 # =============================================================================
69 # PUBLIC API
70 # =============================================================================
71  
72 =head1 SYNOPSIS
73  
74 L<Geo::Coder::All> and L<Geo::Coder::Many> are great modules but neither
75 quite does what I want.
76  
77 C<Geo::Coder::List> aggregates multiple geocoding services into a single,
78 unified interface. It chains and prioritizes backends based on regex routing
79 and per-geocoder query limits, caches results at two levels (L1 in-memory
80 always; optional L2 via CHI or a plain HASH), and normalizes every provider's
81 idiosyncratic response into the common structure expected by
82 L<HTML::GoogleMaps::V3> and L<HTML::OSM>:
83  
84 $result->{geometry}{location}{lat} # canonical latitude
85 $result->{geometry}{location}{lng} # canonical longitude
86 $result->{geocoder} # source object (or 'cache')
87  
88 use Geo::Coder::List;
89 use Geo::Coder::OSM;
90 use Geo::Coder::CA;
91  
92 my $list = Geo::Coder::List->new()
93 ->push({ regex => qr/(Canada|USA)$/, geocoder => Geo::Coder::CA->new() })
94 ->push(Geo::Coder::OSM->new());
95  
96 my $loc = $list->geocode('10 Downing St, London, UK');
97 printf "lat=%.4f lng=%.4f\n",
98 $loc->{geometry}{location}{lat},
99 $loc->{geometry}{location}{lng};
100  
101 =head1 SUBROUTINES/METHODS
102  
103 =head2 new
104  
105 Creates a new C<Geo::Coder::List> object. When called on an existing object
106 it returns a clone of that object merged with the supplied arguments.
107  
108 The constructor reads configuration from environment variables via
109 L<Object::Configure>; for example, setting
110 C<GEO__CODER__LIST__carp_on_warn=1> causes warnings to use L<Carp>.
111  
112 use Geo::Coder::List;
113 use CHI;
114  
115 # With an optional L2 cache (any CHI driver works)
116 my $geocoder = Geo::Coder::List->new(
117 cache => CHI->new(driver => 'Memory', global => 1),
118 debug => 0,
119 );
120  
121 # Clone an existing object with a higher debug level
122 my $verbose = $geocoder->new(debug => 2);
123  
124 =head3 API SPECIFICATION
125  
126 =head4 INPUT
127  
128 # Params::Validate::Strict schema
129 {
130 cache => {
131 type => [ 'hashref', 'object' ], # OBJECT must implement get($key) and set($key, $value, $ttl)
132 optional => 1,
133 },
134 debug => {
135 type => 'boolean',
136 optional => 1,
137 default => 0,
138 },
139 # Any additional key is forwarded to Object::Configure
140 }
141  
142 =head4 OUTPUT
143  
144 # Return::Set schema
145 OBJECT blessed into Geo::Coder::List
146  
147 =cut
148  
149 sub new
150 333 ▶{
Subroutine new: called CC=7 SCAR=19.5
Pod documented
151 333 my $class = shift;
152 333 ▶ my $params = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
116217
MC/DC100%1/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
153  
154 # Handle the rare Geo::Coder::List::new() (function-style) invocation
155 333 ▶ if(!defined($class)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $class) { } 8 325 333
elsif (builtin::blessed($class)) { } 6 319 325
156 8 ▶ if(scalar keys %{$params} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %{$params;} > 0) 4 4 8
157 # Using ::new() with arguments is not supported
158 4 carp(__PACKAGE__, ' use ->new() not ::new() to instantiate');
159 4 return;
160 }
161 # FIXME: cloning does not work when called as ::new() with arguments
162 4 $class = __PACKAGE__;
163 } elsif(blessed($class)) {
164 # Shallow clone merged with new params; log is always fresh so the
165 # clone starts with an empty event history independent of the original
166 6 return bless { %{$class}, %{$params}, log => [] }, ref($class);
167 }
168  
169 # Let Object::Configure overlay defaults from environment / config files
170 323 $params = Object::Configure::configure($class, $params);
171  
172 # Fill in any %config defaults the caller did not explicitly supply
173 323 for my $key (keys %config) {
174 1292 ▶ $params->{$key} //= $config{$key};
Condition100%3/3
$params->{$key} //= $config{$key}
l!l&&r!l&&!r
13969310
MC/DC100%2/2
$params->{$key} //= $config{$key}
$params->{$key} $config{$key}
Truth table100%3/3
A //= B
A= $params->{$key}B= $config{$key}
ABresult
1X1
011
000
175 }
176  
177 # Bless and return; params override scalar defaults but locations/log
178 # are always initialised fresh so callers cannot inject stale state
179 return bless {
180 debug => DEBUG_DEFAULT,
181 geocoders => [],
182 323 %{$params},
183 locations => {},
184 log => [],
185 }, $class;
186 }
187  
188 # =============================================================================
189  
190 =head2 push
191  
192 Appends a geocoder to the chain. Geocoders are tried in the order they
193 were pushed. Returns C<$self> so calls can be chained.
194  
195 A plain geocoder object is tried for every location. A hashref with
196 C<regex>, C<geocoder>, and optional C<limit> keys restricts the geocoder to
197 locations matching the regex and caps total queries at C<limit>.
198  
199 my $list = Geo::Coder::List->new()
200 ->push({ regex => qr/USA$/, geocoder => Geo::Coder::CA->new(), limit => 100 })
201 ->push(Geo::Coder::OSM->new());
202  
203 =head3 API SPECIFICATION
204  
205 =head4 INPUT
206  
207 # Params::Validate::Strict schema
208 {
209 geocoder => {
210 type => OBJECT | HASHREF,
211 required => 1,
212 # HASHREF must contain: geocoder => OBJECT
213 # HASHREF may contain: regex => Regexp
214 # limit => SCALAR (positive integer)
215 },
216 }
217  
218 =head4 OUTPUT
219  
220 # Return::Set schema
221 OBJECT blessed into Geo::Coder::List # $self, for chaining
222  
223 =cut
224  
225 sub push
226 260 ▶{
Subroutine push: called CC=2 SCAR=6.9
Pod documented
227 # Deliberately NOT using Params::Get here: passing the hashref through it
228 # would stringify the compiled qr// object, destroying the regex.
229 260 my ($self, $geocoder) = @_;
230  
231 # A geocoder argument is mandatory
232 260 ▶ croak(__PACKAGE__, '::push: Usage: ($geocoder)') unless defined($geocoder);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $geocoder 4 256 260
233  
234 # Append to the ordered chain and return $self for chaining
235 256 CORE::push @{$self->{geocoders}}, $geocoder;
236  
237 256 return $self;
238 }
239  
240 # =============================================================================
241  
242 =head2 geocode
243  
244 Resolves a location string to geographic coordinates by trying each geocoder
245 in turn. The first successful result is returned and cached.
246  
247 In scalar context returns a single hashref (or C<undef> on failure).
248 In list context returns all results from the winning geocoder.
249  
250 The C<geocoder> field of the returned hashref holds the geocoder object that
251 supplied the result; it is set to the string C<'cache'> when the result was
252 served from cache.
253  
254 See L<Geo::Coder::GooglePlaces::V3> for the canonical result structure.
255  
256 my $result = $list->geocode(location => 'Paris, France');
257 if($result) {
258 printf "lat=%.4f lng=%.4f via %s\n",
259 $result->{geometry}{location}{lat},
260 $result->{geometry}{location}{lng},
261 ref($result->{geocoder}) || $result->{geocoder};
262 }
263  
264 # List context returns all candidates from the winning geocoder
265 my @results = $list->geocode('London, UK');
266  
267 =head3 API SPECIFICATION
268  
269 =head4 INPUT
270  
271 # Params::Validate::Strict schema
272 {
273 location => {
274 type => SCALAR,
275 required => 1,
276 # Must contain at least one non-digit character
277 },
278 }
279  
280 =head4 OUTPUT
281  
282 # Return::Set schema (scalar context)
283 HASHREF | undef
284 {
285 geometry => { location => { lat => Num, lng => Num } },
286 geocoder => OBJECT | 'cache',
287 lat => Num, # convenience alias
288 lng => Num, # convenience alias
289 lon => Num, # compatibility alias for lng
290 debug => Int, # source line of the normalisation branch taken
291 # ... provider-specific keys are preserved
292 }
293  
294 # Return::Set schema (list context)
295 ARRAY of the above HASHREFs
296  
297 =cut
298  
299 202 ▶sub geocode {
Subroutine geocode: called CC=97 SCAR=46.2
Pod documented
300 202 my $self = shift;
301  
302 # Params::Get enforces 'location'; calling geocode() with no args causes
303 # get_params itself to croak with "Usage:" matching t/carp.t expectations
304 202 my $params = Params::Get::get_params('location', @_);
305 200 ▶ if(!defined($params)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $params) 0 200 200
306 0 $self->_error(__PACKAGE__, ' usage: geocode(location => $location)');
307 0 return;
308 }
309  
310 200 my $location = $params->{'location'};
311  
312 # Reject empty or whitespace-only location strings
313 200 ▶ if((!defined($location)) || (length($location) == 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $location or length $location == 0) 6 194 200
Condition100%3/3
not defined $location or length $location == 0
l!l&&r!l&&!r
33194
MC/DC100%2/2
not defined $location or length $location == 0
not defined $location length $location == 0
Truth table100%3/3
not(A) or B
A= not defined $locationB= length $location == 0
ABresult
1X1
011
000
314 6 $self->_warn(__PACKAGE__, ' usage: geocode(location => $location)');
315 6 return;
316 }
317  
318 # A purely numeric string is almost certainly an error (e.g. a bare postcode)
319 194 ▶ if($params->{'location'} !~ /\D/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"location"} =~ /\D/) 4 190 194
320 4 $self->_error('Usage: ', __PACKAGE__, ': invalid input to geocode(), ', $params->{location});
321 }
322  
323 # Collapse runs of whitespace and expand any HTML entities
324 190 $location =~ s/\s\s+/ /g;
325 190 $location = decode_entities($location);
326 # Propagate the cleaned-up string so geocoders also receive the decoded form
327 190 $params->{'location'} = $location;
328  
329 190 ▶ print "location: $location\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 4 186 190
330  
331 # Capture the caller's line number once for all log entries in this call
332 190 my @call_details = caller(0);
333  
334 # ── L1 / L2 cache lookup ──────────────────────────────────────────────
335  
336 # _cache() returns undef for both "not in cache" and "cached not-found";
337 # the not-found sentinel is handled internally so callers see undef either way
338 190 my $cached = $self->_cache($location);
339  
340 190 ▶ if(defined $cached) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cached) 28 162 190
341 # A defined value means we have a genuine cached positive result
342 28 ▶ my @rc = ref($cached) eq 'ARRAY' ? @{$cached} : ($cached);
Branch: 1 branch
BranchTrueFalseTotal
ref $cached eq 'ARRAY' ? : 5 23 28
343  
344 # Mark every element as coming from cache. Shallow-copy HASH results
345 # first so that neither the L1 cache entry nor any caller-held reference
346 # to the same hashref is mutated in place.
347 28 for my $r (@rc) {
348 28 ▶ next unless ref($r);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $r 0 28 28
349 28 ▶ $r = { %{$r} } if ref($r) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $r eq "HASH" 26 2 28
350 28 $r->{'geocoder'} = $CACHE_SOURCE;
351 }
352  
353 # Scalar context: return the first (and usually only) element
354 28 ▶ if(!wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (wantarray) 22 6 28
355 22 my $rc = $rc[0];
356 22 CORE::push @{$self->{'log'}}, {
357 line => $call_details[2],
358 location => $location,
359 timetaken => 0,
360 geocoder => $CACHE_SOURCE,
361 wantarray => 0,
362 result => $rc,
363 };
364 22 ▶ print __PACKAGE__, ': ', __LINE__, ": cached\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 22 22
365 22 return $rc;
366 }
367  
368 # List context: return all cached candidates
369 6 CORE::push @{$self->{'log'}}, {
370 line => $call_details[2],
371 location => $location,
372 timetaken => 0,
373 geocoder => $CACHE_SOURCE,
374 wantarray => 1,
375 result => \@rc,
376 };
377 6 ▶ print __PACKAGE__, ': ', __LINE__, ": cached\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 6 6
378  
379 # Determine if every element is empty; if so return nothing
380 6 my $allempty = 1;
381 6 for my $r (@rc) {
382 6 ▶ if(ref($r) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $r eq 'HASH') { } 5 1 6
elsif (ref $r eq 'Geo::Location::Point') { } 1 0 1
383 5 ▶ $allempty = 0 if defined $r->{geometry}{location}{lat};
Branch: 1 branch
BranchTrueFalseTotal
if defined $r->{"geometry"}{"location"}{"lat"} 3 2 5
384 } elsif(ref($r) eq 'Geo::Location::Point') {
385 1 $allempty = 0;
386 }
387 }
388 6 ▶ return if $allempty;
Branch: 1 branch
BranchTrueFalseTotal
if $allempty 2 4 6
389 4 return @rc;
390 }
391  
392 # Also check if this location is cached as a definite not-found in L1,
393 # without going through _cache() (which masks the sentinel as undef)
394 162 ▶ if(exists $self->{'locations'}{$location}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{"locations"}{$location}) 5 157 162
395 5 my $stored = $self->{'locations'}{$location};
396 5 ▶ if(ref($stored) && ref($stored) eq _NOT_FOUND_CLASS) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $stored and ref $stored eq "Geo::Coder::List::_NotFound") 5 0 5
Condition33%1/3
ref $stored and ref $stored eq "Geo::Coder::List::_NotFound"
!ll&&!rl&&r
005
MC/DC0%0/2
ref $stored and ref $stored eq "Geo::Coder::List::_NotFound"
ref $stored ref $stored eq "Geo::Coder::List::_NotFound"
Truth table33%1/3
A and B
A= ref $storedB= ref $stored eq "Geo::Coder::List::_NotFound"
ABresult
0X0
100
111
397 5 ▶ print "No matches (cached)\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 5 5
398 5 ▶ return wantarray ? () : undef;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 4 5
399 }
400 }
401  
402 # ── Try each geocoder in turn ─────────────────────────────────────────
403  
404 157 ENCODER: foreach my $g (@{$self->{geocoders}}) {
405 164 my $geocoder = $g;
406  
407 # Unpack a hashref entry and apply regex / limit guards
408 164 ▶ if(ref($geocoder) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq "HASH") 14 150 164
409 # Decrement and check the per-geocoder query limit
410 14 ▶ if(exists($geocoder->{'limit'}) && defined(my $limit = $geocoder->{'limit'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})) 10 4 14
Condition66%2/3
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
!ll&&!rl&&r
4010
MC/DC50%1/2
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
exists $geocoder->{"limit"} defined(my $limit = $geocoder->{"limit"})
Truth table66%2/3
A and B
A= exists $geocoder->{"limit"}B= defined(my $limit = $geocoder->{"limit"})
ABresult
0X0
100
111
411 10 ▶ print "limit: $limit\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 10 10
412 10 ▶ if($limit <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit <= 0) 6 4 10
413 6 next;
414 }
415 4 $geocoder->{'limit'}--;
416 }
417  
418 # Skip this entry if the location does not match its regex
419 8 ▶ if(my $regex = $geocoder->{'regex'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $regex = $geocoder->{"regex"}) 4 4 8
420 print 'consider ', ref($geocoder->{geocoder}), ": $regex\n"
421 4 ▶ if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 4 4
422 4 ▶ if($location !~ $regex) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($location =~ /$regex/) 3 1 4
423 3 next;
424 }
425 }
426  
427 # Unwrap the actual geocoder object from the hashref
428 5 $geocoder = $g->{'geocoder'};
429 }
430  
431 # Start timing before the network call
432 155 my @rc;
433 155 my $timetaken = Time::HiRes::time();
434  
435 155 eval {
436 # Geo::GeoNames uses a positional argument, not a hash
437 155 ▶ print 'trying ', ref($geocoder), "\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 4 151 155
438 155 ▶ if(ref($geocoder) eq 'Geo::GeoNames') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq 'Geo::GeoNames') { } 2 153 155
439 print 'username => ', $geocoder->username(), "\n"
440 2 ▶ if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 2 2
441 2 ▶ die 'lost username' if(!defined($geocoder->username()));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $geocoder->username 1 1 2
442 1 @rc = $geocoder->geocode($location);
443 } else {
444 153 @rc = $geocoder->geocode(%{$params});
445 }
446 };
447  
448 155 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 9 146 155
449 # Log the failure and move on; do not abort the whole chain
450 9 my $log = {
451 line => $call_details[2],
452 location => $location,
453 geocoder => ref($geocoder),
454 timetaken => Time::HiRes::time() - $timetaken,
455 wantarray => wantarray,
456 error => $@,
457 };
458 9 CORE::push @{$self->{'log'}}, $log;
459 9 $self->_warn(ref($geocoder), " '$location': $@");
460 9 next ENCODER;
461 }
462  
463 146 $timetaken = Time::HiRes::time() - $timetaken;
464  
465 # Geo::Coder::US::Census sometimes returns a truthy but empty result
466 146 ▶ if((ref($geocoder) eq 'Geo::Coder::US::Census') &&
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq "Geo::Coder::US::Census" and not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}) 2 144 146
Condition66%2/3
ref $geocoder eq "Geo::Coder::US::Census" and not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
!ll&&!rl&&r
14402
MC/DC50%1/2
ref $geocoder eq "Geo::Coder::US::Census" and not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
ref $geocoder eq "Geo::Coder::US::Census" not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
Truth table66%2/3
A and not(B)
A= ref $geocoder eq "Geo::Coder::US::Census"B= not defined $rc[0]{"result"}{"addressMatches"}[0]{"coordinates"}{"y"}
ABresult
0X0
100
111
467 !(defined($rc[0]->{result}{addressMatches}[0]->{coordinates}{y}))) {
468 2 my $log = {
469 line => $call_details[2],
470 location => $location,
471 timetaken => $timetaken,
472 geocoder => ref($geocoder),
473 wantarray => wantarray,
474 result => $RESULT_NONE,
475 };
476 2 CORE::push @{$self->{'log'}}, $log;
477 2 next ENCODER;
478 }
479  
480 # Reject empty result sets and trivially empty hashes / arrays
481 144 ▶ if((scalar(@rc) == 0) ||
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @rc == 0 or ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0 or 0) 22 122 144
Condition100%8/8
scalar @rc == 0 or ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0 or 0
l!l
22122
scalar @rc == 0 or ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0
l!l&&r!l&&!r
211122
ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0
!ll&&!rl&&r
131091
MC/DC100%3/3
scalar @rc == 0 or ref $rc[0] eq "HASH" and scalar keys %{$rc[0];} == 0 or 0
scalar @rc == 0 ref $rc[0] eq "HASH" scalar keys %{$rc[0];} == 0
Truth table100%4/4
A or B and C
A= scalar @rc == 0B= ref $rc[0] eq "HASH"C= scalar keys %{$rc[0];} == 0
ABCresult
1XX1
0111
00X0
0100
482 110 ((ref($rc[0]) eq 'HASH') && (scalar(keys %{$rc[0]}) == 0)) ||
483 # UNREACHABLE: if $rc[0] is an ARRAY ref, $rc[0][0] may be undef,
484 # which causes keys(%{undef}) to die under strict refs. No known
485 # geocoder returns an ARRAY-of-ARRAYs with an empty-hash sub-element.
486 # A safe rewrite would guard with: ref($rc[0][0]) eq 'HASH' first.
487 # ((ref($rc[0]) eq 'ARRAY') && (scalar(keys %{$rc[0][0]}) == 0)) ||
488 0) {
489 22 my $log = {
490 line => $call_details[2],
491 location => $location,
492 timetaken => $timetaken,
493 geocoder => ref($geocoder),
494 wantarray => wantarray,
495 result => $RESULT_NONE,
496 };
497 22 CORE::push @{$self->{'log'}}, $log;
498 22 next ENCODER;
499 }
500  
501 # ── Normalise each candidate result ──────────────────────────────
502  
503 # Track which element was successfully normalised so we return it,
504 # not blindly return $rc[0] when a later element was the good one
505 122 my $good_result;
506  
507 122 POSSIBLE_LOCATION: foreach my $l (@rc) {
508 # Geo::GeoNames wraps each result in a one-element array
509 122 ▶ if(ref($l) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $l eq "ARRAY") 2 120 122
510 # FIXME: only the first element of the sub-array is considered
511 2 $l = $l->[0];
512 }
513  
514 # Skip undefined or empty-string candidates
515 122 ▶ if((!defined($l)) || ($l eq '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $l or $l eq "") 5 117 122
Condition100%3/3
not defined $l or $l eq ""
l!l&&r!l&&!r
32117
MC/DC100%2/2
not defined $l or $l eq ""
not defined $l $l eq ""
Truth table100%3/3
not(A) or B
A= not defined $lB= $l eq ""
ABresult
1X1
011
000
516 5 my $log = {
517 line => $call_details[2],
518 location => $location,
519 timetaken => $timetaken,
520 geocoder => ref($geocoder),
521 wantarray => wantarray,
522 result => $RESULT_NONE,
523 };
524 5 CORE::push @{$self->{'log'}}, $log;
525 5 next ENCODER;
526 }
527  
528 # Skip bare scalars (e.g. integer 0, plain strings) that are
529 # not references; they cannot be hash-dereferenced below
530 117 ▶ next unless ref($l);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $l 3 114 117
531  
532 # Stamp the source geocoder on the result before normalisation
533 114 $l->{'geocoder'} = ref($geocoder);
534  
535 print ref($geocoder), ': ',
536 114 ▶ Data::Dumper->new([\$l])->Dump() if($self->{'debug'} >= 2);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} >= 2 2 112 114
537  
538 # Geo::Location::Point objects carry their own accessors;
539 # upgrade the geocoder field and populate the canonical geometry
540 # structure so callers can rely on geometry.location.{lat,lng}
541 114 ▶ if(ref($l) eq 'Geo::Location::Point') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $l eq "Geo::Location::Point") 4 110 114
542 4 $l->{'geocoder'} = $geocoder;
543  
544 # Populate canonical geometry structure from the GLP's own fields
545 4 ▶ if(!defined($l->{geometry}{location}{lat}) && defined($l->{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"lat"}) 3 1 4
Condition66%2/3
not defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"lat"}
!ll&&!rl&&r
103
MC/DC50%1/2
not defined $l->{"geometry"}{"location"}{"lat"} and defined $l->{"lat"}
not defined $l->{"geometry"}{"location"}{"lat"} defined $l->{"lat"}
Truth table66%2/3
not(A) and B
A= not defined $l->{"geometry"}{"location"}{"lat"}B= defined $l->{"lat"}
ABresult
0X0
100
111
546 3 $l->{geometry}{location}{lat} = $l->{lat};
547 3 ▶ $l->{geometry}{location}{lng} = $l->{lng} // $l->{lon};
Condition33%1/3
$l->{"lng"} // $l->{"lon"}
l!l&&r!l&&!r
300
MC/DC0%0/2
$l->{"lng"} // $l->{"lon"}
$l->{"lng"} $l->{"lon"}
Truth table33%1/3
A // B
A= $l->{"lng"}B= $l->{"lon"}
ABresult
1X1
011
000
548 }
549  
550 # Convenience aliases (idempotent if already set by GLP)
551 4 ▶ $l->{'lat'} //= $l->{geometry}{location}{lat};
Condition66%2/3
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
l!l&&r!l&&!r
310
MC/DC0%0/2
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
$l->{"lat"} $l->{"geometry"}{"location"}{"lat"}
Truth table66%2/3
A //= B
A= $l->{"lat"}B= $l->{"geometry"}{"location"}{"lat"}
ABresult
1X1
011
000
552 4 ▶ $l->{'lng'} //= $l->{geometry}{location}{lng};
Condition66%2/3
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
310
MC/DC0%0/2
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lng"} $l->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $l->{"lng"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
553 4 ▶ $l->{'lon'} //= $l->{geometry}{location}{lng};
Condition33%1/3
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
040
MC/DC0%0/2
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lon"} $l->{"geometry"}{"location"}{"lng"}
Truth table33%1/3
A //= B
A= $l->{"lon"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
554  
555 4 CORE::push @{$self->{'log'}}, {
556 line => $call_details[2],
557 location => $location,
558 timetaken => $timetaken,
559 geocoder => ref($geocoder),
560 wantarray => wantarray,
561 result => $l,
562 };
563 4 $good_result = $l;
564 4 last POSSIBLE_LOCATION;
565 }
566  
567 # Only HASH results need normalisation
568 110 ▶ next if(ref($l) ne 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
if ref $l ne "HASH" 0 110 110
569  
570 110 ▶ if($l->{'error'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($l->{'error'}) { } 1 109 110
571 # A top-level 'error' key signals a provider-level failure
572 my $log = {
573 line => $call_details[2],
574 location => $location,
575 timetaken => $timetaken,
576 geocoder => ref($geocoder),
577 wantarray => wantarray,
578 1 error => $l->{'error'},
579 };
580 1 CORE::push @{$self->{'log'}}, $log;
581 1 next ENCODER;
582 } else {
583 # Map provider-specific fields to the canonical geometry structure
584 109 ▶ if(!defined($l->{geometry}{location}{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $l->{"geometry"}{"location"}{"lat"}) 105 4 109
585 105 my ($lat, $long);
586  
587 105 ▶ if(defined($l->{lat}) && defined($l->{lon})) {
Branch: 11 branches
BranchTrueFalseTotal
if (defined $l->{'lat'} and defined $l->{'lon'}) { } 79 26 105
elsif ($l->{'BestLocation'}) { } 2 24 26
elsif ($l->{'point'}) { } 3 21 24
elsif (defined $l->{'latt'}) { } 2 19 21
elsif (defined $l->{'latitude'}) { } 3 16 19
elsif (defined $l->{'properties'}{'geoLatitude'}) { } 1 15 16
elsif ($l->{'results'}[0]{'geometry'}) { } 3 12 15
elsif ($l->{'RESULTS'}) { } 2 10 12
elsif (defined $l->{'result'}{'addressMatches'}[0]{'coordinates'}{'y'}) { } 1 9 10
elsif (defined $l->{'lat'}) { } 3 6 9
elsif ($l->{'features'}) { } 4 2 6
Condition100%3/3
defined $l->{"lat"} and defined $l->{"lon"}
!ll&&!rl&&r
23379
MC/DC100%2/2
defined $l->{"lat"} and defined $l->{"lon"}
defined $l->{"lat"} defined $l->{"lon"}
Truth table100%3/3
A and B
A= defined $l->{"lat"}B= defined $l->{"lon"}
ABresult
0X0
100
111
588 # OSM / RandMcNally: top-level lat/lon fields
589 79 $lat = $l->{lat};
590 79 $long = $l->{lon};
591 79 $l->{'debug'} = __LINE__;
592 } elsif($l->{BestLocation}) {
593 # Bing Maps: BestLocation.Coordinates.{Latitude,Longitude}
594 2 $lat = $l->{BestLocation}->{Coordinates}->{Latitude};
595 2 $long = $l->{BestLocation}->{Coordinates}->{Longitude};
596 2 $l->{'debug'} = __LINE__;
597 } elsif($l->{point}) {
598 # Bing Maps alternative: point.coordinates[lat, lng]
599 3 $lat = $l->{point}->{coordinates}[0];
600 3 $long = $l->{point}->{coordinates}[1];
601 3 $l->{'debug'} = __LINE__;
602 } elsif(defined($l->{latt})) {
603 # geocoder.ca: latt / longt fields
604 2 $lat = $l->{latt};
605 2 $long = $l->{longt};
606 2 $l->{'debug'} = __LINE__;
607 } elsif(defined($l->{latitude})) {
608 # postcodes.io, Geo::Coder::Free: latitude / longitude
609 3 $lat = $l->{latitude};
610 3 $long = $l->{longitude};
611 3 ▶ if(my $type = $l->{'local_type'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $type = $l->{"local_type"}) 1 2 3
612 # Carry the local_type hint forward as a normalised 'type'
613 1 $l->{'type'} = lcfirst($type);
614 }
615 3 $l->{'debug'} = __LINE__;
616 } elsif(defined($l->{'properties'}{'geoLatitude'})) {
617 # HERE / Ovi: properties.geoLatitude / geoLongitude
618 1 $lat = $l->{properties}{geoLatitude};
619 1 $long = $l->{properties}{geoLongitude};
620 1 $l->{'debug'} = __LINE__;
621 } elsif($l->{'results'}[0]->{'geometry'}) {
622 3 ▶ if($l->{'results'}[0]->{'geometry'}->{'location'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($l->{'results'}[0]{'geometry'}{'location'}) { } 1 2 3
623 # DataScienceToolkit mirrors the Google Maps shape
624 1 $lat = $l->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
625 1 $long = $l->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};
626 1 $l->{'debug'} = __LINE__;
627 } else {
628 # OpenCage places lat/lng directly under geometry
629 2 $lat = $l->{'results'}[0]->{'geometry'}->{'lat'};
630 2 $long = $l->{'results'}[0]->{'geometry'}->{'lng'};
631 2 $l->{'debug'} = __LINE__;
632 }
633 } elsif($l->{'RESULTS'}) {
634 # GeoCodeFarm: RESULTS[0].COORDINATES.{latitude,longitude}
635 2 $lat = $l->{'RESULTS'}[0]{'COORDINATES'}{'latitude'};
636 2 $long = $l->{'RESULTS'}[0]{'COORDINATES'}{'longitude'};
637 2 $l->{'debug'} = __LINE__;
638 } elsif(defined($l->{result}{addressMatches}[0]->{coordinates}{y})) {
639 # US Census Bureau: result.addressMatches[0].coordinates.{y,x}
640 1 $lat = $l->{result}{addressMatches}[0]->{coordinates}{y};
641 1 $long = $l->{result}{addressMatches}[0]->{coordinates}{x};
642 1 $l->{'debug'} = __LINE__;
643 } elsif(defined($l->{lat})) {
644 # Geo::GeoNames: lat / lng (reached only after lat+lon check fails)
645 3 $lat = $l->{lat};
646 3 $long = $l->{lng};
647 3 $l->{'debug'} = __LINE__;
648 } elsif($l->{features}) {
649 4 ▶ if($l->{features}[0]->{center}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($l->{'features'}[0]{'center'}) { } 1 3 4
elsif ($l->{'features'}[0]{'geometry'}{'coordinates'}) { } 1 2 3
650 # Geo::Coder::Mapbox: center is [lng, lat]
651 1 $lat = $l->{features}[0]->{center}[1];
652 1 $long = $l->{features}[0]->{center}[0];
653 1 $l->{'debug'} = __LINE__;
654 } elsif($l->{'features'}[0]{'geometry'}{'coordinates'}) {
655 # Geo::Coder::GeoApify: coordinates is [lng, lat]
656 1 $lat = $l->{'features'}[0]{'geometry'}{'coordinates'}[1];
657 1 $long = $l->{'features'}[0]{'geometry'}{'coordinates'}[0];
658 1 $l->{'debug'} = __LINE__;
659 } else {
660 # GeoApify signals not-found via empty features, not an error
661 2 next ENCODER;
662 }
663 } else {
664 2 $l->{'debug'} = __LINE__;
665 }
666  
667 103 ▶ if(defined($lat) && defined($long)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lat and defined $long) { } 101 2 103
Condition66%2/3
defined $lat and defined $long
!ll&&!rl&&r
20101
MC/DC50%1/2
defined $lat and defined $long
defined $lat defined $long
Truth table66%2/3
A and B
A= defined $latB= defined $long
ABresult
0X0
100
111
668 # Populate the canonical geometry structure
669 101 $l->{geometry}{location}{lat} = $lat;
670 101 $l->{geometry}{location}{lng} = $long;
671 # Compatibility aliases expected by callers
672 101 $l->{'lat'} = $lat;
673 101 $l->{'lon'} = $long;
674 } else {
675 # No coordinates extracted; clean up any partial data
676 2 delete $l->{'geometry'};
677 2 delete $l->{'lat'};
678 2 delete $l->{'lon'};
679 }
680  
681 # geocoder.xyz provides a country name under 'standard'
682 103 ▶ if($l->{'standard'}{'countryname'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($l->{"standard"}{"countryname"}) 1 102 103
683 1 $l->{'address'}{'country'} = $l->{'standard'}{'countryname'};
684 }
685 }
686  
687 107 ▶ if(defined($l->{geometry}{location}{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $l->{"geometry"}{"location"}{"lat"}) 105 2 107
688 print $l->{geometry}{location}{lat}, '/',
689 $l->{geometry}{location}{lng}, "\n"
690 105 ▶ if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 4 101 105
691  
692 # Store the geocoder object (not just its name) on the result
693 105 $l->{geocoder} = $geocoder;
694 105 ▶ $l->{'lat'} //= $l->{geometry}{location}{lat};
Condition66%2/3
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
l!l&&r!l&&!r
10140
MC/DC0%0/2
$l->{"lat"} //= $l->{"geometry"}{"location"}{"lat"}
$l->{"lat"} $l->{"geometry"}{"location"}{"lat"}
Truth table66%2/3
A //= B
A= $l->{"lat"}B= $l->{"geometry"}{"location"}{"lat"}
ABresult
1X1
011
000
695 105 ▶ $l->{'lng'} //= $l->{geometry}{location}{lng};
Condition100%3/3
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
31002
MC/DC100%2/2
$l->{"lng"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lng"} $l->{"geometry"}{"location"}{"lng"}
Truth table100%3/3
A //= B
A= $l->{"lng"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
696 105 ▶ $l->{'lon'} //= $l->{geometry}{location}{lng};
Condition100%3/3
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
10122
MC/DC100%2/2
$l->{"lon"} //= $l->{"geometry"}{"location"}{"lng"}
$l->{"lon"} $l->{"geometry"}{"location"}{"lng"}
Truth table100%3/3
A //= B
A= $l->{"lon"}B= $l->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
697  
698 105 my $log = {
699 line => $call_details[2],
700 location => $location,
701 timetaken => $timetaken,
702 geocoder => ref($geocoder),
703 wantarray => wantarray,
704 result => $l,
705 };
706 105 CORE::push @{$self->{'log'}}, $log;
707  
708 # Record which element succeeded, then exit the inner loop
709 105 $good_result = $l;
710 105 last POSSIBLE_LOCATION;
711 }
712 }
713 }
714  
715 # Only attempt to return / cache if normalisation actually succeeded
716 114 ▶ next ENCODER unless defined $good_result;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $good_result 5 109 114
717  
718 print 'Number of matches from ', ref($geocoder), ': ',
719 109 ▶ scalar(@rc), "\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 4 105 109
720  
721 109 ▶ if($self->{'debug'} >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"} >= 2) 2 107 109
722 # Use 'local' to avoid permanently altering the global Maxdepth
723 2 local $Data::Dumper::Maxdepth = 10;
724 2 print Data::Dumper->new([\@rc])->Dump();
725 }
726  
727 # NOTE (latent unreachable path): if a geocoder returned a list whose
728 # first element is undef (e.g. (undef, {lat=>1,lon=>2})), $good_result
729 # would be set from a later element but defined($rc[0]) is false, so
730 # the block below is skipped and the valid result is silently discarded.
731 # No known geocoder produces a leading undef, making this scenario
732 # unreachable in practice. A safer guard would be defined($good_result).
733 109 ▶ if(defined($rc[0])) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc[0]) 109 0 109
734 # Normalise the legacy 'long' key some geocoders emit
735 109 ▶ if(defined($rc[0]->{'long'}) && !defined($rc[0]->{'lng'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc[0]{"long"} and not defined $rc[0]{"lng"}) 1 108 109
Condition66%2/3
defined $rc[0]{"long"} and not defined $rc[0]{"lng"}
!ll&&!rl&&r
10801
MC/DC50%1/2
defined $rc[0]{"long"} and not defined $rc[0]{"lng"}
defined $rc[0]{"long"} not defined $rc[0]{"lng"}
Truth table66%2/3
A and not(B)
A= defined $rc[0]{"long"}B= not defined $rc[0]{"lng"}
ABresult
0X0
100
111
736 1 $rc[0]->{'lng'} = $rc[0]->{'long'};
737 }
738 109 ▶ if(defined($rc[0]->{'long'}) && !defined($rc[0]->{'lon'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc[0]{"long"} and not defined $rc[0]{"lon"}) 1 108 109
Condition66%2/3
defined $rc[0]{"long"} and not defined $rc[0]{"lon"}
!ll&&!rl&&r
10801
MC/DC50%1/2
defined $rc[0]{"long"} and not defined $rc[0]{"lon"}
defined $rc[0]{"long"} not defined $rc[0]{"lon"}
Truth table66%2/3
A and not(B)
A= defined $rc[0]{"long"}B= not defined $rc[0]{"lon"}
ABresult
0X0
100
111
739 1 $rc[0]->{'lon'} = $rc[0]->{'long'};
740 }
741  
742 # Sanity check: the good result must have lat and lng
743 109 ▶ if((!defined($good_result->{lat})) || (!defined($good_result->{lng}))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $good_result->{"lat"} and defined $good_result->{"lng"}) 1 108 109
Condition66%2/3
defined $good_result->{"lat"} and defined $good_result->{"lng"}
!ll&&!rl&&r
01108
MC/DC50%1/2
defined $good_result->{"lat"} and defined $good_result->{"lng"}
defined $good_result->{"lat"} defined $good_result->{"lng"}
Truth table66%2/3
A and B
A= defined $good_result->{"lat"}B= defined $good_result->{"lng"}
ABresult
0X0
100
111
744 1 $self->_warn(Data::Dumper->new([\@rc])->Dump());
745 1 $self->_error("BUG: '$location': HASH exists but is not sensible");
746 }
747  
748 108 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) 4 104 108
749 4 $self->_cache($location, \@rc);
750 4 return @rc;
751 }
752  
753 104 $self->_cache($location, $good_result);
754 104 return $good_result;
755 }
756 }
757  
758 # ── No geocoder produced a usable result ──────────────────────────────
759  
760 48 ▶ print "No matches\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 48 48
761  
762 # Cache the not-found result so repeated calls do not hammer all backends
763 48 $self->_cache($location, undef);
764  
765 48 ▶ return wantarray ? () : undef;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 46 48
766 }
767  
768 # =============================================================================
769  
770 =head2 ua
771  
772 Sets the L<LWP::UserAgent> (or compatible) object on every geocoder in the
773 chain. Useful when you need proxy support or custom timeouts across all
774 backends at once.
775  
776 There is intentionally no read accessor since that would be meaningless
777 (each geocoder could have a different UA).
778  
779 use LWP::UserAgent;
780 my $ua = LWP::UserAgent->new();
781 $ua->env_proxy(1);
782 $list->ua($ua);
783  
784 =head3 API SPECIFICATION
785  
786 =head4 INPUT
787  
788 # Params::Validate::Strict schema
789 {
790 ua => {
791 type => OBJECT,
792 optional => 1,
793 },
794 }
795  
796 =head4 OUTPUT
797  
798 # Return::Set schema
799 OBJECT # the same $ua that was passed in
800  
801 =cut
802  
803 sub ua
804 31 ▶{
Subroutine ua: called CC=9 SCAR=22.0
Pod documented
805 31 my ($self, $ua) = @_;
806  
807 # Nothing to propagate if no UA was supplied
808 31 ▶ return unless $ua;
Branch: 1 branch
BranchTrueFalseTotal
unless $ua 4 27 31
809  
810 # Push the UA into every geocoder in the chain
811 27 foreach my $g (@{$self->{geocoders}}) {
812 30 ▶ my $geocoder = (ref($g) eq 'HASH') ? $g->{geocoder} : $g;
Branch: 1 branch
BranchTrueFalseTotal
ref $g eq 'HASH' ? : 5 25 30
813 # Guard against a misconfigured entry that has no geocoder object
814 30 ▶ Carp::croak('No geocoder found') unless defined $geocoder;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $geocoder 3 27 30
815  
816 # When the incoming UA supports clone(), create a per-geocoder copy
817 # and set the geocoder's own agent string on that copy.
818 # Some APIs (e.g. OSM Nominatim) require a specific User-Agent and
819 # refuse requests that carry the generic libwww-perl default.
820 # The agent string is derived from the geocoder class name and version
821 # (e.g. 'Geo::Coder::OSM/0.03') without reading the geocoder's current
822 # UA, which would trigger any spy or hook installed on its ua() method.
823 27 ▶ if($ua->can('clone') && $ua->can('agent')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ua->can('clone') and $ua->can('agent')) { } 13 14 27
Condition100%3/3
$ua->can("clone") and $ua->can("agent")
!ll&&!rl&&r
13113
MC/DC100%2/2
$ua->can("clone") and $ua->can("agent")
$ua->can("clone") $ua->can("agent")
Truth table100%3/3
A and B
A= $ua->can("clone")B= $ua->can("agent")
ABresult
0X0
100
111
824 13 my $per_ua = $ua->clone();
825 13 my $class = ref($geocoder);
826 13 ▶ my $version = eval { $geocoder->VERSION() } // '';
Condition100%2/2
eval { // ""
l!l
211
MC/DC100%1/1
eval { do { $geocoder->VERSION } } // ""
eval { do { $geocoder->VERSION } }
Truth table100%2/2
A
A= eval { do { $geocoder->VERSION } }
Aresult
11
00
827 13 ▶ $per_ua->agent($version ? "$class/$version" : $class);
Branch: 1 branch
BranchTrueFalseTotal
$version ? : 2 11 13
828 13 $geocoder->ua($per_ua);
829 } else {
830 14 $geocoder->ua($ua);
831 }
832 }
833  
834 # Return the UA so callers can verify what was set (API contract)
835 24 return $ua;
836 }
837  
838 # =============================================================================
839  
840 =head2 reverse_geocode
841  
842 Converts a latitude/longitude pair into a human-readable address string.
843  
844 In scalar context returns a single address string (or C<undef>).
845 In list context returns all address strings from the winning geocoder.
846  
847 my $address = $list->reverse_geocode(latlng => '51.5074,-0.1278');
848 print "Address: $address\n" if $address;
849  
850 my @addresses = $list->reverse_geocode(latlng => '51.5074,-0.1278');
851  
852 =head3 API SPECIFICATION
853  
854 =head4 INPUT
855  
856 # Params::Validate::Strict schema
857 {
858 latlng => {
859 type => SCALAR,
860 required => 1,
861 regex => qr/^\s*[-+]?(?:\d*\.?\d+|\d+\.?\d*)
862 \s*,\s*
863 [-+]?(?:\d*\.?\d+|\d+\.?\d*)\s*$/x,
864 },
865 }
866  
867 =head4 OUTPUT
868  
869 # Return::Set schema (scalar context)
870 SCALAR (address string) | undef
871  
872 # Return::Set schema (list context)
873 ARRAY of SCALAR
874  
875 =cut
876  
877 62 ▶sub reverse_geocode {
Subroutine reverse_geocode: called CC=29 SCAR=33.8
Pod documented
878 62 my $self = shift;
879 62 my $params = Params::Get::get_params('latlng', \@_);
880  
881 60 ▶ my $latlng = $params->{'latlng'} or Carp::croak('Usage: reverse_geocode(latlng => $location)');
Branch: 1 branch
BranchTrueFalseTotal
my $latlng = $params->{"latlng"} or Carp::croak("Usage: reverse_geocode(latlng => \$location)") 58 2 60
882  
883 # Split into components; populate convenience keys for geocoders that want them
884 58 my ($latitude, $longitude) = split(/,/, $latlng);
885 58 ▶ $params->{'lat'} //= $latitude;
Condition33%1/3
$params->{"lat"} //= $latitude
l!l&&r!l&&!r
0580
MC/DC0%0/2
$params->{"lat"} //= $latitude
$params->{"lat"} $latitude
Truth table33%1/3
A //= B
A= $params->{"lat"}B= $latitude
ABresult
1X1
011
000
886 58 ▶ $params->{'lon'} //= $longitude;
Condition33%1/3
$params->{"lon"} //= $longitude
l!l&&r!l&&!r
0580
MC/DC0%0/2
$params->{"lon"} //= $longitude
$params->{"lon"} $longitude
Truth table33%1/3
A //= B
A= $params->{"lon"}B= $longitude
ABresult
1X1
011
000
887  
888 # Check L1 / L2 cache before hitting any backend
889 58 ▶ if(my $rc = $self->_cache($latlng)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $rc = $self->_cache($latlng)) 5 53 58
890 5 return $rc;
891 }
892  
893 53 my @call_details = caller(0);
894  
895 53 foreach my $g (@{$self->{geocoders}}) {
896 54 my $geocoder = $g;
897  
898 # Apply the per-geocoder limit guard for hashref entries
899 54 ▶ if(ref($geocoder) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $geocoder eq "HASH") 5 49 54
900 5 ▶ if(exists($geocoder->{'limit'}) && defined(my $limit = $geocoder->{'limit'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})) 4 1 5
Condition66%2/3
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
!ll&&!rl&&r
104
MC/DC50%1/2
exists $geocoder->{"limit"} and defined(my $limit = $geocoder->{"limit"})
exists $geocoder->{"limit"} defined(my $limit = $geocoder->{"limit"})
Truth table66%2/3
A and B
A= exists $geocoder->{"limit"}B= defined(my $limit = $geocoder->{"limit"})
ABresult
0X0
100
111
901 4 ▶ print "limit: $limit\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 4 4
902 4 ▶ if($limit <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit <= 0) 3 1 4
903 3 next;
904 }
905 1 $geocoder->{'limit'}--;
906 }
907 2 $geocoder = $g->{'geocoder'};
908 }
909  
910 51 ▶ print 'trying ', ref($geocoder), "\n" if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 1 50 51
911  
912 51 ▶ if(wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 17 34 51
913 # ── List context: collect all address strings from this geocoder ───
914 17 my @rc;
915 my @locs;
916 17 eval { @locs = $geocoder->reverse_geocode(%{$params}) };
917  
918 # Some geocoders (e.g. Geo::Coder::GeoApify) use strict parameter
919 # validation and reject the 'latlng' key as unknown. Retry without
920 # it -- lat and lon are already in %params from the split above.
921 # Other geocoders (e.g. Geo::Coder::CA) require 'latlng', so the
922 # first attempt must include it.
923 17 ▶ if($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) 2 15 17
924 2 my %no_latlng = %{$params};
925 2 delete $no_latlng{'latlng'};
926 2 $@ = '';
927 2 eval { @locs = $geocoder->reverse_geocode(%no_latlng) };
928 }
929  
930 17 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 3 14 17
931 3 CORE::push @{$self->{'log'}}, {
932 line => $call_details[2],
933 location => $latlng,
934 geocoder => ref($geocoder),
935 timetaken => 0,
936 wantarray => 1,
937 error => $@,
938 };
939 3 $self->_warn(ref($geocoder), " '$latlng': $@");
940 3 next;
941 }
942  
943 14 ▶ print Data::Dumper->new([\@locs])->Dump() if($self->{'debug'} >= 2);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} >= 2 0 14 14
944  
945 14 foreach my $loc (@locs) {
946 19 ▶ if(my $name = $loc->{'display_name'}) {
Branch: 3 branches
BranchTrueFalseTotal
if (my $name = $loc->{'display_name'}) { } 15 4 19
elsif ($loc->{'city'}) { } 2 2 4
elsif ($loc->{'features'}) { } 2 0 2
947 # OSM returns the full address in display_name
948 15 CORE::push @rc, $name;
949 } elsif($loc->{'city'}) {
950 # Geo::Coder::CA: build the address from individual fields
951 2 CORE::push @rc, _build_ca_address($loc);
952 } elsif($loc->{features}) {
953 # GeoApify: formatted string inside a features array
954 CORE::push @rc,
955 2 $loc->{features}[0]->{properties}{formatted};
956 2 last; # only one result from this provider
957 }
958 }
959  
960 14 CORE::push @{$self->{'log'}}, {
961 line => $call_details[2],
962 location => $latlng,
963 geocoder => ref($geocoder),
964 timetaken => 0,
965 wantarray => 1,
966 result => \@rc,
967 };
968  
969 14 $self->_cache($latlng, \@rc);
970 14 return @rc;
971  
972 } else {
973 # ── Scalar context: return the first address string ────────────────
974 my $rc = $self->_cache($latlng)
975 34 ▶ // eval { $geocoder->reverse_geocode(%{$params}) };
Condition66%2/3
$self->_cache($latlng) // eval {
l!l&&r!l&&!r
02014
MC/DC50%1/2
$self->_cache($latlng) // eval { do { $geocoder->reverse_geocode(%{$params;}) } }
$self->_cache($latlng) eval { do { $geocoder->reverse_geocode(%{$params;}) } }
Truth table66%2/3
A // B
A= $self->_cache($latlng)B= eval { do { $geocoder->reverse_geocode(%{$params;}) } }
ABresult
1X1
011
000
976  
977 # Same strict-validation fallback as the list-context path above
978 34 ▶ if($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /Unknown parameter.*latlng|latlng.*[Uu]nknown/s) 7 27 34
979 7 my %no_latlng = %{$params};
980 7 delete $no_latlng{'latlng'};
981 7 $@ = '';
982 7 $rc = eval { $geocoder->reverse_geocode(%no_latlng) };
983 }
984  
985 34 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 7 27 34
986 7 CORE::push @{$self->{'log'}}, {
987 line => $call_details[2],
988 location => $latlng,
989 geocoder => ref($geocoder),
990 timetaken => 0,
991 wantarray => 0,
992 error => $@,
993 };
994 7 $self->_warn(ref($geocoder), " '$latlng': $@");
995 7 next;
996 }
997  
998 # A bare string needs no further processing
999 27 ▶ next unless defined $rc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rc 1 26 27
1000 26 ▶ if(!ref($rc)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $rc) 3 23 26
1001 3 CORE::push @{$self->{'log'}}, {
1002 line => $call_details[2],
1003 location => $latlng,
1004 geocoder => ref($geocoder),
1005 timetaken => 0,
1006 wantarray => 0,
1007 result => $rc,
1008 };
1009 3 return $rc;
1010 }
1011  
1012 23 ▶ print Data::Dumper->new([$rc])->Dump() if($self->{'debug'} >= 2);
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} >= 2 1 22 23
1013  
1014 23 ▶ if(my $name = $rc->{'display_name'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $name = $rc->{"display_name"}) 18 5 23
1015 # OSM
1016 18 CORE::push @{$self->{'log'}}, {
1017 line => $call_details[2],
1018 location => $latlng,
1019 geocoder => ref($geocoder),
1020 timetaken => 0,
1021 wantarray => 0,
1022 result => $name,
1023 };
1024 18 return $self->_cache($latlng, $name);
1025 }
1026  
1027 5 ▶ if($rc->{'city'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc->{"city"}) 3 2 5
1028 # Geo::Coder::CA
1029 3 my $name = _build_ca_address($rc);
1030 3 CORE::push @{$self->{'log'}}, {
1031 line => $call_details[2],
1032 location => $latlng,
1033 geocoder => ref($geocoder),
1034 timetaken => 0,
1035 wantarray => 0,
1036 result => $name,
1037 };
1038 3 return $self->_cache($latlng, $name);
1039 }
1040  
1041 2 ▶ if($rc->{features}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc->{"features"}) 2 0 2
1042 # GeoApify
1043 2 my $name = $rc->{features}[0]->{properties}{formatted};
1044 2 CORE::push @{$self->{'log'}}, {
1045 line => $call_details[2],
1046 location => $latlng,
1047 geocoder => ref($geocoder),
1048 timetaken => 0,
1049 wantarray => 0,
1050 result => $name,
1051 };
1052 2 return $self->_cache($latlng, $name);
1053 }
1054 }
1055 }
1056  
1057 13 return;
1058 }
1059  
1060 # =============================================================================
1061  
1062 =head2 log
1063  
1064 Returns an arrayref of log entries accumulated since the last C<flush()>.
1065 Each entry is a hashref with the keys: C<line>, C<location>, C<timetaken>,
1066 C<geocoder>, C<wantarray>, and either C<result> or C<error>.
1067  
1068 foreach my $entry (@{ $list->log() }) {
1069 printf "%s: %.3fs via %s\n",
1070 $entry->{location},
1071 $entry->{timetaken},
1072 $entry->{geocoder};
1073 }
1074  
1075 =head3 API SPECIFICATION
1076  
1077 =head4 INPUT
1078  
1079 # No parameters accepted
1080  
1081 =head4 OUTPUT
1082  
1083 # Return::Set schema
1084 ARRAYREF of HASHREF
1085 [
1086 {
1087 line => Int,
1088 location => Str,
1089 timetaken => Num,
1090 geocoder => Str | 'cache',
1091 wantarray => Bool,
1092 result => HASHREF | ARRAYREF | Str, # on success
1093 error => Str, # on failure
1094 },
1095 ...
1096 ]
1097  
1098 =cut
1099  
1100 37 ▶sub log {
Subroutine log: called CC=2 SCAR=7.2
Pod documented
1101 37 my $self = shift;
1102  
1103 # Guard against the state left by flush(); always return a valid arrayref
1104 37 ▶ return $self->{'log'} // [];
Condition50%1/2
$self->{"log"} // []
l!l
370
MC/DC0%0/1
$self->{"log"} // []
$self->{"log"}
Truth table50%1/2
A
A= $self->{"log"}
Aresult
11
00
1105 }
1106  
1107 # =============================================================================
1108  
1109 =head2 flush
1110  
1111 Clears all accumulated log entries and returns C<$self> to allow chaining.
1112  
1113 $list->geocode('Paris, France');
1114 my $entries = $list->log();
1115 $list->flush()->geocode('London, UK'); # chained
1116  
1117 =head3 API SPECIFICATION
1118  
1119 =head4 INPUT
1120  
1121 # No parameters accepted
1122  
1123 =head4 OUTPUT
1124  
1125 # Return::Set schema
1126 OBJECT blessed into Geo::Coder::List # $self, for chaining
1127  
1128 =cut
1129  
1130 15 ▶sub flush {
Subroutine flush: called CC=1 SCAR=0.0
Pod documented
1131 15 my $self = shift;
1132  
1133 # Reset to an empty arrayref so log() always returns a valid reference
1134 15 $self->{'log'} = [];
1135  
1136 15 return $self;
1137 }
1138  
1139 # =============================================================================
1140 # PRIVATE HELPERS
1141 # =============================================================================
1142  
1143 # _build_ca_address
1144 #
1145 # Purpose: Assemble a printable address string from a Geo::Coder::CA
1146 # reverse-geocode response. The CA response uses different keys
1147 # for US addresses (nested under 'usa') vs Canadian ones.
1148 #
1149 # Entry: $loc - HASHREF from Geo::Coder::CA reverse_geocode()
1150 #
1151 # Exit: Returns a plain string, or empty string if nothing was found.
1152 #
1153 # Notes: Street number and name are joined with a space; other parts
1154 # (city, province/state, country) are joined with ', '.
1155  
1156 sub _build_ca_address
1157 16 ▶{
Subroutine _build_ca_address: called CC=17 SCAR=28.4
1158 16 my $loc = $_[0];
1159 16 my $name = '';
1160  
1161 16 ▶ if(my $usa = $loc->{'usa'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $usa = $loc->{'usa'}) { } 5 11 16
1162 # US address layout inside a CA result
1163 5 ▶ $name = $usa->{'usstnumber'} // '';
Condition100%2/2
$usa->{"usstnumber"} // ""
l!l
32
MC/DC100%1/1
$usa->{"usstnumber"} // ""
$usa->{"usstnumber"}
Truth table100%2/2
A
A= $usa->{"usstnumber"}
Aresult
11
00
1164 # Street name follows number with a space; if no number, no leading space
1165 5 ▶ $name .= ($name ? ' ' : '') . $usa->{'usstaddress'} if $usa->{'usstaddress'};
Branch: 2 branches
BranchTrueFalseTotal
if $usa->{"usstaddress"} 4 1 5
$name ? : 3 1 4
1166 # City, state, country each separated by ', '; skip separator if name empty
1167 5 ▶ $name .= ($name ? ', ' : '') . $usa->{'uscity'} if $usa->{'uscity'};
Branch: 2 branches
BranchTrueFalseTotal
if $usa->{"uscity"} 4 1 5
$name ? : 3 1 4
1168 5 ▶ $name .= ($name ? ', ' : '') . $usa->{'state'} if $usa->{'state'};
Branch: 2 branches
BranchTrueFalseTotal
if $usa->{"state"} 3 2 5
$name ? : 3 0 3
1169 # Country is always appended for the US branch
1170 5 ▶ $name .= ($name ? ', ' : '') . 'USA';
Branch: 1 branch
BranchTrueFalseTotal
$name ? : 5 0 5
1171 } else {
1172 # Canadian address layout
1173 11 ▶ $name = $loc->{'stnumber'} // '';
Condition100%2/2
$loc->{"stnumber"} // ""
l!l
83
MC/DC100%1/1
$loc->{"stnumber"} // ""
$loc->{"stnumber"}
Truth table100%2/2
A
A= $loc->{"stnumber"}
Aresult
11
00
1174 # Street name follows number with a space; if no number, no leading space
1175 11 ▶ $name .= ($name ? ' ' : '') . $loc->{'staddress'} if $loc->{'staddress'};
Branch: 2 branches
BranchTrueFalseTotal
if $loc->{"staddress"} 8 3 11
$name ? : 7 1 8
1176 11 ▶ $name .= ($name ? ', ' : '') . $loc->{'city'} if $loc->{'city'};
Branch: 2 branches
BranchTrueFalseTotal
if $loc->{"city"} 9 2 11
$name ? : 8 1 9
1177 11 ▶ $name .= ($name ? ', ' : '') . $loc->{'prov'} if $loc->{'prov'};
Branch: 2 branches
BranchTrueFalseTotal
if $loc->{"prov"} 8 3 11
$name ? : 8 0 8
1178 }
1179  
1180 16 return $name;
1181 }
1182  
1183 # -----------------------------------------------------------------------------
1184  
1185 # _cache
1186 #
1187 # Read from or write to the two-level cache.
1188 # L1 is an in-process HASH (always active).
1189 # L2 is an optional CHI-compatible object or a plain HASH ref.
1190 #
1191 # Entry (write): _cache($key, $value)
1192 # $value may be undef, which is stored as $NOT_FOUND_SENTINEL so
1193 # subsequent reads can distinguish "cached not-found" from "never
1194 # looked up". Detect the write path by testing scalar(@_) before
1195 # shifting, not by truthiness of the value.
1196 #
1197 # Entry (read): _cache($key)
1198 #
1199 # Exit (write): Returns $value (undef if the location was not found).
1200 # Exit (read): Returns the cached value, or undef if not in cache.
1201 # $NOT_FOUND_SENTINEL is never surfaced to callers; undef is
1202 # returned in its place so callers handle both cases identically.
1203 #
1204 # Side effects: May update $self->{locations} (L1) and $self->{'cache'} (L2).
1205 #
1206 # Notes: Cache TTLs are taken from $self->{cache_*_duration}, which are
1207 # initialised from %config and overridable via Object::Configure.
1208 # Not-found sentinels are stored only in L1 to avoid leaking
1209 # internal implementation details into an external L2 store.
1210  
1211 510 ▶sub _cache {
Subroutine _cache: called CC=37 SCAR=36.4
1212 510 my $self = shift;
1213 510 my $key = shift;
1214  
1215 # ── Write path ────────────────────────────────────────────────────────
1216 # Detect a write call by the presence of a third argument (even if undef).
1217 # Testing truthiness of the value would silently swallow not-found results.
1218  
1219 510 ▶ if(scalar(@_)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_) 218 292 510
1220 218 my $value = shift;
1221  
1222 # Store a sentinel for not-found so we can skip backends on repeat calls
1223 218 ▶ my $stored = defined($value) ? $value : $NOT_FOUND_SENTINEL;
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 165 53 218
1224 218 $self->{locations}->{$key} = $stored;
1225  
1226 218 my $rc = $value;
1227  
1228 218 ▶ if($self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"cache"}) 24 194 218
1229 24 my $duration;
1230  
1231 24 ▶ if(ref($value) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq 'ARRAY') { } 8 16 24
elsif (ref $value eq 'HASH') { } 13 3 16
1232 8 foreach my $item (@{$value}) {
1233 # Blessed objects (e.g. Geo::Location::Point) may hold
1234 # unserializable handles; stringify their geocoder field too
1235 8 ▶ if(blessed($item) && ref($item->{'geocoder'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($item) and ref $item->{"geocoder"}) 2 6 8
Condition66%2/3
builtin::blessed($item) and ref $item->{"geocoder"}
!ll&&!rl&&r
602
MC/DC50%1/2
builtin::blessed($item) and ref $item->{"geocoder"}
builtin::blessed($item) ref $item->{"geocoder"}
Truth table66%2/3
A and B
A= builtin::blessed($item)B= ref $item->{"geocoder"}
ABresult
0X0
100
111
1236 2 $item->{'geocoder'} = ref($item->{'geocoder'});
1237 }
1238  
1239 8 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 2 6 8
1240  
1241 # Serialise the geocoder object to its class name for storage
1242 6 $item->{'geocoder'} = ref($item->{'geocoder'});
1243  
1244 # Strip everything except geometry to keep the L2 entry small
1245 6 ▶ unless($self->{'debug'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"debug"}) 5 1 6
1246 5 ▶ while(my ($k, $v) = each %{$item}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$item;}) 10 5 15
1247 10 ▶ delete $item->{$k} unless($k eq 'geometry');
Branch: 1 branch
BranchTrueFalseTotal
unless $k eq "geometry" 6 4 10
1248 }
1249 }
1250  
1251 6 ▶ unless(defined($item->{geometry}{location}{lat})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $item->{"geometry"}{"location"}{"lat"}) 4 2 6
1252 # Partial or temporary failure: use the shorter TTL.
1253 # UNREACHABLE ARM: the access above auto-vivifies
1254 # $item->{geometry} as {}, so defined($item->{geometry})
1255 # is always true here; the false arm never executes.
1256 # Original ternary preserved for documentation:
1257 # $duration //= defined($item->{geometry})
1258 # ? $self->{'cache_part_duration'}
1259 # : $self->{'cache_miss_duration'};
1260 4 ▶ $duration //= $self->{'cache_part_duration'};
Condition33%1/3
$duration //= $self->{"cache_part_duration"}
l!l&&r!l&&!r
040
MC/DC0%0/2
$duration //= $self->{"cache_part_duration"}
$duration $self->{"cache_part_duration"}
Truth table33%1/3
A //= B
A= $durationB= $self->{"cache_part_duration"}
ABresult
1X1
011
000
1261 4 $rc = undef;
1262 }
1263 }
1264  
1265 # All items were clean: use the full hit duration
1266 8 ▶ $duration //= $self->{'cache_hit_duration'};
Condition66%2/3
$duration //= $self->{"cache_hit_duration"}
l!l&&r!l&&!r
440
MC/DC0%0/2
$duration //= $self->{"cache_hit_duration"}
$duration $self->{"cache_hit_duration"}
Truth table66%2/3
A //= B
A= $durationB= $self->{"cache_hit_duration"}
ABresult
1X1
011
000
1267  
1268 } elsif(ref($value) eq 'HASH') {
1269 13 $value->{'geocoder'} = ref($value->{'geocoder'});
1270  
1271 13 ▶ unless($self->{'debug'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"debug"}) 12 1 13
1272 12 ▶ while(my ($k, $v) = each %{$value}) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$value;}) 40 12 52
1273 40 ▶ delete $value->{$k} unless($k eq 'geometry');
Branch: 1 branch
BranchTrueFalseTotal
unless $k eq "geometry" 30 10 40
1274 }
1275 }
1276  
1277 13 ▶ if(defined($value->{geometry}{location}{lat})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $value->{'geometry'}{'location'}{'lat'}) { } 8 5 13
elsif (defined $value->{'geometry'}) { } 5 0 5
1278 # Confirmed location: cache for a full month
1279 8 $duration = $self->{'cache_hit_duration'};
1280 } elsif(defined($value->{geometry})) {
1281 # Partial geometry: may be a transient failure, retry soon
1282 5 $duration = $self->{'cache_part_duration'};
1283 5 $rc = undef;
1284 }
1285 # UNREACHABLE: the else branch below is dead. The access
1286 # defined($value->{geometry}{location}{lat}) above auto-vivifies
1287 # $value->{geometry} as {}, so the elsif is always taken when
1288 # the if fails. Original else preserved for documentation:
1289 # } else {
1290 # # No geometry at all: place probably does not exist
1291 # $duration = $self->{'cache_miss_duration'};
1292 # $rc = undef;
1293 # }
1294 } else {
1295 # Scalar string or a blessed object (e.g. Geo::Location::Point).
1296 # Blessed objects may hold unserializable handles; stringify the
1297 # geocoder field so CHI (Storable) can freeze the value safely.
1298 3 ▶ if(ref($value) && ref($value->{'geocoder'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value and ref $value->{"geocoder"}) 0 3 3
Condition33%1/3
ref $value and ref $value->{"geocoder"}
!ll&&!rl&&r
300
MC/DC0%0/2
ref $value and ref $value->{"geocoder"}
ref $value ref $value->{"geocoder"}
Truth table33%1/3
A and B
A= ref $valueB= ref $value->{"geocoder"}
ABresult
0X0
100
111
1299 0 $value->{'geocoder'} = ref($value->{'geocoder'});
1300 }
1301 3 $duration = $self->{'cache_hit_duration'};
1302 }
1303  
1304 24 ▶ print Data::Dumper->new([$value])->Dump() if($self->{'debug'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 2 22 24
1305  
1306 # Do not push the not-found sentinel into L2
1307 24 ▶ if(!defined($value)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $value) { } 3 21 24
elsif (ref $self->{'cache'} eq 'HASH') { } 11 10 21
1308 # value is not-found; L1 sentinel is sufficient
1309 } elsif(ref($self->{'cache'}) eq 'HASH') {
1310 11 $self->{'cache'}->{$key} = $value;
1311 } else {
1312 10 $self->{'cache'}->set($key, $value, $duration);
1313 }
1314 }
1315  
1316 218 return $rc;
1317 }
1318  
1319 # ── Read path ─────────────────────────────────────────────────────────
1320  
1321 # Check L1 first (in-process, no serialisation cost)
1322 292 my $rc = $self->{'locations'}->{$key};
1323  
1324 # Fall through to L2 only when L1 has no entry for this key
1325 292 ▶ if((!defined($rc)) && $self->{'cache'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $rc and $self->{"cache"}) 7 285 292
Condition100%3/3
not defined $rc and $self->{"cache"}
!ll&&!rl&&r
432427
MC/DC100%2/2
not defined $rc and $self->{"cache"}
not defined $rc $self->{"cache"}
Truth table100%3/3
not(A) and B
A= not defined $rcB= $self->{"cache"}
ABresult
0X0
100
111
1326 7 ▶ if(ref($self->{'cache'}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{'cache'} eq 'HASH') { } 5 2 7
1327 5 $rc = $self->{'cache'}->{$key};
1328 } else {
1329 2 $rc = $self->{'cache'}->get($key);
1330 }
1331 }
1332  
1333 292 ▶ return unless defined $rc;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rc 246 46 292
1334  
1335 # Translate the not-found sentinel back to undef for the caller
1336 46 ▶ return if ref($rc) && (ref($rc) eq _NOT_FOUND_CLASS);
Branch: 1 branch
BranchTrueFalseTotal
if ref $rc and ref $rc eq "Geo::Coder::List::_NotFound" 7 39 46
Condition100%3/3
ref $rc and ref $rc eq "Geo::Coder::List::_NotFound"
!ll&&!rl&&r
3367
MC/DC100%2/2
ref $rc and ref $rc eq "Geo::Coder::List::_NotFound"
ref $rc ref $rc eq "Geo::Coder::List::_NotFound"
Truth table100%3/3
A and B
A= ref $rcB= ref $rc eq "Geo::Coder::List::_NotFound"
ABresult
0X0
100
111
1337  
1338 # Restore the convenience aliases that were stripped before L2 storage
1339 39 ▶ if(ref($rc) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rc eq "HASH") 28 11 39
1340 28 ▶ return unless defined($rc->{geometry}{location}{lat});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rc->{"geometry"}{"location"}{"lat"} 1 27 28
1341 27 ▶ $rc->{'lat'} //= $rc->{geometry}{location}{lat};
Condition66%2/3
$rc->{"lat"} //= $rc->{"geometry"}{"location"}{"lat"}
l!l&&r!l&&!r
2160
MC/DC0%0/2
$rc->{"lat"} //= $rc->{"geometry"}{"location"}{"lat"}
$rc->{"lat"} $rc->{"geometry"}{"location"}{"lat"}
Truth table66%2/3
A //= B
A= $rc->{"lat"}B= $rc->{"geometry"}{"location"}{"lat"}
ABresult
1X1
011
000
1342 27 ▶ $rc->{'lng'} //= $rc->{geometry}{location}{lng};
Condition66%2/3
$rc->{"lng"} //= $rc->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
2160
MC/DC0%0/2
$rc->{"lng"} //= $rc->{"geometry"}{"location"}{"lng"}
$rc->{"lng"} $rc->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $rc->{"lng"}B= $rc->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
1343 27 ▶ $rc->{'lon'} //= $rc->{geometry}{location}{lng};
Condition66%2/3
$rc->{"lon"} //= $rc->{"geometry"}{"location"}{"lng"}
l!l&&r!l&&!r
2160
MC/DC0%0/2
$rc->{"lon"} //= $rc->{"geometry"}{"location"}{"lng"}
$rc->{"lon"} $rc->{"geometry"}{"location"}{"lng"}
Truth table66%2/3
A //= B
A= $rc->{"lon"}B= $rc->{"geometry"}{"location"}{"lng"}
ABresult
1X1
011
000
1344 }
1345  
1346 38 return $rc;
1347 }
1348  
1349 # Emit a debug message somewhere
1350 0 ▶sub _debug {
Subroutine _debug: not called CC=3 SCAR=24.8
1351 0 my $self = shift;
1352  
1353 0 ▶ if(my $logger = $self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 0 0 0
1354 0 $logger->debug(@_);
1355 }
1356 0 ▶ if($self->{debug}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 0 0 0
1357 0 print @_, "\n";
1358 }
1359 }
1360  
1361 # Emit a warning message somewhere
1362 26 ▶sub _warn {
Subroutine _warn: called CC=2 SCAR=7.6
1363 26 my $self = shift;
1364  
1365 26 ▶ if(my $logger = $self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{'logger'}) { } 26 0 26
1366 26 $logger->warn(@_);
1367 } else {
1368 0 Carp::carp(@_);
1369 }
1370 }
1371  
1372 # Emit an error message somewhere
1373 5 ▶sub _error {
Subroutine _error: called CC=2 SCAR=7.4
1374 5 my $self = shift;
1375  
1376 5 ▶ if(my $logger = $self->{logger}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{'logger'}) { } 5 0 5
1377 5 $logger->error(@_);
1378 5 die @_;
1379 } else {
1380 0 Carp::croak(@_);
1381 }
1382 }
1383  
1384 # =============================================================================
1385 # DOCUMENTATION
1386 # =============================================================================
1387  
1388 =head1 AUTHOR
1389  
1390 Nigel Horne, C<< <njh at nigelhorne.com> >>
1391  
1392 =head1 BUGS
1393  
1394 Please report any bugs or feature requests to
1395 C<bug-geo-coder-list at rt.cpan.org>, or through the web interface at
1396 L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Geo-Coder-List>.
1397  
1398 Known limitations:
1399  
1400 =over 4
1401  
1402 =item * C<reverse_geocode()> does not yet support L<Geo::Location::Point> objects.
1403  
1404 =item * When C<Geo::GeoNames> returns multiple candidates, only the first
1405 element of each sub-array is considered.
1406  
1407 =back
1408  
1409 =head1 SEE ALSO
1410  
1411 =over 4
1412  
1413 =item * L<Test Dashboard|https://nigelhorne.github.io/Geo-Coder-List/coverage/>
1414  
1415 =item * L<Geo::Coder::All>
1416  
1417 =item * L<Geo::Coder::GooglePlaces>
1418  
1419 =item * L<Geo::Coder::Many>
1420  
1421 =item * L<Configure an Object at Runtime|Object::Configure>
1422  
1423 =item * L<Readonly>
1424  
1425 =back
1426  
1427 =head1 SUPPORT
1428  
1429 You can find documentation for this module with the perldoc command:
1430  
1431 perldoc Geo::Coder::List
1432  
1433 =over 4
1434  
1435 =item * RT: CPAN's request tracker
1436  
1437 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Geo-Coder-List>
1438  
1439 =item * MetaCPAN
1440  
1441 L<https://metacpan.org/release/Geo-Coder-List>
1442  
1443 =back
1444  
1445 =encoding utf-8
1446  
1447 =head2 FORMAL SPECIFICATION
1448  
1449 =head3 new
1450  
1451 List_State
1452 ──────────────────────────────────────────────────────
1453 geocoders : seq (Geocoder | RegexGeocoder)
1454 L1 : LocationStr ↛ (GeoResult | NotFound)
1455 log : seq LogEntry
1456 debug : ℕ
1457 cache? : L2Cache
1458  
1459 new
1460 ──────────────────────────────────────────────────────
1461 List_State
1462 params? : ℙ(Key × Value)
1463 ──────────────────────────────────────────────────────
1464 geocoders = ⟨⟩
1465 L1 = ∅
1466 log = ⟨⟩
1467 debug = params?.debug ∣ DEBUG_DEFAULT
1468 cache = params?.cache ∣ ⊥
1469  
1470 =head3 push
1471  
1472 push
1473 ──────────────────────────────────────────────────────
1474 ΔList_State
1475 g? : Geocoder | RegexGeocoder
1476 ──────────────────────────────────────────────────────
1477 geocoders' = geocoders ⌢ ⟨g?⟩
1478 L1' = L1
1479 log' = log
1480 ──────────────────────────────────────────────────────
1481 where RegexGeocoder ::= { regex : Regex
1482 ; geocoder : Geocoder
1483 ; limit? : ℕ }
1484  
1485 =head3 geocode
1486  
1487 LocationStr ::= { s : seq Char | s ≠ ⟨⟩ ∧ ∃ c : s • c ∉ Digit }
1488 GeoResult ::= HASHREF with geometry.location.{lat,lng} : ℝ
1489  
1490 geocode
1491 ──────────────────────────────────────────────────────────────────────
1492 ΔList_State
1493 loc? : LocationStr
1494 result! : GeoResult | ⊥
1495 ──────────────────────────────────────────────────────────────────────
1496 loc? ∈ dom L1
1497 ⟹ result! = L1(loc?)
1498 ∧ log' = log ⌢ ⟨{geocoder ↦ cache; timetaken ↦ 0}⟩
1499  
1500 loc? ∉ dom L1
1501 ⟹ (∃ i : 1..#geocoders •
1502 applies(geocoders i, loc?)
1503 ∧ result! = Normalize(geocoders i . geocode(loc?))
1504 ∧ L1' = L1 ⊕ {loc? ↦ result!}
1505 ∧ log' = log ⌢ ⟨{geocoder ↦ class(geocoders i)}⟩)
1506 ∨ (result! = ⊥ ∧ L1' = L1 ⊕ {loc? ↦ ⊥})
1507  
1508 applies(g, loc) ≙
1509 (g isa Geocoder)
1510 ∨ (g isa RegexGeocoder ∧ loc ∈ matches(g.regex) ∧ g.limit > 0)
1511  
1512 =head3 ua SPECIFICATION
1513  
1514 ua
1515 ──────────────────────────────────────────────────────
1516 ΞList_State
1517 ua? : UserAgent
1518 ua! : UserAgent
1519 ──────────────────────────────────────────────────────
1520 ∀ g : ran geocoders • g.ua = ua?
1521 ua! = ua?
1522  
1523 =head3 reverse_geocode
1524  
1525 LatLngStr ::= { s : seq Char
1526 | s matches /^[-+]?\d+\.?\d*,[-+]?\d+\.?\d*$/ }
1527  
1528 reverse_geocode
1529 ──────────────────────────────────────────────────────────────────────
1530 ΔList_State
1531 latlng? : LatLngStr
1532 result! : seq Char | ⊥
1533 ──────────────────────────────────────────────────────────────────────
1534 latlng? ∈ dom L1
1535 ⟹ result! = L1(latlng?)
1536  
1537 latlng? ∉ dom L1
1538 ⟹ (∃ i : 1..#geocoders •
1539 applies(geocoders i, latlng?)
1540 ∧ result! = geocoders i . reverse_geocode(latlng?)
1541 ∧ L1' = L1 ⊕ {latlng? ↦ result!})
1542 ∨ result! = ⊥
1543  
1544 =head3 log
1545  
1546 log
1547 ──────────────────────────────────────────────────────
1548 ΞList_State
1549 result! : seq LogEntry
1550 ──────────────────────────────────────────────────────
1551 result! = log
1552  
1553 =head3 flush
1554  
1555 flush
1556 ──────────────────────────────────────────────────────
1557 ΔList_State
1558 ──────────────────────────────────────────────────────
1559 log' = ⟨⟩
1560 geocoders' = geocoders
1561 L1' = L1
1562  
1563 =head1 LICENSE AND COPYRIGHT
1564  
1565 Copyright 2016-2026 Nigel Horne.
1566  
1567 Usage is subject to the GPL2 licence terms.
1568 If you use it,
1569 please let me know.
1570  
1571 =cut
1572  
1573 24 1;
↑ Summary