blib/lib/Database/BI/Model/Boundary.pm

filter: Statementstmt 99.4% 332 / 334 Branchbran 94.4% 170 / 180 Conditioncond 89.1% 247 / 277 MC/DCmcdc 74.8% 107 / 143 Subroutinesub 100% 45 / 45 Podpod 100% 10 / 10 totaltotal 92.1% 911 / 989 CC 200 SCAR 25.0
CC
200
Cov
95%
_known
24.7
outlines
23.0
_outline_id
23.0
CRAP 12.2
« script/database-bi ↑ Summary blib/lib/Database/BI/SafeUA.pm »
1 package Database::BI::Model::Boundary;
2  
3 # The outline of the area each map marker is in: its country, state or
4 # province, county, city, town or neighbourhood (the level).
5 #
6 # A map can draw the boundary of the area around each of its markers. The
7 # outlines come from OpenStreetMap's Nominatim, through its reverse lookup:
8 # given a point and a zoom, it names the administrative area there and, with
9 # polygon_geojson, sends its shape. Asking by point rather than by name means
10 # the same code serves coordinate columns and geocoded places, in any country,
11 # and needs no state or country column to tell one Richmond from another.
12 #
13 # Nominatim allows one request a second, so this module asks as little as it
14 # can:
15 #
16 # 1. Each point is rounded to 3 decimal places (about 110 m), which is also
17 # all of it that leaves this machine, and remembered with the outline it
18 # fell in (or with none, for a point at sea).
19 # 2. A point not remembered is first tested against the outlines already
20 # known, through an index of their bounding boxes, so ten thousand shops
21 # in one county cost one request, not ten thousand.
22 # 3. Only then is Nominatim asked, at most online_max times a call, and a
23 # point it does not answer is left pending, not remembered as nowhere.
24 #
25 # The outlines are simplified by Nominatim (polygon_threshold), about 7 KB each,
26 # because they are written into the page.
27 #
28 # What Nominatim has at each level differs by country, and was probed in
29 # November 2026 (the points and what came back are in the comments at %LEVELS).
30 # A level is therefore a plan: a list of tries, each a reverse zoom and the
31 # place ranks an answer may have, taken in order until one gives an outline.
32 #
33 # country zoom 3, rank 4.
34 # state zoom 5, rank 8: a US or Indian state, a Canadian province, a
35 # New Zealand region, England or Scotland.
36 # county below, one rank a country.
37 # city zoom 10, ranks 12 to 16, an administrative area or a place
38 # mapped as an area: Toronto, Manchester, Canterbury (the
39 # district), Bristol. Where zoom 10 gives only a point (York,
40 # Pune), zoom 8 at rank 12: the unitary authority or city
41 # district. A point in no city gets its rank 12 area
42 # too (a US county): zoom 10 answers with it. New Zealand's cities are its territorial
43 # authorities, rank 12 at zoom 8 (Hamilton City), or the region
44 # where that is one (Auckland).
45 # town zoom 12, ranks 13 to 18: Margate, a Toronto ward. Then zoom
46 # 14, ranks 19 and 20, administrative areas only: a town
47 # that is a civil parish (Westgate-on-Sea).
48 # neighbourhood zoom 14, ranks 17 to 20: a Toronto neighbourhood, an English
49 # civil parish (Westgate-on-Sea), a suburb mapped as an area
50 # (Manchester's City Centre). Most suburbs are mapped as a
51 # point (Cliftonville, Garlinge), and those have no outline.
52 #
53 # The larger the area, the more its outline is simplified (the level's detail),
54 # or a country would be megabytes. An outline is kept under its detail, so one
55 # relation drawn at two levels (Auckland, a state and a city) is kept twice.
56 #
57 # A "county" is the division of a country below its states. Which
58 # of Nominatim's place ranks that is depends on the country, so %LEVELS gives a
59 # rank for most (12: a US county, an English county, a German Landkreis, a
60 # French departement, a Pakistani district) and the countries that differ (10:
61 # an Indian or Bangladeshi district, a Chinese prefecture, a Spanish province;
62 # 8: a Kenyan county), and config map_bounds_ranks can add more. Each reply
63 # names its country, so a point is asked at the zoom of the last country seen,
64 # and again at its own country's zoom when that guess was wrong: one extra
65 # request at each border a map crosses. The rank an outline was accepted at is
66 # kept with it, so a changed table asks again rather than draw the old level.
67 # The other levels do the same with their plans: a point is asked the first try
68 # of the last country's plan, and its own country's plan from there.
69  
70 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
71 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 6 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
74 6 ▶use JSON::PP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
75 6 ▶use List::Util qw(first);
Subroutine BEGIN: called CC=1 SCAR=0.0
76 6 ▶use Params::Get ();
Subroutine BEGIN: called CC=1 SCAR=0.0
77 6 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
78 6 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
79 6 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
80 6 ▶use Storable qw(dclone);
Subroutine BEGIN: called CC=1 SCAR=0.0
81 6 ▶use URI ();
Subroutine BEGIN: called CC=1 SCAR=0.0
82  
83 6 our $VERSION = '0.024.0';
84  
85 # The place rank an answer must have at each level: rank for a country not
86 # listed, countries for those that differ, by ISO 3166-1 alpha-2 code. Checked
87 # against Nominatim's reverse lookup in November 2026: rank 12
88 # at zoom 8 is the county level in the US, UK, Ireland, Germany, France, Italy,
89 # Pakistan, Mexico, Nigeria, South Africa, Russia, Indonesia and Canada.
90 # Australia, Brazil and Japan have nothing between their states and their
91 # towns, so a point there is nowhere.
92 #
93 # The other levels are plans: tries => [ { zoom, ranks => [low, high], places } ],
94 # with plans => { country => [ tries ] } for a country that differs. places
95 # lets a try take a place mapped as an area (place=city, town, suburb; a
96 # relation or a closed way) as well as an administrative boundary. detail is
97 # how far Nominatim may move an outline's edge to simplify it, in degrees, as
98 # text: it is stored with each outline and compared. name and names are what
99 # the area is called, as a word a caller can name it by to its readers
100 # (name_for). What the reverse lookup gave, November 2026 (zoom: rank, name):
101 #
102 # Toronto 5: 8 Ontario; 8 and 10: 12 Toronto; 12: 18 Toronto Centre
103 # (ward); 14: 20 Financial District
104 # Pune 5: 8 Maharashtra; 8: 12 Pune City Subdistrict; 10 and up:
105 # points only
106 # Canterbury 8: 12 Kent; 10 and 12: 16 Canterbury (the district)
107 # Manchester 8: 10 Greater Manchester; 10: 16 Manchester; 14: 19 City
108 # Centre (place=suburb, a way)
109 # Bristol, York 8: 12, the unitary authority; 10: 16 Bristol (place=city, a
110 # relation), York a point
111 # Hamilton NZ 5: 8 Waikato; 8, 10 and 12: 12 Hamilton City
112 # Auckland 5 and 8: 8 Auckland; 10: 16 Waitemata (a local board)
113 # Wellington 8: 12 Wellington City; 10: a point
114 # Margate 10: 16 Thanet; 12: 18 Margate (place=town, a relation); 13
115 # and 14: points (Cliftonville, Westbrook, Garlinge)
116 # Westgate-on-Sea 14: 20, the civil parish; 12: 18 Birchington, a point
117 6 Readonly my %LEVELS => (
118 country => {
119 name => 'country',
120 detail => '0.02', # Canada 15 KB, India 29 KB
121 tries => [ { zoom => 3, ranks => [ 4, 4 ] } ],
122 },
123 state => {
124 name => 'state',
125 names => {
126 ca => 'province', cn => 'province', es => 'region', fr => 'region',
127 gb => 'country', it => 'region', jp => 'prefecture', nl => 'province',
128 nz => 'region', pk => 'province', za => 'province',
129 },
130 detail => '0.01', # Ontario 12 KB, Maharashtra 30 KB, England 7 KB
131 tries => [ { zoom => 5, ranks => [ 8, 8 ] } ],
132 },
133 county => {
134 rank => 12,
135 countries => {
136 bd => 10, # district (zila); 12 is an upazila
137 cn => 10, # prefecture-level city; 12 is a district
138 es => 10, # province; Spain has no rank 12
139 in => 10, # district; 12 is a sub-district (tehsil, taluk)
140 ke => 8, # county; 12 is a sub-county
141 },
142 name => 'county',
143 names => {
144 bd => 'district', cn => 'prefecture', de => 'district', es => 'province',
145 fr => 'department', in => 'district', it => 'province',
146 },
147 # About 100 m. Each outline is simplified alone, so neighbours' shared
148 # borders differ by up to this, which shows as gaps and overlaps now
149 # that each is drawn on its own side of the border; 0.005 (500 m, 2 KB
150 # a county) was 7 pixels out at the zoom a county fills the map, this
151 # (7 KB) under 2.
152 detail => '0.001',
153 },
154 city => {
155 name => 'city',
156 names => { gb => 'district', nz => 'district' },
157 detail => '0.0005', # Thanet 4 KB
158 tries => [
159 { zoom => 10, ranks => [ 12, 16 ], places => 1 },
160 { zoom => 8, ranks => [ 12, 12 ] },
161 ],
162 plans => {
163 nz => [ { zoom => 8, ranks => [ 8, 12 ] } ],
164 },
165 },
166 town => {
167 name => 'town',
168 detail => '0.0002',
169 tries => [
170 { zoom => 12, ranks => [ 13, 18 ], places => 1 },
171 # A parished English town is its civil parish, rank 20, and zoom
172 # 12 there answers with the nearest town mapped as a point.
173 { zoom => 14, ranks => [ 19, 20 ] },
174 ],
175 },
176 neighbourhood => {
177 name => 'neighbourhood',
178 detail => '0.0002', # Westgate-on-Sea 1 KB
179 tries => [ { zoom => 14, ranks => [ 17, 20 ], places => 1 } ],
180 },
181 );
182  
183 # The levels, largest area first: the order a reader chooses from.
184 6 Readonly my @LEVEL_ORDER => qw(country state county city town neighbourhood);
185  
186 # The reverse zoom that asks for each rank. A zoom names the most detailed
187 # rank it may return, so a point with no area at that rank comes back as
188 # something larger (a state), which the rank check turns away rather than
189 # drawing.
190 6 Readonly my %ZOOM_FOR_RANK => (8 => 5, 10 => 6, 12 => 8);
191  
192 6 Readonly my $REVERSE_URL => 'https://nominatim.openstreetmap.org/reverse';
193 # The detail outlines had before levels did (the county's): an outline at it is
194 # kept under its plain key, so a cache from 0.023.0 is still read.
195 6 Readonly my $PLAIN_DETAIL => '0.001';
196 6 Readonly my $DECIMALS => 3; # of a point, in its key and in what is sent
197 6 Readonly my $DEFAULT_MAX => 20; # Nominatim requests in one call, as map_geocode_online_max
198 6 Readonly my $CACHE_DIR => 'boundary-cache'; # under model_dir, for file_cache()
199 6 Readonly my $CACHE_NAMESPACE => __PACKAGE__;
200 6 Readonly my $CACHE_MAX_SIZE => 8 * 1024 * 1024; # bytes, for the process-wide default
201  
202 6 my $json = JSON::PP->new->canonical->utf8;
203  
204 =head1 NAME
205  
206 Database::BI::Model::Boundary - The outline of the area around each map marker
207  
208 =head1 VERSION
209  
210 0.024.0
211  
212 =head1 SYNOPSIS
213  
214 use Database::BI::Model::Boundary;
215  
216 my $boundary = Database::BI::Model::Boundary->new(
217 cache => Database::BI::Model::Boundary->file_cache('.bi'),
218 online => 1,
219 level => 'state', # country, state, county (default), city, town, neighbourhood
220 );
221  
222 my $result = $boundary->outlines([ [ 39.09, -77.64 ], [ 38.85, -77.31 ] ]);
223 $map->add_geojson(
224 { type => 'FeatureCollection', features => $result->{features} },
225 name => 'County boundaries',
226 );
227  
228 # A point the map page listed as pending, looked up on its own
229 my $answer = $boundary->lookup_point($result->{pending}[0]);
230  
231 =head1 DESCRIPTION
232  
233 Finds the area each point is in, at one level, and returns its outline as a GeoJSON
234 Feature, for L<HTML::OSM>'s C<add_geojson>. The outlines come from
235 OpenStreetMap's Nominatim reverse lookup, through the same throttled user agent
236 as the geocoder (L<Database::BI::Model::Geocode/nominatim_ua>), so the two
237 together never ask more than once a second.
238  
239 Only the point is sent, rounded to three decimal places (about 110 metres).
240 Every answer is cached: a point with the outline it is in, and the outline
241 itself. A point inside an outline already known is matched here, without a
242 request, so many points in one county cost one lookup.
243  
244 The levels, largest first:
245  
246 =over 4
247  
248 =item country
249  
250 =item state
251  
252 A US or Indian state, a Canadian province, a New Zealand region, England.
253  
254 =item county
255  
256 The default; see below.
257  
258 =item city
259  
260 A city or the district named after it: Toronto, Manchester, the district of
261 Canterbury, Hamilton City in New Zealand. Where OpenStreetMap has no city round a point, or has the city only as a point
262 (York, Pune), the area at the county's rank there: the unitary authority, the
263 city district, or the county itself.
264  
265 =item town
266  
267 A town or city ward: Margate, Toronto Centre. An English town that is a civil
268 parish (Westgate-on-Sea) is that parish.
269  
270 =item neighbourhood
271  
272 A neighbourhood, suburb or civil parish that OpenStreetMap has as an area.
273 Many suburbs are mapped only as a point, and those have no outline.
274  
275 =back
276  
277 Larger areas are simplified more, so an outline is a few kilobytes at any
278 level.
279  
280 A county here is the division of a country below its states, whose place rank
281 in Nominatim depends on the country: 12 (a US county or independent city, an
282 English county, a German Landkreis, a French departement) unless the country is
283 listed otherwise: 10 for India, Bangladesh, China and Spain (district,
284 prefecture, province), 8 for Kenya. C<ranks> adds or changes countries.
285 Anything else Nominatim answers is taken as "no county here" and remembered as
286 such. A country with nothing at its rank (Australia, Brazil, Japan) gets no
287 outlines.
288  
289 Each reply names the point's country, so a point is asked at the zoom of the
290 last country seen, and asked again when its own country wants another rank.
291 An outline is kept with the rank it was accepted at; when C<ranks> changes, the
292 points it covered are asked again.
293  
294 =head1 METHODS
295  
296 =head2 new
297  
298 my $boundary = Database::BI::Model::Boundary->new(%args);
299  
300 =head3 API SPECIFICATION
301  
302 =head4 INPUT
303  
304 cache : object with get() and set() (CHI) optional; default one
305 CHI Memory cache for the process
306 online : boolean optional, default 0: may Nominatim be asked
307 online_max : integer optional, default 20: requests in one outlines() call
308 level : string optional, default 'county'; one of levels()
309 ranks : hashref optional: { country code => place rank }, over the
310 county level's own list; codes are two letters (any case),
311 ranks 8, 10 or 12. The other levels ignore it
312 ua : object with get() optional: the user agent to ask with
313 (tests); default Geocode::nominatim_ua()
314  
315 =head4 OUTPUT
316  
317 A Database::BI::Model::Boundary object. Croaks on an unknown level, a cache
318 without get and set, or ranks that are not a hash of two-letter codes to 8, 10
319 or 12.
320  
321 =cut
322  
323 78 ▶sub new {
Subroutine new: called CC=10 SCAR=23.1
Pod documented
324 78 my $class = shift;
325 78 ▶ my $raw = Params::Get::get_params(undef, \@_) // {};
Condition100%2/2
Params::Get::get_params(undef, \@_) // {}
l!l
744
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
326  
327 78 my $args = validate_strict(
328 schema => {
329 cache => { type => 'object', optional => 1, default => undef },
330 online => { type => 'boolean', optional => 1, default => 0 },
331 online_max => { type => 'integer', optional => 1, default => $DEFAULT_MAX, min => 0 },
332 level => { type => 'string', optional => 1, default => 'county' },
333 ua => { type => 'object', optional => 1, default => undef, can => 'get' },
334 ranks => { type => 'hashref', optional => 1, default => undef },
335 },
336 input => $raw,
337 );
338  
339 73 ▶ my $level_name = $args->{level} // '';
Condition100%2/2
$$args{"level"} // ""
l!l
721
MC/DC100%1/1
$$args{"level"} // ""
$$args{"level"}
Truth table100%2/2
A
A= $$args{"level"}
Aresult
11
00
340 73 ▶ my $level = $LEVELS{$level_name}
Branch: 1 branch
BranchTrueFalseTotal
my $level = $LEVELS{$level_name} or croak("Unknown boundary level '${level_name}'") 66 7 73
341 or croak "Unknown boundary level '$level_name'";
342 croak 'The boundary cache needs get() and set()'
343 66 ▶ if defined($args->{cache}) && !($args->{cache}->can('get') && $args->{cache}->can('set'));
Branch: 1 branch
BranchTrueFalseTotal
if defined $$args{"cache"} and not $$args{"cache"}->can("get") && $$args{"cache"}->can("set") 1 65 66
Condition83%5/6
defined $$args{"cache"} and not $$args{"cache"}->can("get") && $$args{"cache"}->can("set")
!ll&&!rl&&r
15501
$$args{'cache'}->can('get') && $$args{'cache'}->can('set')
!ll&&!rl&&r
1050
MC/DC66%2/3
defined $$args{"cache"} and not $$args{"cache"}->can("get") && $$args{"cache"}->can("set")
defined $$args{"cache"} $$args{'cache'}->can('get') $$args{'cache'}->can('set')
Truth table75%3/4
A and not(B && C)
A= defined $$args{"cache"}B= $$args{'cache'}->can('get')C= $$args{'cache'}->can('set')
ABCresult
0XX0
1110
10X1
1101
344  
345 return bless {
346 65 %{$args},
347 65 ▶ ranks => { %{ $level->{countries} // {} }, %{ $class->check_ranks($args->{ranks} // {}) } },
Condition85%6/7
$$level{"countries"} // {}
l!l
605
$$args{"ranks"} // {}
l!l
857
$$args{"cache"} // _default_cache()
l!l&&r!l&&!r
50130
MC/DC100%1/1
$$level{"countries"} // {}
$$level{"countries"}
MC/DC100%1/1
$$args{"ranks"} // {}
$$args{"ranks"}
MC/DC0%0/2
$$args{"cache"} // _default_cache()
$$args{"cache"} _default_cache()
Truth table100%2/2
A
A= $$level{"countries"}
Aresult
11
00
Truth table100%2/2
A
A= $$args{"ranks"}
Aresult
11
00
Truth table66%2/3
A // B
A= $$args{"cache"}B= _default_cache()
ABresult
1X1
011
000
348 65 cache => $args->{cache} // _default_cache(),
349 }, $class;
350 }
351  
352 =head2 check_ranks
353  
354 my $ranks = Database::BI::Model::Boundary->check_ranks({ LK => 10 }); # { lk => 10 }
355  
356 =head3 API SPECIFICATION
357  
358 =head4 INPUT
359  
360 ranks : hashref of { country code => place rank }
361 Domains: a code is exactly two ASCII letters (any case); a rank is
362 8, 10 or 12 as a whole number (7, 9, 11, 13, '08' and '8 ' are not)
363  
364 =head4 OUTPUT
365  
366 A new hashref with the codes in lower case and the ranks as numbers. Croaks
367 on a value that is not a hashref, a key that is not a two-letter code, or a
368 rank that is not 8, 10 or 12, naming the entry. Used by C<new> and by the
369 application's startup check of C<map_bounds_ranks>.
370  
371 =cut
372  
373 126 ▶sub check_ranks {
Subroutine check_ranks: called CC=9 SCAR=22.0
Pod documented
374 126 my (undef, $ranks) = @_;
375 126 ▶ croak 'Boundary ranks must be a hash of country codes to place ranks'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ranks eq "HASH" 8 118 126
376 unless ref($ranks) eq 'HASH';
377 118 my %checked;
378 118 for my $code (sort keys %{$ranks}) {
379 68 my $rank = $ranks->{$code};
380 68 ▶ croak "'$code' is not a two-letter country code" unless $code =~ /\A[A-Za-z]{2}\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $code =~ /\A[A-Za-z]{2}\z/ 15 53 68
381 68 croak "the rank for '$code' must be one of " . join(', ', sort { $a <=> $b } keys %ZOOM_FOR_RANK)
382 53 ▶ unless defined($rank) && !ref($rank) && $rank =~ /\A[0-9]+\z/ && $ZOOM_FOR_RANK{$rank};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $ZOOM_FOR_RANK{$rank} 26 27 53
Condition100%9/9
defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $ZOOM_FOR_RANK{$rank}
!ll&&!rl&&r
161027
defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/
!ll&&!rl&&r
51137
defined $rank and not ref $rank
!ll&&!rl&&r
2348
MC/DC100%4/4
defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $ZOOM_FOR_RANK{$rank}
defined $rank not ref $rank $rank =~ /\A[0-9]+\z/ $ZOOM_FOR_RANK{$rank}
Truth table100%5/5
A and not(B) and C and D
A= defined $rankB= not ref $rankC= $rank =~ /\A[0-9]+\z/D= $ZOOM_FOR_RANK{$rank}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
383 27 ▶ croak "'$code' is given twice" if exists $checked{ lc $code };
Branch: 1 branch
BranchTrueFalseTotal
if exists $checked{lc $code} 3 24 27
384 24 $checked{ lc $code } = $rank + 0;
385 }
386 74 return \%checked;
387 }
388  
389 =head2 rank_for
390  
391 my $rank = $boundary->rank_for('in'); # 10
392  
393 =head3 API SPECIFICATION
394  
395 =head4 INPUT
396  
397 country : string, an ISO 3166-1 alpha-2 code in any case; undef or ''
398 for a point in no country (the sea)
399  
400 =head4 OUTPUT
401  
402 The place rank an outline in that country must have at the county level: the
403 country's own, from C<ranks> or the built-in list, else 12. At another level,
404 the most detailed rank its first try takes there.
405  
406 =cut
407  
408 17 ▶sub rank_for {
Subroutine rank_for: called CC=6 SCAR=17.9
Pod documented
409 17 my ($self, $country) = @_;
410 17 my $level = $LEVELS{ $self->{level} };
411 17 ▶ return $self->_plan($country)->[0]{ranks}[1] unless defined $level->{rank};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$level{"rank"} 2 15 17
412 my $rank = (defined($country) && !ref($country) && length($country))
413 15 ▶ ? $self->{ranks}{ lc $country } : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $country && !ref($country) && length $country ? : 10 5 15
Condition100%6/6
defined $country and not ref $country and length $country
!ll&&!rl&&r
4110
defined $country and not ref $country
!ll&&!rl&&r
2211
MC/DC100%3/3
defined $country and not ref $country and length $country
defined $country not ref $country length $country
Truth table100%4/4
A and not(B) and C
A= defined $countryB= not ref $countryC= length $country
ABCresult
0XX0
10X0
1100
1111
414 15 ▶ return $rank // $level->{rank};
Condition66%2/3
$rank // $$level{"rank"}
l!l&&r!l&&!r
870
MC/DC0%0/2
$rank // $$level{"rank"}
$rank $$level{"rank"}
Truth table66%2/3
A // B
A= $rankB= $$level{"rank"}
ABresult
1X1
011
000
415 }
416  
417 =head2 name_for
418  
419 my $word = $boundary->name_for('in'); # 'district'
420  
421 What this object's level is called in a country, so a caller can say
422 "district" on a map of India rather than "county".
423  
424 =head3 API SPECIFICATION
425  
426 =head4 INPUT
427  
428 country : string, an ISO 3166-1 alpha-2 code in any case; undef or ''
429 for a point in no country
430  
431 =head4 OUTPUT
432  
433 One lower-case English word: C<country>, C<state>, C<region>, C<province>,
434 C<prefecture>, C<county>, C<district>, C<department>, C<city>, C<town> or
435 C<neighbourhood>. A country not listed gets the level's own name
436 (L</level_name>). It is a word to look a translation up by, not text to show.
437 Called on the class, it answers for the county level.
438  
439 =cut
440  
441 61 ▶sub name_for {
Subroutine name_for: called CC=7 SCAR=19.5
Pod documented
442 61 my ($self, $country) = @_;
443 61 ▶ my $level = $LEVELS{ ref($self) ? $self->{level} : 'county' };
Branch: 1 branch
BranchTrueFalseTotal
ref $self ? : 42 19 61
444 my $name = (defined($country) && !ref($country) && length($country))
445 61 ▶ ? ($level->{names} // {})->{ lc $country } : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $country && !ref($country) && length $country ? : 17 44 61
Condition87%7/8
defined $country and not ref $country and length $country
!ll&&!rl&&r
53917
defined $country and not ref $country
!ll&&!rl&&r
2356
$$level{"names"} // {}
l!l
170
MC/DC100%3/3
defined $country and not ref $country and length $country
defined $country not ref $country length $country
MC/DC0%0/1
$$level{"names"} // {}
$$level{"names"}
Truth table100%4/4
A and not(B) and C
A= defined $countryB= not ref $countryC= length $country
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $$level{"names"}
Aresult
11
00
446 61 ▶ return $name // $level->{name};
Condition66%2/3
$name // $$level{"name"}
l!l
11500
MC/DC0%0/2
$name // $$level{"name"}
$name $$level{"name"}
Truth table66%2/3
A // B
A= $nameB= $$level{"name"}
ABresult
1X1
011
000
447 }
448  
449 =head2 level_name
450  
451 my $word = Database::BI::Model::Boundary->level_name('state'); # 'state'
452  
453 =head3 API SPECIFICATION
454  
455 =head4 INPUT
456  
457 level : string, one of levels()
458  
459 =head4 OUTPUT
460  
461 What the level's areas are called where no country says otherwise, as
462 L</name_for> gives it: the word to use before a point's country is known.
463 Undef for a level that is not one.
464  
465 =cut
466  
467 115 ▶sub level_name {
Subroutine level_name: called CC=4 SCAR=13.9
Pod documented
468 115 my (undef, $level) = @_;
469 115 ▶ return unless defined($level) && !ref($level) && $LEVELS{$level};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $level and not ref $level and $LEVELS{$level} 82 33 115
Condition100%6/6
defined $level and not ref $level and $LEVELS{$level}
!ll&&!rl&&r
74833
defined $level and not ref $level
!ll&&!rl&&r
71341
MC/DC100%3/3
defined $level and not ref $level and $LEVELS{$level}
defined $level not ref $level $LEVELS{$level}
Truth table100%4/4
A and not(B) and C
A= defined $levelB= not ref $levelC= $LEVELS{$level}
ABCresult
0XX0
10X0
1100
1111
470 33 return $LEVELS{$level}{name};
471 }
472  
473 =head2 levels
474  
475 my @levels = Database::BI::Model::Boundary->levels;
476 # ('country', 'state', 'county', 'city', 'town', 'neighbourhood')
477  
478 =head3 API SPECIFICATION
479  
480 =head4 INPUT
481  
482 None.
483  
484 =head4 OUTPUT
485  
486 The names of the levels new() takes, the largest area first.
487  
488 =cut
489  
490 27 ▶sub levels {
Subroutine levels: called CC=1 SCAR=0.0
Pod documented
491 27 return @LEVEL_ORDER;
492 }
493  
494 =head2 point_key
495  
496 my $key = Database::BI::Model::Boundary->point_key(39.0901, -77.6402); # '39.090,-77.640'
497  
498 =head3 API SPECIFICATION
499  
500 =head4 INPUT
501  
502 lat : number -90 .. 90
503 lon : number -180 .. 180
504  
505 Domains: each is a plain decimal, an optional minus and ASCII digits with an
506 optional fraction (1, -1.5, 12.345678). A plus sign, a bare point (.5, 5.),
507 an exponent, spaces, a newline, a comma, NaN, Inf and non-ASCII digits are
508 not numbers here. The edges -90, 90, -180 and 180 are in; anything past
509 them, however slightly (90.0001), is out, even if it would round to an edge.
510  
511 =head4 OUTPUT
512  
513 The point rounded to three decimal places, as C<"lat,lon">: what the cache is
514 keyed by and all of the point that is sent. Undef for a point out of range.
515  
516 =cut
517  
518 100370 ▶sub point_key {
Subroutine point_key: called CC=7 SCAR=19.5
Pod documented
519 100370 my (undef, $lat, $lon) = @_;
520  
521 100370 ▶ return unless defined($lat) && defined($lon)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lat and defined $lon and $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and abs $lat <= 90 and abs $lon <= 180 64 100306 100370
Condition100%15/15
defined $lat and defined $lon and $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and abs $lat <= 90 and abs $lon <= 180
!ll&&!rl&&r
586100306
defined $lat and defined $lon and $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and abs $lat <= 90
!ll&&!rl&&r
499100312
defined $lat and defined $lon and $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/
!ll&&!rl&&r
445100321
defined $lat and defined $lon and $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/
!ll&&!rl&&r
1628100326
defined $lat and defined $lon
!ll&&!rl&&r
97100354
MC/DC100%6/6
defined $lat and defined $lon and $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ and abs $lat <= 90 and abs $lon <= 180
defined $lat defined $lon $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ abs $lat <= 90 abs $lon <= 180
Truth table100%7/7
A and B and C and D and E and F
A= defined $latB= defined $lonC= $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/D= $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/E= abs $lat <= 90F= abs $lon <= 180
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
522 && $lat =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/ && $lon =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/
523 && abs($lat) <= 90 && abs($lon) <= 180;
524  
525 my @parts = map {
526 100306 my $text = sprintf("%.${DECIMALS}f", $_);
527 200612 $text =~ s/\A-(?=0\.0+\z)//; # no "-0.000", so a point has one key
528 200612 $text;
529 } ($lat, $lon);
530 100306 return join(',', @parts);
531 }
532  
533 =head2 outlines
534  
535 my $result = $boundary->outlines(\@points, lookup => 1);
536  
537 =head3 API SPECIFICATION
538  
539 =head4 INPUT
540  
541 points : arrayref of [lat, lon]
542 lookup : boolean, default 1. 0 asks Nominatim nothing: the points not
543 known yet come back in pending, for the caller to look up one at
544 a time (lookup_point)
545  
546 =head4 OUTPUT
547  
548 {
549 features => [ GeoJSON Feature, ... ] one per outline, in the order
550 their first point came; properties { name, osm, called }
551 (called: what the division is called there, as name_for)
552 pending => [ point_key, ... ] points not known, not asked
553 inside => { point_key => osm, ... } the outline each point drawn is in,
554 by the osm of its Feature (to total what is in each)
555 counts => { points, drawn, attempted, nowhere }
556 offline => 0|1 points were left because Nominatim may not be asked
557 failed => 0|1 Nominatim did not answer; the rest were left
558 }
559  
560 A point out of range is ignored. A Feature's name is the place's name as
561 OpenStreetMap has it: text, not HTML.
562  
563 =cut
564  
565 53 ▶sub outlines {
Subroutine outlines: called CC=23 SCAR=31.4
Pod documented
566 53 my ($self, $points, @rest) = @_;
567 53 ▶ croak 'outlines() needs an arrayref of [lat, lon]' unless ref($points) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $points eq "ARRAY" 5 48 53
568 48 my %opt = @rest;
569 48 ▶ my $lookup = exists($opt{lookup}) ? $opt{lookup} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $opt{'lookup'} ? : 38 10 48
570  
571 48 local ($@, $!);
572  
573 48 my (@keys, %seen);
574 48 for my $point (@{$points}) {
575 100108 ▶ next unless ref($point) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $point eq "ARRAY" 3 100105 100108
576 100105 my $key = $self->point_key(@{$point}[0, 1]);
577 100105 ▶ push @keys, $key if defined($key) && !$seen{$key}++;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key and not $seen{$key}++ 100093 12 100105
Condition66%2/3
defined $key and not $seen{$key}++
!ll&&!rl&&r
120100093
MC/DC50%1/2
defined $key and not $seen{$key}++
defined $key not $seen{$key}++
Truth table66%2/3
A and not(B)
A= defined $keyB= not $seen{$key}++
ABresult
0X0
100
111
578 }
579  
580 48 my %counts = (points => scalar(@keys), drawn => 0, attempted => 0, nowhere => 0);
581 48 my (@order, %used, %inside, @pending, $failed, $offline);
582 48 my $index = $self->_index;
583  
584 48 for my $key (@keys) {
585 100093 my ($osm, $status) = $self->_known($key, $index);
586 100093 ▶ if (!defined($status) && $lookup) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $status and $lookup) 73 100020 100093
Condition100%3/3
not defined $status and $lookup
!ll&&!rl&&r
1210000873
MC/DC100%2/2
not defined $status and $lookup
not defined $status $lookup
Truth table100%3/3
not(A) and B
A= not defined $statusB= $lookup
ABresult
0X0
100
111
587 73 ▶ if (!$self->_can_ask) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $self->_can_ask) { } 3 70 73
elsif (not $failed and $counts{'attempted'} < $$self{'online_max'}) { } 38 44 82
588 3 $offline = 1;
589 ▶ } elsif (!$failed && $counts{attempted} < $self->{online_max}) {
Condition100%3/3
not $failed and $counts{"attempted"} < $$self{"online_max"}
!ll&&!rl&&r
122038
MC/DC100%2/2
not $failed and $counts{"attempted"} < $$self{"online_max"}
not $failed $counts{"attempted"} < $$self{"online_max"}
Truth table100%3/3
not(A) and B
A= not $failedB= $counts{"attempted"} < $$self{"online_max"}
ABresult
0X0
100
111
590 38 $counts{attempted}++;
591 38 ($osm, $status) = $self->_ask($key, $index);
592 38 ▶ $failed = 1 if $status eq 'failed';
Branch: 1 branch
BranchTrueFalseTotal
if $status eq "failed" 10 28 38
593 }
594 }
595 100093 ▶ if (!defined($status) || $status eq 'failed') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $status or $status eq "failed") 100053 40 100093
Condition100%3/3
not defined $status or $status eq "failed"
l!l&&r!l&&!r
1000431040
MC/DC100%2/2
not defined $status or $status eq "failed"
not defined $status $status eq "failed"
Truth table100%3/3
not(A) or B
A= not defined $statusB= $status eq "failed"
ABresult
1X1
011
000
596 100053 push @pending, $key;
597 100053 next;
598 }
599 40 ▶ if ($status eq 'nowhere') {
Branch: 1 branch
BranchTrueFalseTotal
if ($status eq "nowhere") 3 37 40
600 3 $counts{nowhere}++;
601 3 next;
602 }
603 37 ▶ push @order, $osm unless $used{$osm}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $used{$osm}++ 37 0 37
604 37 $inside{$key} = $osm;
605 }
606  
607 48 my @features;
608 48 for my $osm (@order) {
609 37 ▶ my $outline = $self->_get($self->_outline_key($osm)) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $outline = $self->_get($self->_outline_key($osm)) or next 37 0 37
610 push @features, {
611 type => 'Feature',
612 properties => { name => $outline->{name}, osm => $osm,
613 called => $self->name_for($outline->{country}) },
614 # A copy: the cache may hand out the one it holds (an in-memory
615 # layer does), and a caller that changes its result must not change
616 # what the next one is given.
617 37 ▶ geometry => (ref($outline->{geometry}) ? dclone($outline->{geometry}) : $outline->{geometry}),
Branch: 1 branch
BranchTrueFalseTotal
ref $$outline{'geometry'} ? : 35 2 37
618 };
619 }
620 48 $counts{drawn} = scalar @features;
621 48 my %drawn = map { $_->{properties}{osm} => 1 } @features;
622 48 delete @inside{ grep { !$drawn{ $inside{$_} } } keys %inside };
623  
624 return {
625 48 ▶ features => \@features,
Branch: 2 branches
BranchTrueFalseTotal
$offline ? : 2 46 48
$failed ? : 10 38 48
626 pending => \@pending,
627 inside => \%inside,
628 counts => \%counts,
629 offline => $offline ? 1 : 0,
630 failed => $failed ? 1 : 0,
631 };
632 }
633  
634 =head2 lookup_point
635  
636 my $answer = $boundary->lookup_point('39.090,-77.640');
637  
638 =head3 API SPECIFICATION
639  
640 =head4 INPUT
641  
642 key : string, a point_key
643  
644 =head4 OUTPUT
645  
646 { status => 'found' | 'nowhere' | 'held', name => string|undef, asked => 0|1 }
647  
648 'found' and 'nowhere' are remembered. 'held' is a point that could not be
649 settled now - Nominatim did not answer, or may not be asked - and is asked
650 again next time. asked says whether Nominatim was asked. Croaks on a key
651 that is not a point_key.
652  
653 =cut
654  
655 42 ▶sub lookup_point {
Subroutine lookup_point: called CC=12 SCAR=24.8
Pod documented
656 42 my ($self, $key) = @_;
657  
658 42 ▶ croak 'lookup_point() needs a point key such as 39.090,-77.640'
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key and not ref $key and $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/ and defined $self->point_key($1, $2) and $self->point_key($1, $2) eq $key 16 26 42
Condition100%12/12
defined $key and not ref $key and $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/ and defined $self->point_key($1, $2) and $self->point_key($1, $2) eq $key
!ll&&!rl&&r
15126
defined $key and not ref $key and $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/ and defined $self->point_key($1, $2)
!ll&&!rl&&r
13227
defined $key and not ref $key and $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/
!ll&&!rl&&r
31029
defined $key and not ref $key
!ll&&!rl&&r
1239
MC/DC100%5/5
defined $key and not ref $key and $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/ and defined $self->point_key($1, $2) and $self->point_key($1, $2) eq $key
defined $key not ref $key $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/ defined $self->point_key($1, $2) $self->point_key($1, $2) eq $key
Truth table100%6/6
A and not(B) and C and D and E
A= defined $keyB= not ref $keyC= $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/D= defined $self->point_key($1, $2)E= $self->point_key($1, $2) eq $key
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
659 unless defined($key) && !ref($key)
660 && $key =~ /\A(-?[0-9]{1,2}\.[0-9]{$DECIMALS}),(-?[0-9]{1,3}\.[0-9]{$DECIMALS})\z/
661 && defined($self->point_key($1, $2)) && $self->point_key($1, $2) eq $key;
662  
663 26 local ($@, $!);
664  
665 26 my $index = $self->_index;
666 26 my ($osm, $status) = $self->_known($key, $index);
667 26 my $asked = 0;
668 26 ▶ if (!defined($status) && $self->_can_ask) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $status and $self->_can_ask) 16 10 26
Condition100%3/3
not defined $status and $self->_can_ask
!ll&&!rl&&r
3716
MC/DC100%2/2
not defined $status and $self->_can_ask
not defined $status $self->_can_ask
Truth table100%3/3
not(A) and B
A= not defined $statusB= $self->_can_ask
ABresult
0X0
100
111
669 16 $asked = 1;
670 16 ($osm, $status) = $self->_ask($key, $index);
671 }
672  
673 26 ▶ return { status => 'held', name => undef, asked => $asked }
Branch: 1 branch
BranchTrueFalseTotal
if not defined $status or $status eq "failed" 9 17 26
Condition100%3/3
not defined $status or $status eq "failed"
l!l&&r!l&&!r
7217
MC/DC100%2/2
not defined $status or $status eq "failed"
not defined $status $status eq "failed"
Truth table100%3/3
not(A) or B
A= not defined $statusB= $status eq "failed"
ABresult
1X1
011
000
674 if !defined($status) || $status eq 'failed';
675 17 ▶ return { status => 'nowhere', name => undef, asked => $asked } if $status eq 'nowhere';
Branch: 1 branch
BranchTrueFalseTotal
if $status eq "nowhere" 2 15 17
676  
677 15 my $outline = $self->_get($self->_outline_key($osm));
678 15 ▶ return { status => 'found', name => ($outline ? $outline->{name} : undef), asked => $asked };
Branch: 1 branch
BranchTrueFalseTotal
$outline ? : 13 2 15
679 }
680  
681 =head2 file_cache
682  
683 my $cache = Database::BI::Model::Boundary->file_cache($model_dir);
684  
685 =head3 API SPECIFICATION
686  
687 =head4 INPUT
688  
689 dir : string, an existing directory (model_dir)
690  
691 =head4 OUTPUT
692  
693 A CHI File cache under C<< <dir>/boundary-cache >>, with a copy of what it
694 reads in memory for as long as the cache object lives. Croaks when dir is not a directory.
695  
696 =cut
697  
698 44 ▶sub file_cache {
Subroutine file_cache: called CC=5 SCAR=16.1
Pod documented
699 44 my (undef, $dir) = @_;
700  
701 44 ▶ croak 'The boundary cache needs a directory, not ' . (defined($dir) ? $dir : 'undef')
Branch: 2 branches
BranchTrueFalseTotal
unless defined $dir and not ref $dir and -d $dir 4 40 44
defined $dir ? : 3 1 4
Condition100%6/6
defined $dir and not ref $dir and -d $dir
!ll&&!rl&&r
2240
defined $dir and not ref $dir
!ll&&!rl&&r
1142
MC/DC100%3/3
defined $dir and not ref $dir and -d $dir
defined $dir not ref $dir -d $dir
Truth table100%4/4
A and not(B) and C
A= defined $dirB= not ref $dirC= -d $dir
ABCresult
0XX0
10X0
1100
1111
702 unless defined($dir) && !ref($dir) && -d $dir;
703  
704 40 require CHI;
705 40 require File::Spec;
706 40 return CHI->new(
707 driver => 'File',
708 root_dir => File::Spec->catdir($dir, $CACHE_DIR),
709 namespace => $CACHE_NAMESPACE,
710 # A copy in memory for this object, which a request makes afresh: it
711 # saves reading the index and outlines again within the request. Not
712 # global, which would share it with every cache of this namespace in
713 # the process, whatever its folder, and keep a worker from seeing
714 # what another has added since.
715 l1_cache => { driver => 'RawMemory', global => 0, max_size => $CACHE_MAX_SIZE },
716 );
717 }
718  
719 # ---------------------------------------------------------------------------
720 # Private
721 # ---------------------------------------------------------------------------
722  
723 6 my $default_cache;
724  
725 13 ▶sub _default_cache {
Subroutine _default_cache: called CC=2 SCAR=7.0
726 13 require CHI;
727 13 ▶ $default_cache //= CHI->new(
Condition66%2/3
$default_cache //= "CHI"->new("driver", "Memory", "global", 1, "namespace", $CACHE_NAMESPACE, "max_size", $CACHE_MAX_SIZE)
l!l&&r!l&&!r
1030
MC/DC0%0/2
$default_cache //= "CHI"->new("driver", "Memory", "global", 1, "namespace", $CACHE_NAMESPACE, "max_size", $CACHE_MAX_SIZE)
$default_cache "CHI"->new("driver", "Memory", "global", 1, "namespace", $CACHE_NAMESPACE, "max_size", $CACHE_MAX_SIZE)
Truth table66%2/3
A //= B
A= $default_cacheB= "CHI"->new("driver", "Memory", "global", 1, "namespace", $CACHE_NAMESPACE, "max_size", $CACHE_MAX_SIZE)
ABresult
1X1
011
000
728 driver => 'Memory',
729 global => 1,
730 namespace => $CACHE_NAMESPACE,
731 max_size => $CACHE_MAX_SIZE,
732 );
733 13 return $default_cache;
734 }
735  
736 # _get($key) / _set($key, $value): the cache, under this level's prefix for a
737 # point and under _outline_key for an outline. A cache that fails reads as empty and writes as nothing: the page
738 # still draws, and asks again next time.
739 100339 ▶sub _get {
Subroutine _get: called CC=1 SCAR=0.0
740 100339 my ($self, $key) = @_;
741 100339 my $value = eval { $self->{cache}->get($key) };
742 100339 return $value;
743 }
744  
745 121 ▶sub _set {
Subroutine _set: called CC=1 SCAR=0.0
746 121 my ($self, $key, $value) = @_;
747 121 return eval { $self->{cache}->set($key, $value, 'never'); 1 };
748 }
749  
750 100161 ▶sub _point_cache_key {
Subroutine _point_cache_key: called CC=1 SCAR=0.0
751 100161 my ($self, $key) = @_;
752 100161 return "point:$self->{level}:$key";
753 }
754  
755 # _detail() -> how far this level's outlines are simplified, as text
756 232 ▶sub _detail {
Subroutine _detail: called CC=1 SCAR=0.0
757 232 my $self = shift;
758 232 return $LEVELS{ $self->{level} }{detail};
759 }
760  
761 # _outline_key($osm) -> the cache key of an outline at this level's detail.
762 # One relation is one outline at every level of the same detail, and a copy
763 # apiece where they differ, so two levels never fetch over each other's.
764 110 ▶sub _outline_key {
Subroutine _outline_key: called CC=2 SCAR=7.1
765 110 my ($self, $osm) = @_;
766 110 my $detail = $self->_detail;
767 110 ▶ return $detail eq $PLAIN_DETAIL ? "outline:$osm" : "outline:$osm:$detail";
Branch: 1 branch
BranchTrueFalseTotal
$detail eq $PLAIN_DETAIL ? : 110 0 110
768 }
769  
770 # _plan($country) -> arrayref of tries { zoom, ranks => [low, high], places }
771 #
772 # How this level is asked for in a country (undef or '' for none known): the
773 # county level's one rank at the zoom that asks for it, else the level's
774 # tries, or the country's own.
775 85 ▶sub _plan {
Subroutine _plan: called CC=7 SCAR=19.5
776 85 my ($self, $country) = @_;
777 85 my $level = $LEVELS{ $self->{level} };
778 85 ▶ $country = (defined($country) && !ref($country)) ? lc($country) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $country && !ref($country) ? : 78 7 85
Condition100%3/3
defined $country and not ref $country
!ll&&!rl&&r
6178
MC/DC100%2/2
defined $country and not ref $country
defined $country not ref $country
Truth table100%3/3
A and not(B)
A= defined $countryB= not ref $country
ABresult
0X0
100
111
779 85 ▶ if (defined $level->{rank}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$level{"rank"}) 78 7 85
780 78 ▶ my $rank = $self->{ranks}{$country} // $level->{rank};
Condition66%2/3
$$self{"ranks"}{$country} // $$level{"rank"}
l!l&&r!l&&!r
2760
MC/DC0%0/2
$$self{"ranks"}{$country} // $$level{"rank"}
$$self{"ranks"}{$country} $$level{"rank"}
Truth table66%2/3
A // B
A= $$self{"ranks"}{$country}B= $$level{"rank"}
ABresult
1X1
011
000
781 78 return [ { zoom => $ZOOM_FOR_RANK{$rank}, ranks => [ $rank, $rank ] } ];
782 }
783 7 ▶ return ($level->{plans} // {})->{$country} // $level->{tries};
Condition80%4/5
($$level{"plans"} // {})->{$country} // $$level{"tries"}
l!l&&r!l&&!r
160
$$level{"plans"} // {}
l!l
52
MC/DC0%0/2
($$level{"plans"} // {})->{$country} // $$level{"tries"}
$$level{"plans"} $$level{"tries"}
Truth table66%2/3
A // B
A= $$level{"plans"}B= $$level{"tries"}
ABresult
1X1
011
000
784 }
785  
786 # _plan_sig(\@plan) -> the plan as text, kept with a point found nowhere so a
787 # changed plan asks again.
788 5 ▶sub _plan_sig {
Subroutine _plan_sig: called CC=2 SCAR=7.0
789 5 my $plan = shift;
790 5 ▶ return join(';', map { "$_->{zoom}:$_->{ranks}[0]-$_->{ranks}[1]" . ($_->{places} ? ':p' : '') } @{$plan});
Branch: 1 branch
BranchTrueFalseTotal
$$_{'places'} ? : 0 5 5
791 }
792  
793 # _accepts(\@plan, $rank) -> 1 when some try of the plan takes that rank
794 16 ▶sub _accepts {
Subroutine _accepts: called CC=2 SCAR=6.9
795 16 my ($plan, $rank) = @_;
796 16 ▶ return (first { $rank >= $_->{ranks}[0] && $rank <= $_->{ranks}[1] } @{$plan}) ? 1 : 0;
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 2 branches
BranchTrueFalseTotal
&first(sub { $rank >= $$_{'ranks'}[0] and $rank <= $$_{'ranks'}[1]; } , @{$plan;}) ? : 15 1 16
$rank >= $$_{"ranks"}[0] and $rank <= $$_{"ranks"}[1] 15 1 16
797 }
798  
799 # _index() -> arrayref of [osm, south, west, north, east]
800 #
801 # The bounding box of every outline this level has found, so a point can be
802 # tested against the few that could hold it. Two processes adding at once can
803 # lose one's entry; that costs a request later, not a wrong answer.
804 112 ▶sub _index {
Subroutine _index: called CC=2 SCAR=6.9
805 112 my $self = shift;
806 112 my $index = $self->_get("index:$self->{level}");
807 112 ▶ return ref($index) eq 'ARRAY' ? [ @{$index} ] : [];
Branch: 1 branch
BranchTrueFalseTotal
ref $index eq 'ARRAY' ? : 44 68 112
808 }
809  
810 # _known($key, \@index) -> ($osm, $status) or ()
811 #
812 # What is known of a point without asking: remembered with an outline or with
813 # none, or inside an outline the index holds (which is then remembered).
814 100119 ▶sub _known {
Subroutine _known: called CC=20 SCAR=32.1
815 100119 my ($self, $key, $index) = @_;
816  
817 100119 my $remembered = $self->_get($self->_point_cache_key($key));
818 100119 ▶ if (ref($remembered) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $remembered eq 'HASH') { } 1 100118 100119
elsif (defined $remembered and length $remembered) { } 19 200198 200217
819 # Nowhere, by the plan its country had then. 0.023.0 kept the rank
820 # alone, which names a county plan.
821 1 my $sig = $remembered->{plan};
822 $sig //= "$ZOOM_FOR_RANK{ $remembered->{rank} }:$remembered->{rank}-$remembered->{rank}"
823 1 ▶ if defined($remembered->{rank}) && $ZOOM_FOR_RANK{ $remembered->{rank} };
Branch: 1 branch
BranchTrueFalseTotal
if defined $$remembered{"rank"} and $ZOOM_FOR_RANK{$$remembered{"rank"}} 1 0 1
Condition40%2/5
defined $$remembered{"rank"} and $ZOOM_FOR_RANK{$$remembered{"rank"}}
!ll&&!rl&&r
001
$sig //= qq[$ZOOM_FOR_RANK{$$remembered{"rank"}}:$$remembered{"rank"}-$$remembered{"rank"}]
l!l
10
MC/DC0%0/2
defined $$remembered{"rank"} and $ZOOM_FOR_RANK{$$remembered{"rank"}}
defined $$remembered{"rank"} $ZOOM_FOR_RANK{$$remembered{"rank"}}
MC/DC0%0/1
$sig //= qq[$ZOOM_FOR_RANK{$$remembered{"rank"}}:$$remembered{"rank"}-$$remembered{"rank"}]
$sig
Truth table33%1/3
A and B
A= defined $$remembered{"rank"}B= $ZOOM_FOR_RANK{$$remembered{"rank"}}
ABresult
0X0
100
111
Truth table50%1/2
A
A= $sig
Aresult
11
00
824 return (undef, 'nowhere')
825 1 ▶ if defined($sig) && $sig eq _plan_sig($self->_plan($remembered->{country}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $sig and $sig eq _plan_sig($self->_plan($$remembered{"country"})) 1 0 1
Condition33%1/3
defined $sig and $sig eq _plan_sig($self->_plan($$remembered{"country"}))
!ll&&!rl&&r
001
MC/DC0%0/2
defined $sig and $sig eq _plan_sig($self->_plan($$remembered{"country"}))
defined $sig $sig eq _plan_sig($self->_plan($$remembered{"country"}))
Truth table33%1/3
A and B
A= defined $sigB= $sig eq _plan_sig($self->_plan($$remembered{"country"}))
ABresult
0X0
100
111
826 ▶ } elsif (defined($remembered) && length($remembered)) {
Condition66%2/3
defined $remembered and length $remembered
!ll&&!rl&&r
100099019
MC/DC50%1/2
defined $remembered and length $remembered
defined $remembered length $remembered
Truth table66%2/3
A and B
A= defined $rememberedB= length $remembered
ABresult
0X0
100
111
827 19 ▶ return ($remembered, 'found') if $self->_current($self->_get($self->_outline_key($remembered)));
Branch: 1 branch
BranchTrueFalseTotal
if $self->_current($self->_get($self->_outline_key($remembered))) 14 5 19
828 # The outline has gone from the cache, or its country's rank changed.
829 }
830 # '' is nowhere from before ranks were kept: ask again.
831  
832 100104 my ($lat, $lon) = split /,/, $key;
833 100104 for my $entry (@{$index}) {
834 # A damaged index entry (not five defined values) knows no outline.
835 285 ▶ next unless ref($entry) eq 'ARRAY' && 5 == grep { defined && !ref } @{$entry}[0 .. 4];
Branch: 1 branch
BranchTrueFalseTotal
unless ref $entry eq "ARRAY" and 5 == grep({defined $_ and not ref $_;} @{$entry;}[0..4]) 2 283 285
Condition83%5/6
ref $entry eq "ARRAY" and 5 == grep({defined $_ and not ref $_;} @{$entry;}[0..4])
!ll&&!rl&&r
02283
defined $_ && !ref($_)
!ll&&!rl&&r
821415
MC/DC50%1/2
ref $entry eq "ARRAY" and 5 == grep({defined $_ and not ref $_;} @{$entry;}[0..4])
ref $entry eq "ARRAY" 5 == grep({defined $_ and not ref $_;} @{$entry;}[0..4])
MC/DC100%2/2
defined $_ && !ref($_)
defined $_ !ref($_)
Truth table66%2/3
A and B
A= ref $entry eq "ARRAY"B= 5 == grep({defined $_ and not ref $_;} @{$entry;}[0..4])
ABresult
0X0
100
111
Truth table100%3/3
A && not(B)
A= defined $_B= !ref($_)
ABresult
0X0
100
111
836 283 my ($osm, $south, $west, $north, $east) = @{$entry};
837 283 ▶ next if $lat < $south || $lat > $north || $lon < $west || $lon > $east;
Branch: 1 branch
BranchTrueFalseTotal
if $lat < $south or $lat > $north or $lon < $west or $lon > $east 282 1 283
Condition88%8/9
$lat < $south or $lat > $north or $lon < $west or $lon > $east
l!l&&r!l&&!r
911911
$lat < $south or $lat > $north or $lon < $west
l!l&&r!l&&!r
910192
$lat < $south or $lat > $north
l!l&&r!l&&!r
289192
MC/DC75%3/4
$lat < $south or $lat > $north or $lon < $west or $lon > $east
$lat < $south $lat > $north $lon < $west $lon > $east
Truth table80%4/5
A or B or C or D
A= $lat < $southB= $lat > $northC= $lon < $westD= $lon > $east
ABCDresult
1XXX1
01XX1
001X1
00011
00000
838 1 my $outline = $self->_get($self->_outline_key($osm));
839 1 ▶ next unless $self->_current($outline) && _contains($outline->{geometry}, $lat, $lon);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_current($outline) and _contains($$outline{"geometry"}, $lat, $lon) 1 0 1
Condition33%1/3
$self->_current($outline) and _contains($$outline{"geometry"}, $lat, $lon)
!ll&&!rl&&r
100
MC/DC0%0/2
$self->_current($outline) and _contains($$outline{"geometry"}, $lat, $lon)
$self->_current($outline) _contains($$outline{"geometry"}, $lat, $lon)
Truth table33%1/3
A and B
A= $self->_current($outline)B= _contains($$outline{"geometry"}, $lat, $lon)
ABresult
0X0
100
111
840 0 $self->_set($self->_point_cache_key($key), $osm);
841 0 return ($osm, 'found');
842 }
843  
844 100104 return;
845 }
846  
847 # _current($outline) -> 1 when an outline was accepted at the rank its country
848 # wants now, and simplified as outlines are now. One kept before ranks were
849 # (no rank), or at another level of detail, is not.
850 27 ▶sub _current {
Subroutine _current: called CC=5 SCAR=16.1
851 27 my ($self, $outline) = @_;
852 27 ▶ return 0 unless ref($outline) eq 'HASH' && defined($outline->{rank});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $outline eq "HASH" and defined $$outline{"rank"} 9 18 27
Condition100%3/3
ref $outline eq "HASH" and defined $$outline{"rank"}
!ll&&!rl&&r
8118
MC/DC100%2/2
ref $outline eq "HASH" and defined $$outline{"rank"}
ref $outline eq "HASH" defined $$outline{"rank"}
Truth table100%3/3
A and B
A= ref $outline eq "HASH"B= defined $$outline{"rank"}
ABresult
0X0
100
111
853 18 ▶ return 0 unless ($outline->{detail} // '') eq $self->_detail;
Branch: 1 branch
BranchTrueFalseTotal
unless ($$outline{"detail"} // "") eq $self->_detail 2 16 18
Condition100%2/2
$$outline{"detail"} // ""
l!l
171
MC/DC100%1/1
$$outline{"detail"} // ""
$$outline{"detail"}
Truth table100%2/2
A
A= $$outline{"detail"}
Aresult
11
00
854 16 return _accepts($self->_plan($outline->{country}), $outline->{rank});
855 }
856  
857 # _last_country() / _last_country($code): the country of the last reply at
858 # this level, whose rank the next point is asked at first. Kept in the cache,
859 # so the first point of a later map is not asked twice.
860 58 ▶sub _last_country {
Subroutine _last_country: called CC=6 SCAR=18.2
861 58 my ($self, @set) = @_;
862 58 my $key = "country:$self->{level}";
863 58 ▶ if (@set) {
Branch: 1 branch
BranchTrueFalseTotal
if (@set) 4 54 58
864 4 $self->{last_country} = $set[0];
865 4 ▶ $self->_set($key, $set[0]) unless ($self->_get($key) // '') eq $set[0];
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_get($key) // "") eq $set[0] 4 0 4
Condition50%1/2
$self->_get($key) // ""
l!l
04
MC/DC0%0/1
$self->_get($key) // ""
$self->_get($key)
Truth table50%1/2
A
A= $self->_get($key)
Aresult
11
00
866 4 return $set[0];
867 }
868 54 ▶ return $self->{last_country} //= $self->_get($key) // '';
Condition75%3/4
$$self{"last_country"} //= $self->_get($key) // ""
l!l
2232
$self->_get($key) // ""
l!l
032
MC/DC100%1/1
$$self{"last_country"} //= $self->_get($key) // ""
$$self{"last_country"}
Truth table100%2/2
A
A= $$self{"last_country"}
Aresult
11
00
869 }
870  
871 96 ▶sub _can_ask {
Subroutine _can_ask: called CC=4 SCAR=13.9
872 96 my $self = shift;
873 96 ▶ return 0 unless $self->{online};
Branch: 1 branch
BranchTrueFalseTotal
unless $$self{"online"} 8 88 96
874 88 ▶ return 1 if $self->{ua};
Branch: 1 branch
BranchTrueFalseTotal
if $$self{"ua"} 4 84 88
875 84 require Database::BI::Model::Geocode;
876 84 ▶ return Database::BI::Model::Geocode::nominatim_ua() ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
Database::BI::Model::Geocode::nominatim_ua() ? : 82 2 84
877 }
878  
879 # _ask($key, \@index) -> ($osm, 'found') | (undef, 'nowhere') | (undef, 'failed')
880 #
881 # Reverse lookups down a plan. The first is the first try of the plan of the
882 # last country seen; its reply names the point's country, whose plan is then
883 # followed from its start (a try at a zoom already asked uses that reply), to
884 # the first try that gives an outline. A found outline is remembered with its
885 # country and rank, added to the index (and to @$index, so the caller's later
886 # points are tested against it), and the point remembered with it. A point no
887 # try gives an outline for is remembered as nowhere, with its country and the
888 # plan. A failure is remembered as nothing.
889 54 ▶sub _ask {
Subroutine _ask: called CC=18 SCAR=29.0
890 54 my ($self, $key, $index) = @_;
891 54 my ($lat, $lon) = split /,/, $key;
892  
893 54 my %replies; # by zoom
894 94 ▶ my $reverse = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
895 94 my $zoom = shift;
896 94 ▶ return $replies{$zoom} //= $self->_reverse($lat, $lon, $zoom);
Condition100%3/3
$replies{$zoom} //= $self->_reverse($lat, $lon, $zoom)
l!l&&r!l&&!r
394312
MC/DC100%2/2
$replies{$zoom} //= $self->_reverse($lat, $lon, $zoom)
$replies{$zoom} $self->_reverse($lat, $lon, $zoom)
Truth table100%3/3
A //= B
A= $replies{$zoom}B= $self->_reverse($lat, $lon, $zoom)
ABresult
1X1
011
000
897 54 };
898  
899 54 my $plan = $self->_plan($self->_last_country);
900 54 ▶ my $first = $reverse->($plan->[0]{zoom}) or return (undef, 'failed');
Branch: 1 branch
BranchTrueFalseTotal
my $first = &$reverse($$plan[0]{"zoom"}) or return undef, "failed" 43 11 54
901  
902 43 ▶ my $country = ref($first->{address}) eq 'HASH' ? $first->{address}{country_code} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $$first{'address'} eq 'HASH' ? : 4 39 43
903 43 ▶ $country = (defined($country) && !ref($country) && $country =~ /\A[A-Za-z]{2}\z/) ? lc($country) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $country && !ref($country) && $country =~ /\A[A-Za-z]{2}\z/ ? : 4 39 43
Condition66%4/6
defined $country and not ref $country and $country =~ /\A[A-Za-z]{2}\z/
!ll&&!rl&&r
3904
defined $country and not ref $country
!ll&&!rl&&r
3904
MC/DC33%1/3
defined $country and not ref $country and $country =~ /\A[A-Za-z]{2}\z/
defined $country not ref $country $country =~ /\A[A-Za-z]{2}\z/
Truth table50%2/4
A and not(B) and C
A= defined $countryB= not ref $countryC= $country =~ /\A[A-Za-z]{2}\z/
ABCresult
0XX0
10X0
1100
1111
904 43 ▶ if (length $country) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $country) 4 39 43
905 4 $self->_last_country($country);
906 4 $plan = $self->_plan($country);
907 }
908  
909 43 my ($reply, $osm);
910 # "Unable to geocode" is the sea at any zoom: no try will do better.
911 43 ▶ for my $try (defined($first->{error}) ? () : @{$plan}) {
Branch: 1 branch
BranchTrueFalseTotal
defined $$first{'error'} ? : 3 40 43
912 40 ▶ my $answer = $reverse->($try->{zoom}) or return (undef, 'failed');
Branch: 1 branch
BranchTrueFalseTotal
my $answer = &$reverse($$try{"zoom"}) or return undef, "failed" 39 1 40
913 39 ▶ $osm = _outline_id($answer, $try) // next;
Condition100%2/2
_outline_id($answer, $try) // (next)
l!l
381
MC/DC100%1/1
_outline_id($answer, $try) // (next)
_outline_id($answer, $try)
Truth table100%2/2
A
A= _outline_id($answer, $try)
Aresult
11
00
914 38 $reply = $answer;
915 38 last;
916 }
917  
918 42 ▶ unless ($reply) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($reply) 4 38 42
919 # The sea, and answers at other ranks or with no shape, alike. rank is
920 # what 0.023.0 kept, and reads back as the same county plan.
921 $self->_set($self->_point_cache_key($key),
922 4 { country => $country, rank => $plan->[0]{ranks}[1], plan => _plan_sig($plan) });
923 4 return (undef, 'nowhere');
924 }
925  
926 38 my $geometry = $reply->{geojson};
927 38 my $name = $reply->{name};
928 38 ▶ $name = $reply->{display_name} unless defined($name) && length($name);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 2 36 38
Condition66%2/3
defined $name and length $name
!ll&&!rl&&r
0236
MC/DC50%1/2
defined $name and length $name
defined $name length $name
Truth table66%2/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
929 $self->_set($self->_outline_key($osm), {
930 name => $name // $osm,
931 geometry => $geometry,
932 country => $country,
933 38 ▶ rank => $reply->{place_rank} + 0,
Condition33%1/3
$name // $osm
l!l&&r!l&&!r
3800
MC/DC0%0/2
$name // $osm
$name $osm
Truth table33%1/3
A // B
A= $nameB= $osm
ABresult
1X1
011
000
934 detail => $self->_detail,
935 });
936  
937 38 ▶ unless (grep { $_->[0] eq $osm } @{$index}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {$$_[0] eq $osm;} @{$index;}) 38 0 38
938 38 my $box = _bounds($geometry);
939 38 ▶ if ($box) {
Branch: 1 branch
BranchTrueFalseTotal
if ($box) 37 1 38
940 37 push @{$index}, [ $osm, @{$box} ];
941 37 my $stored = $self->_index;
942 37 ▶ push @{$stored}, [ $osm, @{$box} ] unless grep { $_->[0] eq $osm } @{$stored};
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$$_[0] eq $osm;} @{$stored;} 37 0 37
943 37 $self->_set("index:$self->{level}", $stored);
944 }
945 }
946 38 $self->_set($self->_point_cache_key($key), $osm);
947  
948 38 return ($osm, 'found');
949 }
950  
951 # _outline_id($reply, $try) -> 'R<id>' or 'W<id>' when the reply is an outline
952 # the try takes, else undef.
953 #
954 # An outline is an area with a shape, at a rank in the try's range: an
955 # administrative boundary's relation, or, for a try that takes places, a place
956 # mapped as an area (place=city, town, suburb), which may be a closed way. A
957 # place mapped as a point has no shape and is not one.
958 60 ▶sub _outline_id {
Subroutine _outline_id: called CC=23 SCAR=31.4
959 60 my ($reply, $try) = @_;
960  
961 60 my $geometry = $reply->{geojson};
962 60 my $rank = $reply->{place_rank};
963 60 ▶ my $category = $reply->{category} // '';
Condition100%2/2
$$reply{"category"} // ""
l!l
591
MC/DC100%1/1
$$reply{"category"} // ""
$$reply{"category"}
Truth table100%2/2
A
A= $$reply{"category"}
Aresult
11
00
964 60 ▶ my $osm_type = $reply->{osm_type} // '';
Condition100%2/2
$$reply{"osm_type"} // ""
l!l
591
MC/DC100%1/1
$$reply{"osm_type"} // ""
$$reply{"osm_type"}
Truth table100%2/2
A
A= $$reply{"osm_type"}
Aresult
11
00
965 return unless defined($reply->{osm_id}) && $reply->{osm_id} =~ /\A[0-9]+\z/
966 && defined($rank) && !ref($rank) && $rank =~ /\A[0-9]+\z/
967 && $rank >= $try->{ranks}[0] && $rank <= $try->{ranks}[1]
968 && ref($geometry) eq 'HASH'
969 && ($geometry->{type} // '') =~ /\A(?:Multi)?Polygon\z/
970 60 ▶ && ref($geometry->{coordinates}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $rank >= $$try{"ranks"}[0] and $rank <= $$try{"ranks"}[1] and ref $geometry eq "HASH" and ($$geometry{"type"} // "") =~ /\A(?:Multi)?Polygon\z/ and ref $$geometry{"coordinates"} eq "ARRAY" 12 48 60
Condition100%29/29
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $rank >= $$try{"ranks"}[0] and $rank <= $$try{"ranks"}[1] and ref $geometry eq "HASH" and ($$geometry{"type"} // "") =~ /\A(?:Multi)?Polygon\z/ and ref $$geometry{"coordinates"} eq "ARRAY"
!ll&&!rl&&r
11148
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $rank >= $$try{"ranks"}[0] and $rank <= $$try{"ranks"}[1] and ref $geometry eq "HASH" and ($$geometry{"type"} // "") =~ /\A(?:Multi)?Polygon\z/
!ll&&!rl&&r
9249
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $rank >= $$try{"ranks"}[0] and $rank <= $$try{"ranks"}[1] and ref $geometry eq "HASH"
!ll&&!rl&&r
7251
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $rank >= $$try{"ranks"}[0] and $rank <= $$try{"ranks"}[1]
!ll&&!rl&&r
6153
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $rank >= $$try{"ranks"}[0]
!ll&&!rl&&r
5154
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/
!ll&&!rl&&r
4155
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank
!ll&&!rl&&r
3156
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank
!ll&&!rl&&r
2157
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/
!ll&&!rl&&r
1158
$$geometry{"type"} // ""
l!l
501
MC/DC100%10/10
defined $$reply{"osm_id"} and $$reply{"osm_id"} =~ /\A[0-9]+\z/ and defined $rank and not ref $rank and $rank =~ /\A[0-9]+\z/ and $rank >= $$try{"ranks"}[0] and $rank <= $$try{"ranks"}[1] and ref $geometry eq "HASH" and ($$geometry{"type"} // "") =~ /\A(?:Multi)?Polygon\z/ and ref $$geometry{"coordinates"} eq "ARRAY"
defined $$reply{"osm_id"} $$reply{"osm_id"} =~ /\A[0-9]+\z/ defined $rank not ref $rank $rank =~ /\A[0-9]+\z/ $rank >= $$try{"ranks"}[0] $rank <= $$try{"ranks"}[1] ref $geometry eq "HASH" $$geometry{"type"} ref $$geometry{"coordinates"} eq "ARRAY"
Truth table100%11/11
A and B and C and not(D) and E and F and G and H and I and J
A= defined $$reply{"osm_id"}B= $$reply{"osm_id"} =~ /\A[0-9]+\z/C= defined $rankD= not ref $rankE= $rank =~ /\A[0-9]+\z/F= $rank >= $$try{"ranks"}[0]G= $rank <= $$try{"ranks"}[1]H= ref $geometry eq "HASH"I= $$geometry{"type"}J= ref $$geometry{"coordinates"} eq "ARRAY"
ABCDEFGHIJresult
0XXXXXXXXX0
10XXXXXXXX0
110XXXXXXX0
1110XXXXXX0
11110XXXXX0
111110XXXX0
1111110XXX0
11111110XX0
111111110X0
11111111100
11111111111
971  
972 48 ▶ my $boundary = $category eq 'boundary' && ($reply->{type} // '') eq 'administrative'
Condition100%8/8
$category eq 'boundary' && ($$reply{'type'} // '') eq 'administrative' && $osm_type eq 'relation'
!ll&&!rl&&r
7239
$category eq "boundary" and ($$reply{"type"} // "") eq "administrative"
!ll&&!rl&&r
5241
$$reply{"type"} // ""
l!l
421
MC/DC100%3/3
$category eq 'boundary' && ($$reply{'type'} // '') eq 'administrative' && $osm_type eq 'relation'
$category eq "boundary" $$reply{"type"} $osm_type eq 'relation'
Truth table100%4/4
A and B && C
A= $category eq "boundary"B= $$reply{"type"}C= $osm_type eq 'relation'
ABCresult
0XX0
10X0
1100
1111
973 && $osm_type eq 'relation';
974 48 ▶ my $place = $try->{places} && $category eq 'place' && ($osm_type eq 'relation' || $osm_type eq 'way');
Condition88%8/9
$$try{'places'} && $category eq 'place' && ($osm_type eq 'relation' || $osm_type eq 'way')
!ll&&!rl&&r
4512
$$try{"places"} and $category eq "place"
!ll&&!rl&&r
4503
$osm_type eq "relation" or $osm_type eq "way"
l!l&&r!l&&!r
111
MC/DC75%3/4
$$try{'places'} && $category eq 'place' && ($osm_type eq 'relation' || $osm_type eq 'way')
$$try{"places"} $category eq "place" $osm_type eq "relation" $osm_type eq "way"
Truth table80%4/5
A and B && C or D
A= $$try{"places"}B= $category eq "place"C= $osm_type eq "relation"D= $osm_type eq "way"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
975 48 ▶ return unless $boundary || $place;
Branch: 1 branch
BranchTrueFalseTotal
unless $boundary or $place 7 41 48
Condition100%3/3
$boundary or $place
l!l&&r!l&&!r
3927
MC/DC100%2/2
$boundary or $place
$boundary $place
Truth table100%3/3
A or B
A= $boundaryB= $place
ABresult
1X1
011
000
976  
977 41 ▶ return ($osm_type eq 'way' ? 'W' : 'R') . $reply->{osm_id};
Branch: 1 branch
BranchTrueFalseTotal
$osm_type eq 'way' ? : 1 40 41
978 }
979  
980 # _reverse($lat, $lon, $zoom) -> the decoded reply, or undef when Nominatim
981 # did not answer with JSON.
982 64 ▶sub _reverse {
Subroutine _reverse: called CC=7 SCAR=19.5
983 64 my ($self, $lat, $lon, $zoom) = @_;
984  
985 64 my $uri = URI->new($REVERSE_URL);
986 64 $uri->query_form(
987 lat => $lat,
988 lon => $lon,
989 zoom => $zoom,
990 format => 'jsonv2',
991 polygon_geojson => 1,
992 polygon_threshold => $self->_detail,
993 'accept-language' => 'en',
994 );
995  
996 64 require Database::BI::Model::Geocode;
997 64 ▶ my $ua = $self->{ua} // Database::BI::Model::Geocode::nominatim_ua();
Condition66%2/3
$$self{"ua"} // Database::BI::Model::Geocode::nominatim_ua()
l!l&&r!l&&!r
13510
MC/DC0%0/2
$$self{"ua"} // Database::BI::Model::Geocode::nominatim_ua()
$$self{"ua"} Database::BI::Model::Geocode::nominatim_ua()
Truth table66%2/3
A // B
A= $$self{"ua"}B= Database::BI::Model::Geocode::nominatim_ua()
ABresult
1X1
011
000
998 64 my $res = eval { $ua->get($uri) };
999 64 ▶ return unless blessed($res) && $res->can('is_success') && $res->is_success;
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($res) and $res->can("is_success") and $res->is_success 12 52 64
Condition100%6/6
builtin::blessed($res) and $res->can("is_success") and $res->is_success
!ll&&!rl&&r
4852
builtin::blessed($res) and $res->can("is_success")
!ll&&!rl&&r
3160
MC/DC100%3/3
builtin::blessed($res) and $res->can("is_success") and $res->is_success
builtin::blessed($res) $res->can("is_success") $res->is_success
Truth table100%4/4
A and B and C
A= builtin::blessed($res)B= $res->can("is_success")C= $res->is_success
ABCresult
0XX0
10X0
1100
1111
1000  
1001 52 ▶ my $reply = eval { $json->decode($res->decoded_content // '') };
Condition100%2/2
$res->decoded_content // ""
l!l
511
MC/DC100%1/1
$res->decoded_content // ""
$res->decoded_content
Truth table100%2/2
A
A= $res->decoded_content
Aresult
11
00
1002 52 ▶ return ref($reply) eq 'HASH' ? $reply : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $reply eq 'HASH' ? : 45 7 52
1003 }
1004  
1005 # _polygons($geometry) -> list of polygons, each an arrayref of rings, each
1006 # ring an arrayref of [lon, lat].
1007 65 ▶sub _polygons {
Subroutine _polygons: called CC=7 SCAR=19.5
1008 65 my $geometry = shift;
1009 65 ▶ return () unless ref($geometry) eq 'HASH' && ref($geometry->{coordinates}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $geometry eq "HASH" and ref $$geometry{"coordinates"} eq "ARRAY" 7 58 65
Condition100%3/3
ref $geometry eq "HASH" and ref $$geometry{"coordinates"} eq "ARRAY"
!ll&&!rl&&r
4358
MC/DC100%2/2
ref $geometry eq "HASH" and ref $$geometry{"coordinates"} eq "ARRAY"
ref $geometry eq "HASH" ref $$geometry{"coordinates"} eq "ARRAY"
Truth table100%3/3
A and B
A= ref $geometry eq "HASH"B= ref $$geometry{"coordinates"} eq "ARRAY"
ABresult
0X0
100
111
1010 58 ▶ return ($geometry->{coordinates}) if ($geometry->{type} // '') eq 'Polygon';
Branch: 1 branch
BranchTrueFalseTotal
if ($$geometry{"type"} // "") eq "Polygon" 48 10 58
Condition100%2/2
$$geometry{"type"} // ""
l!l
571
MC/DC100%1/1
$$geometry{"type"} // ""
$$geometry{"type"}
Truth table100%2/2
A
A= $$geometry{"type"}
Aresult
11
00
1011 10 ▶ return @{ $geometry->{coordinates} } if ($geometry->{type} // '') eq 'MultiPolygon';
Branch: 1 branch
BranchTrueFalseTotal
if ($$geometry{"type"} // "") eq "MultiPolygon" 8 2 10
Condition100%2/2
$$geometry{"type"} // ""
l!l
91
MC/DC100%1/1
$$geometry{"type"} // ""
$$geometry{"type"}
Truth table100%2/2
A
A= $$geometry{"type"}
Aresult
11
00
1012 2 return ();
1013 }
1014  
1015 # _bounds($geometry) -> [south, west, north, east], or undef with no points
1016 44 ▶sub _bounds {
Subroutine _bounds: called CC=13 SCAR=25.6
1017 44 my $geometry = shift;
1018 44 my ($south, $west, $north, $east);
1019 44 for my $polygon (_polygons($geometry)) {
1020 44 ▶ for my $position (@{ $polygon->[0] // [] }) {
Condition100%2/2
$$polygon[0] // []
l!l
431
MC/DC100%1/1
$$polygon[0] // []
$$polygon[0]
Truth table100%2/2
A
A= $$polygon[0]
Aresult
11
00
1021 194 my ($lon, $lat) = @{$position};
1022 194 ▶ $south = $lat if !defined($south) || $lat < $south;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $south or $lat < $south 42 152 194
Condition100%3/3
not defined $south or $lat < $south
l!l&&r!l&&!r
402152
MC/DC100%2/2
not defined $south or $lat < $south
not defined $south $lat < $south
Truth table100%3/3
not(A) or B
A= not defined $southB= $lat < $south
ABresult
1X1
011
000
1023 194 ▶ $north = $lat if !defined($north) || $lat > $north;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $north or $lat > $north 80 114 194
Condition100%3/3
not defined $north or $lat > $north
l!l&&r!l&&!r
4040114
MC/DC100%2/2
not defined $north or $lat > $north
not defined $north $lat > $north
Truth table100%3/3
not(A) or B
A= not defined $northB= $lat > $north
ABresult
1X1
011
000
1024 194 ▶ $west = $lon if !defined($west) || $lon < $west;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $west or $lon < $west 42 152 194
Condition100%3/3
not defined $west or $lon < $west
l!l&&r!l&&!r
402152
MC/DC100%2/2
not defined $west or $lon < $west
not defined $west $lon < $west
Truth table100%3/3
not(A) or B
A= not defined $westB= $lon < $west
ABresult
1X1
011
000
1025 194 ▶ $east = $lon if !defined($east) || $lon > $east;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $east or $lon > $east 80 114 194
Condition100%3/3
not defined $east or $lon > $east
l!l&&r!l&&!r
4040114
MC/DC100%2/2
not defined $east or $lon > $east
not defined $east $lon > $east
Truth table100%3/3
not(A) or B
A= not defined $eastB= $lon > $east
ABresult
1X1
011
000
1026 }
1027 }
1028 44 ▶ return defined($south) ? [ $south, $west, $north, $east ] : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $south ? : 40 4 44
1029 }
1030  
1031 # _contains($geometry, $lat, $lon) -> 1 when the point is inside a polygon's
1032 # outer ring and none of its holes (Fairfax County's hole is the City of
1033 # Fairfax). Even-odd ray casting, with longitude as x.
1034 19 ▶sub _contains {
Subroutine _contains: called CC=5 SCAR=16.1
1035 19 my ($geometry, $lat, $lon) = @_;
1036 19 for my $polygon (_polygons($geometry)) {
1037 # Premise 1: the geometry came from a web service and a cache file.
1038 # Premise 2: a damaged entry must not turn a map into a 500.
1039 # Conclusion: what is not a polygon holds no point.
1040 16 ▶ next unless ref($polygon) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $polygon eq "ARRAY" 3 13 16
1041 13 my ($outer, @holes) = @{$polygon};
1042 13 ▶ next unless _in_ring($outer, $lon, $lat);
Branch: 1 branch
BranchTrueFalseTotal
unless _in_ring($outer, $lon, $lat) 7 6 13
1043 6 ▶ return 1 unless grep { _in_ring($_, $lon, $lat) } @holes;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {_in_ring($_, $lon, $lat);} @holes 4 2 6
1044 }
1045 15 return 0;
1046 }
1047  
1048 # _is_position($value) -> 1 | 0
1049 #
1050 # A GeoJSON position is a list of at least two defined numbers. Anything else
1051 # in a ring means the ring is damaged, and a damaged ring holds no point.
1052 144 ▶sub _is_position {
Subroutine _is_position: called CC=7 SCAR=19.5
1053 144 my ($position) = @_;
1054 144 ▶ return 0 unless ref($position) eq 'ARRAY' && @{$position} >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $position eq "ARRAY" and @{$position;} >= 2 4 140 144
Condition100%3/3
ref $position eq "ARRAY" and @{$position;} >= 2
!ll&&!rl&&r
31140
MC/DC100%2/2
ref $position eq "ARRAY" and @{$position;} >= 2
ref $position eq "ARRAY" @{$position;} >= 2
Truth table100%3/3
A and B
A= ref $position eq "ARRAY"B= @{$position;} >= 2
ABresult
0X0
100
111
1055 140 ▶ return (defined $position->[0] && defined $position->[1]
Branch: 1 branch
BranchTrueFalseTotal
defined $$position[0] && defined $$position[1] && !ref($$position[0]) && !ref($$position[1]) ? : 138 2 140
Condition77%7/9
defined $$position[0] and defined $$position[1] and not ref $$position[0] and not ref $$position[1]
!ll&&!rl&&r
20138
defined $$position[0] and defined $$position[1] and not ref $$position[0]
!ll&&!rl&&r
11138
defined $$position[0] and defined $$position[1]
!ll&&!rl&&r
10139
MC/DC50%2/4
defined $$position[0] and defined $$position[1] and not ref $$position[0] and not ref $$position[1]
defined $$position[0] defined $$position[1] not ref $$position[0] not ref $$position[1]
Truth table60%3/5
A and B and not(C) and not(D)
A= defined $$position[0]B= defined $$position[1]C= not ref $$position[0]D= not ref $$position[1]
ABCDresult
0XXX0
10XX0
110X0
11100
11111
1056 && !ref($position->[0]) && !ref($position->[1])) ? 1 : 0;
1057 }
1058  
1059 35 ▶sub _in_ring {
Subroutine _in_ring: called CC=9 SCAR=22.0
1060 35 my ($ring, $x, $y) = @_;
1061 35 ▶ return 0 unless ref($ring) eq 'ARRAY' && @{$ring} >= 3;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ring eq "ARRAY" and @{$ring;} >= 3 8 27 35
Condition100%3/3
ref $ring eq "ARRAY" and @{$ring;} >= 3
!ll&&!rl&&r
5327
MC/DC100%2/2
ref $ring eq "ARRAY" and @{$ring;} >= 3
ref $ring eq "ARRAY" @{$ring;} >= 3
Truth table100%3/3
A and B
A= ref $ring eq "ARRAY"B= @{$ring;} >= 3
ABresult
0X0
100
111
1062 27 my $inside = 0;
1063 27 ▶ return 0 unless _is_position($ring->[-1]);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_position($$ring[-1]) 1 26 27
1064 26 my ($px, $py) = @{ $ring->[-1] };
1065 26 for my $position (@{$ring}) {
1066 117 ▶ return 0 unless _is_position($position);
Branch: 1 branch
BranchTrueFalseTotal
unless _is_position($position) 5 112 117
1067 112 my ($qx, $qy) = @{$position};
1068 112 ▶ if ((($qy > $y) != ($py > $y))
Branch: 1 branch
BranchTrueFalseTotal
if ($qy > $y != $py > $y and $x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx) 15 97 112
Condition100%3/3
$qy > $y != $py > $y and $x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx
!ll&&!rl&&r
732415
MC/DC100%2/2
$qy > $y != $py > $y and $x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx
$qy > $y != $py > $y $x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx
Truth table100%3/3
A and B
A= $qy > $y != $py > $yB= $x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx
ABresult
0X0
100
111
1069 && ($x < ($px - $qx) * ($y - $qy) / ($py - $qy) + $qx)) {
1070 15 $inside = !$inside;
1071 }
1072 112 ($px, $py) = ($qx, $qy);
1073 }
1074 21 ▶ return $inside ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$inside ? : 11 10 21
1075 }
1076  
1077 6 1;
1078  
1079 __END__
« script/database-bi ↑ Summary blib/lib/Database/BI/SafeUA.pm »