1package Interchange6::Schema::Populate::StateLocale;
2
3=head1 NAME
4
5Interchange6::Schema::Populate::StateLocale
6
7=head1 DESCRIPTION
8
9This role provides population capabilities for the State class
10
11=cut
12
13use Moo::Role;
14use Locale::SubCountry;
15
16=head1 METHODS
17
18=head2 populate_states
19
20Returns array reference containing one hash reference per state,
21ready to use with populate schema method.
22
23=cut
24
25sub populate_states {
26    my $self = shift;
27
28    my $countries =
29      $self->schema->resultset('Country')->search( { -bool => 'show_states' } );
30
31    while ( my $country_result = $countries->next ) {
32
33        my $country =
34          Locale::SubCountry->new( $country_result->country_iso_code );
35
36        # should never happen so let Devel::Cover watch it for us
37        # uncoverable branch true
38        next unless $country->has_sub_countries;
39
40        my %country_states_keyed_by_code = $country->code_full_name_hash;
41
42        foreach my $state_code ( sort keys %country_states_keyed_by_code ) {
43
44            # some US 'states' are not actually states of the US
45            next
46              if ( $country_result->country_iso_code eq 'US'
47                && $state_code =~ /(AS|GU|MP|PR|UM|VI)/ );
48
49            my $state_name = $country_states_keyed_by_code{$state_code};
50
51            # remove (Junk) from some records
52            $state_name =~ s/\s*\([^)]*\)//g;
53
54            $country_result->create_related(
55                'states',
56                {
57                    'name'           => $state_name,
58                    'state_iso_code' => $state_code,
59                }
60            );
61        }
62    }
63}
64
651;
66