DRI/Data/LanguageTag.pm

filter: Statementstmt 83.3% 10 / 12 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 4 / 4 Podpod n/a totaltotal 87.5% 14 / 16 CC 1 SCAR 0.7
CC
1
Cov
83%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« DRI/Protocol/RRP/Core/Host.pm ↑ Summary DRI/Protocol/RRP/Core/Domain.pm »
1 ## Domain Registry Interface, Language Tag parsing (RFC5646)
2 ##
3 ## Copyright (c) 2015,2016 Patrick Mevzek <netdri@dotandco.com>. All rights reserved.
4 ##
5 ## This file is part of Net::DRI
6 ##
7 ## Net::DRI is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## See the LICENSE file that comes with this distribution for more details.
13 ####################################################################################################
14  
15 package Net::DRI::Data::LanguageTag;
16  
17 81 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 81 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 81 ▶use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21 0 ▶use Sub::Name;
Subroutine BEGIN: called CC=1 SCAR=2.6
22  
23 use overload '""' => sub { my ($self, @rest) = @_; return $self->as_string(); },
24 '@{}' => sub { my ($self, @rest) = @_; return [ $self->subtags() ]; },
25 '.' => sub { my ($self, $toadd, $swap) = @_; mydie('Left adding subtags is not implemented') if $swap; return $self->add_subtag($toadd); },
26 'cmp' => sub { my ($self, $other, $swap) = @_; my $r = "${self}" cmp "${other}"; return $swap ? -$r : $r; }, ## should we compare subtags one by one?
27 'fallback' => undef;
28  
29 my $digit=qr/[0-9]/;
30 my $alpha=qr/[A-Za-z]/;
31 my $alphanum=qr/${digit}|${alpha}/;
32  
33 my $irregular=qr/en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE/i;
34 my $regular=qr/art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang/i;
35 my $grandfathered=qr/${irregular}|${regular}/;
36  
37 my $privateuse=qr/x(?:-${alphanum}{1,8})+/i; ## TODO check if lower bound is indeed 1 ! is this like an extension, and hence need to be checked
38  
39 my $extlang=qr/${alpha}{3}(?:-${alpha}{3}){0,2}/;
40 my $language=qr/(?:${alpha}{2,3}(-${extlang})?)|${alpha}{4}|${alpha}{5,8}/;
41  
42 my $script=qr/${alpha}{4}/;
43 my $region=qr/${alpha}{2}|${digit}{3}/;
44 my $variant=qr/${alphanum}{5,8}|${digit}${alphanum}{3}/;
45  
46 my $singleton=qr/${digit}|[A-W]|[Y-Z]|[a-w]|[y-z]/;
47 my $extension=qr/${singleton}(?:-${alphanum}{2,8})+/;
48  
49 my $langtag=qr/(?<language>${language})(?<script>(-${script})?)(?<region>(-${region})?)(?<variant>(-${variant})*)(?<extension>(-${extension})*)(?<privateuse>(-${privateuse})?)/;
50  
51 ## §2.1.1 : At all times, language tags and their subtags, including private use and extensions, are to be treated as case insensitive
52 my $TAG=qr/(?<langtag>${langtag})|(?<privateuse>${privateuse})|(?<grandfathered>${grandfathered})/i;
53  
54 my $mydie;
55 if (exists $INC{'Net/DRI.pm'})
56 {
57 require Net::DRI::Exception;
58 $mydie=sub { Net::DRI::Exception->usererr_invalid_parameters(@_); };
59 } else
60 {
61 require Carp;
62 $mydie=\&Carp::croak;
63 }
64 *mydie=$mydie;
65 subname 'mydie', $mydie;
66  
67 sub new
68 {
69 my ($class,$tag)=@_;
70 my $self={};
71 bless $self,$class;
72 mydie('No tag to parse') unless defined $tag && length $tag;
73 $self->_parse($tag);
74 return $self;
75 }
76  
77 my @okeys=qw/type language script region variant extension privateuse/;
78  
79 ## This also checks syntax and canonicalize (for parts that can be done without access to the langtag registry)
80 sub _parse
81 {
82 my ($self,$tag)=@_;
83  
84 mydie(qq{Tag "$tag" does not validate as a "Language Tag" per RFC5646 rules}) unless $tag=~/^${TAG}$/;
85  
86 my %build;
87 ## regular grandfathered tags will fall into the 'langtag' case as the re is parsed left to right
88 $build{type}=exists $+{langtag} ? 'langtag': ( exists $+{privateuse} ? 'privateuse' : 'grandfathered');
89 if ($build{type} eq 'langtag')
90 {
91 $build{language}=[ _format_subtags(0,grep { length } split(/-/,$+{language})) ];
92 $build{script}=[ _format_subtags(1,grep { length } split(/-/,$+{script})) ];
93 $build{region}=[ _format_subtags(1,grep { length } split(/-/,$+{region})) ];
94  
95 $build{variant}=[ _format_subtags(1,grep { length } split(/-/,$+{variant})) ];
96 # §2.2.5 point 5
97 {
98 my %seen;
99 foreach my $variant (@{$build{variant}})
100 {
101 if (exists $seen{$variant})
102 {
103 mydie(qq{Variant element "${variant}" can not appear more than once in language tag});
104 }
105 $seen{$variant}=1;
106 }
107 }
108  
109 my @exts=_format_subtags(1,grep { length } split(/-/,$+{extension}));
110 # §2.2.6 point 3
111 {
112 my %seen;
113 foreach my $extension (grep { length == 1 } @exts)
114 {
115 if (exists $seen{$extension})
116 {
117 mydie(qq{Extension singleton "${extension}" can not appear more than once in language tag});
118 }
119 $seen{$extension}=1;
120 }
121 }
122 # §2.2.6 point 6
123 mydie(q{In extension subtag, singletons can not follow one another}) if join('',map { length == 1 ? 1 : 0 } @exts)=~m/11/; ## TODO: check if this is possible (not with above regex anyway!)
124 # §4.5 canonicalization (only part that can be done without the registry)
125 # "Extension sequences are ordered into case-insensitive ASCII order by singleton subtag."
126 {
127 @exts=(join('-',@exts)=~m/(${singleton}(?:-${alphanum}{2,8})+)+/g);
128 # uncoverable branch true (lc $a->[0] cmp lc $b->[0] can never be false (Devel::Cover sees it as unless …) because that would mean $a->[0] eq $b->[0] which means twice the same singleton which is something checked above already anyway)
129 $build{extension}=[ map { ($_->[0],split(/-/,$_->[1])) } sort { lc $a->[0] cmp lc $b->[0] || lc $a->[1] cmp lc $b->[1] } map { [ split(/-/,$_,2) ] } @exts ];
130 }
131  
132 $build{privateuse}=[ _format_subtags(1,grep { length } split(/-/,$+{privateuse})) ];
133  
134 $build{tags}=[ map { @{$build{$_}} } qw/language script region variant extension privateuse/ ];
135 } else
136 {
137 $build{tags}=[ _format_subtags(0,split(/-/,$tag)) ];
138 }
139  
140 ## Everything went through nicely, time to update the structure;
141 ## ('tags' key will be always populated, no need to clean it first)
142 delete @$self{@okeys};
143 @$self{keys %build}=values %build;
144 return;
145 }
146  
147 # §2.1.1 Formatting of Language Tags
148 sub _format_subtags
149 {
150 my ($notfirst,@tags)=@_;
151  
152 ## inline static list in order not to depend on locale subsystem where we run
153 state $lc={ qw/A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z/ };
154 state $up={ reverse %$lc };
155  
156 my @t;
157 foreach my $ti (0..$#tags)
158 {
159 my $t=$tags[$ti];
160 mydie(qq{Subtag "$t" is too long}) if length $t > 8; ## 2.1 Syntax: All subtags have a maximum length of eight characters.
161 ## lowercase everything, except:
162 ## two-letter and four-letter subtags that neither appear at the start of the tag nor occur after singletons.
163 ## (upercase everything for two-letter, and titlecase for four-letter)
164 if (($notfirst || $ti != 0) && length $tags[$ti-1] > 1)
165 {
166 if (length $t == 2)
167 {
168 push @t,join('',map { defined $up->{$_} ? $up-> {$_} : $_ } split(//,$t)); ## Devel::Cover does not handle // correctly, hence using the longer form
169 next;
170 } elsif (length $t == 4)
171 {
172 my ($first,$rest)=($t=~m/^(.)(...)$/);
173 push @t,(defined $up->{$first} ? $up->{$first} : $first).(join('',map { defined $lc->{$_} ? $lc->{$_} : $_ } split(//, $rest))); ## See above comment on Devel::Cover
174 next;
175 }
176 }
177 push @t,join('',map { defined $lc->{$_} ? $lc->{$_} : $_ } split(//, $t)); ## See above comment on Devel::Cover
178 }
179  
180 return @t;
181 }
182  
183 sub type { return $_[0]->{type}; } ## no critic (Subroutines::RequireArgUnpacking)
184  
185 sub _subtag
186 {
187 my ($self,$item)=@_;
188 my $ra=$self->{$item};
189 return unless defined $ra;
190 return wantarray ? @$ra : join('-',@$ra);
191 }
192  
193 sub language { return _subtag($_[0],'language'); } ## no critic (Subroutines::RequireArgUnpacking)
194 sub script { return _subtag($_[0],'script'); } ## no critic (Subroutines::RequireArgUnpacking)
195 sub region { return _subtag($_[0],'region'); } ## no critic (Subroutines::RequireArgUnpacking)
196 sub variant { return _subtag($_[0],'variant'); } ## no critic (Subroutines::RequireArgUnpacking)
197 sub extension { return _subtag($_[0],'extension'); } ## no critic (Subroutines::RequireArgUnpacking)
198 sub privateuse { return _subtag($_[0],'privateuse'); } ## no critic (Subroutines::RequireArgUnpacking)
199  
200  
201 sub subtags
202 {
203 my ($self)=@_;
204 return @{$self->{tags}} if wantarray;
205 my %r;
206 @r{@okeys}=@$self{@okeys};
207 return \%r; ## in hashref context, all values are refarrays (or undef if not parsed at all), even for single valued items, such as script & region
208 }
209  
210 sub as_string
211 {
212 my ($self)=@_;
213 return join('-',@{$self->{tags}});
214 }
215  
216 sub add_subtag
217 {
218 my ($self,$tag)=@_;
219 mydie('Undefined subtag to add') unless defined $tag;
220 return $self unless length $tag;
221 my $try=$self->as_string().'-'.$tag;
222 $self->_parse($try);
223 return $self;
224 }
225  
226 ####################################################################################################
227 1;
228  
229 __END__
« DRI/Protocol/RRP/Core/Host.pm ↑ Summary DRI/Protocol/RRP/Core/Domain.pm »