Babelfish.pm

filter: Statementstmt 84.0% 174 / 207 Branchbran 60.3% 64 / 106 Conditioncond 50.0% 19 / 38 MC/DCmcdc 33.3% 7 / 21 Subroutinesub 93.5% 29 / 31 Podpod 100% 13 / 13 totaltotal 73.5% 306 / 416 CC 75 SCAR 26.7
CC
75
Cov
73%
look_for_watchers
56.0
has_any_value
49.0
t_or_undef
18.0
CRAP 14.5
« Babelfish/Phrase/Parser.pm ↑ Summary Babelfish/Phrase/PluralForms.pm »
1 package Locale::Babelfish;
2  
3 # ABSTRACT: Perl I18n using https://github.com/nodeca/babelfish format.
4  
5 2 our $VERSION = '2.10'; # VERSION
6  
7  
8 2 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 ▶use Carp qw/ confess /;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use File::Find qw( find );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use File::Spec ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 2 ▶use YAML::SyckWrapper qw( load_yaml );
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use Locale::Babelfish::Phrase::Parser ();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use Locale::Babelfish::Phrase::Compiler ();
Subroutine BEGIN: called CC=1 SCAR=0.0
20  
21  
22 2 ▶use parent qw( Class::Accessor::Fast );
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 use constant {
25 2 MTIME_INDEX => 9,
26 2 ▶};
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 2 __PACKAGE__->mk_accessors( qw(
29 dictionaries
30 fallbacks
31 fallback_cache
32 dirs
33 suffix
34 default_locale
35 watch
36 watchers
37 ) );
38  
39 2 my $parser = Locale::Babelfish::Phrase::Parser->new();
40 2 my $compiler = Locale::Babelfish::Phrase::Compiler->new();
41  
42  
43 sub _built_config {
44 1 ▶ my ( $cfg ) = @_;
Subroutine _built_config: called CC=5 SCAR=18.2
45 return {
46 dictionaries => {},
47 fallbacks => {},
48 fallback_cache => {},
49 suffix => $cfg->{suffix} // 'yaml',
50 default_locale => $cfg->{default_locale} // 'en_US',
51 watch => $cfg->{watch} || 0,
52 watchers => {},
53 1 ▶ %{ $cfg // {} },
Condition50%4/8
$cfg->{"suffix"} // "yaml"
l!l
01
$cfg->{"default_locale"} // "en_US"
l!l
01
$cfg->{'watch'} || 0
l!l
01
$cfg // {}
l!l
10
MC/DC0%0/1
$cfg->{"suffix"} // "yaml"
$cfg->{"suffix"}
MC/DC0%0/1
$cfg->{"default_locale"} // "en_US"
$cfg->{"default_locale"}
MC/DC0%0/1
$cfg->{'watch'} || 0
$cfg->{'watch'}
MC/DC0%0/1
$cfg // {}
$cfg
Truth table50%1/2
A
A= $cfg->{"suffix"}
Aresult
11
00
Truth table50%1/2
A
A= $cfg->{"default_locale"}
Aresult
11
00
Truth table50%1/2
A
A= $cfg->{'watch'}
Aresult
11
00
Truth table50%1/2
A
A= $cfg
Aresult
11
00
54 };
55 }
56  
57 sub new {
58 1 ▶ my ( $class, $cfg ) = @_;
Subroutine new: called CC=1 SCAR=0.0
Pod documented
59  
60 my $self = bless {
61 _cfg => $cfg,
62 1 %{ _built_config( $cfg ) },
63 }, $class;
64  
65 1 $self->load_dictionaries;
66 1 $self->locale( $self->{default_locale} );
67  
68 1 return $self;
69 }
70  
71  
72 sub locale {
73 3 ▶ my $self = shift;
Subroutine locale: called CC=2 SCAR=7.1
Pod documented
74 3 ▶ return $self->{locale} if scalar(@_) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ == 0 0 3 3
75 3 $self->{locale} = $self->detect_locale( $_[0] );
76 }
77  
78  
79 sub on_watcher_change {
80 0 ▶ my ( $self ) = @_;
Subroutine on_watcher_change: not called CC=2 SCAR=17.9
Pod documented
81 0 delete $self->{keys %$self};
82 0 my %new_cfg = %{ _built_config( $self->{_cfg} ) };
83 0 ▶ while( my ( $key, $value ) = each %new_cfg ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %new_cfg) 0 0 0
84 0 $self->{$key} = $value;
85 }
86 0 $self->load_dictionaries;
87 0 $self->locale( $self->{default_locale} );
88 }
89  
90  
91 sub look_for_watchers {
92 0 ▶ my ( $self ) = @_;
Subroutine look_for_watchers: not called CC=7 SCAR=40.3
Pod documented
93 0 ▶ return unless $self->{watch};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"watch"} 0 0 0
94 0 my $ok = 1;
95 0 ▶ while ( my ( $file, $mtime ) = each %{ $self->watchers } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$self->watchers;}) 0 0 0
96 0 my $new_mtime = (stat($file))[MTIME_INDEX];
97 0 ▶ if ( !defined( $mtime ) || !defined( $new_mtime ) || $new_mtime != $mtime ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $mtime && defined $new_mtime or $new_mtime != $mtime) 0 0 0
Condition0%0/6
not defined $mtime && defined $new_mtime or $new_mtime != $mtime
l!l&&r!l&&!r
000
defined $mtime && defined $new_mtime
!ll&&!rl&&r
000
MC/DC0%0/3
not defined $mtime && defined $new_mtime or $new_mtime != $mtime
defined $mtime defined $new_mtime $new_mtime != $mtime
Truth table0%0/4
not(A && B) or C
A= defined $mtimeB= defined $new_mtimeC= $new_mtime != $mtime
ABCresult
0XX1
10X1
1111
1100
98 0 $ok = 0;
99 0 last;
100 }
101 }
102 0 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
103 0 $self->on_watcher_change();
104 }
105  
106  
107 sub t_or_undef {
108 28 ▶ my ( $self, $dictname_key, $params, $custom_locale ) = @_;
Subroutine t_or_undef: called CC=17 SCAR=28.9
Pod documented
109  
110  
111 28 ▶ confess 'No dictname_key' unless $dictname_key;
Branch: 1 branch
BranchTrueFalseTotal
unless $dictname_key 0 28 28
112 # запрещаем ключи не ASCII
113 28 ▶ confess("wrong dictname_key: $dictname_key") if $dictname_key =~ m/\P{ASCII}/;
Branch: 1 branch
BranchTrueFalseTotal
if $dictname_key =~ /\P{ASCII}/ 0 28 28
114  
115 28 ▶ my $locale = $custom_locale ? $self->detect_locale( $custom_locale ) : $self->{locale};
Branch: 1 branch
BranchTrueFalseTotal
$custom_locale ? : 0 28 28
116  
117 28 my $r = $self->{dictionaries}->{$locale}->{$dictname_key};
118  
119 28 ▶ if ( defined $r ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r) { } 25 3 28
120 25 ▶ if ( ref( $r ) eq 'SCALAR' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $r eq 'SCALAR') { } 11 14 25
elsif (ref $r eq 'ARRAY') { } 6 8 14
121 11 $self->{dictionaries}->{$locale}->{$dictname_key} = $r = $compiler->compile(
122 $parser->parse( $$r, $locale ),
123 );
124 }
125 elsif ( ref( $r ) eq 'ARRAY' ) {
126 6 $self->{dictionaries}{$locale}{$dictname_key} = $r
127 = _process_list_items( $r, $locale );
128 }
129 }
130 # fallbacks
131 else {
132 3 ▶ $self->{fallback_cache}->{$locale} //= {};
Condition100%2/2
$self->{"fallback_cache"}{$locale} //= {}
l!l
12
MC/DC100%1/1
$self->{"fallback_cache"}{$locale} //= {}
$self->{"fallback_cache"}{$locale}
Truth table100%2/2
A
A= $self->{"fallback_cache"}{$locale}
Aresult
11
00
133 # в кэше может быть undef, чтобы не пробегать локали для несуществующих ключей повторно.
134 3 ▶ if ( exists $self->{fallback_cache}->{$locale}->{$dictname_key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{'fallback_cache'}{$locale}{$dictname_key}) { } 0 3 3
135 0 $r = $self->{fallback_cache}->{$locale}->{$dictname_key};
136 }
137 else {
138 3 ▶ my @fallback_locales = @{ $self->{fallbacks}->{$locale} // [] };
Condition100%2/2
$self->{"fallbacks"}{$locale} // []
l!l
21
MC/DC100%1/1
$self->{"fallbacks"}{$locale} // []
$self->{"fallbacks"}{$locale}
Truth table100%2/2
A
A= $self->{"fallbacks"}{$locale}
Aresult
11
00
139 3 for ( @fallback_locales ) {
140 2 $r = $self->{dictionaries}->{$_}->{$dictname_key};
141 2 ▶ if ( defined $r ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r) 1 1 2
142 1 ▶ if ( ref( $r ) eq 'SCALAR' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $r eq 'SCALAR') { } 1 0 1
elsif (ref $r eq 'ARRAY') { } 0 0 0
143 1 $self->{dictionaries}->{$_}->{$dictname_key} = $r = $compiler->compile(
144 $parser->parse( $$r, $_ ),
145 );
146 }
147 elsif ( ref( $r ) eq 'ARRAY' ) {
148 0 $self->{dictionaries}{$locale}{$dictname_key} = $r
149 = _process_list_items( $r, $locale );
150 }
151 1 last;
152 }
153 }
154 3 $self->{fallback_cache}->{$locale}->{$dictname_key} = $r;
155 }
156 }
157  
158 28 ▶ if ( ref( $r ) eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $r eq "CODE") 23 5 28
159 23 my $flat_params = {};
160 # Переводим хэш параметров в "плоскую форму" так как в babelfish они имеют вид params.key.subkey
161 23 ▶ if ( defined($params) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $params) 20 3 23
162 # переданный скаляр превращаем в хэш { count, value }.
163 20 ▶ if ( ref($params) eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params eq '') { } 3 17 20
164 3 $flat_params = {
165 count => $params,
166 value => $params,
167 };
168 }
169 else {
170 17 _flat_hash_keys( $params, '', $flat_params );
171 }
172 }
173  
174 23 return $r->( $flat_params );
175 }
176  
177 5 return $r;
178 }
179  
180  
181 sub t {
182 28 ▶ my $self = shift;
Subroutine t: called CC=2 SCAR=6.9
Pod documented
183  
184 28 ▶ return $self->t_or_undef( @_ ) || "[$_[0]]";
Condition100%2/2
$self->t_or_undef(@_) || "[$_[0]]"
l!l
262
MC/DC100%1/1
$self->t_or_undef(@_) || "[$_[0]]"
$self->t_or_undef(@_)
Truth table100%2/2
A
A= $self->t_or_undef(@_)
Aresult
11
00
185 }
186  
187  
188 sub has_any_value {
189 1 ▶ my ( $self, $dictname_key, $custom_locale ) = @_;
Subroutine has_any_value: called CC=10 SCAR=38.9
Pod documented
190  
191 # запрещаем ключи не ASCII
192 1 ▶ confess("wrong dictname_key: $dictname_key") if $dictname_key =~ m/\P{ASCII}/;
Branch: 1 branch
BranchTrueFalseTotal
if $dictname_key =~ /\P{ASCII}/ 0 1 1
193  
194 1 ▶ my $locale = $custom_locale ? $self->detect_locale( $custom_locale ) : $self->{locale};
Branch: 1 branch
BranchTrueFalseTotal
$custom_locale ? : 0 1 1
195  
196 1 ▶ return 1 if $self->{dictionaries}->{$locale}->{$dictname_key};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"dictionaries"}{$locale}{$dictname_key} 1 0 1
197  
198 0 ▶ $self->{fallback_cache}->{$locale} //= {};
Condition0%0/2
$self->{"fallback_cache"}{$locale} //= {}
l!l
00
MC/DC0%0/1
$self->{"fallback_cache"}{$locale} //= {}
$self->{"fallback_cache"}{$locale}
Truth table0%0/2
A
A= $self->{"fallback_cache"}{$locale}
Aresult
11
00
199 return ( ( defined $self->{fallback_cache}->{$locale}->{$dictname_key} ) ? 1 : 0 )
200 0 ▶ if exists $self->{fallback_cache}->{$locale}->{$dictname_key};
Branch: 2 branches
BranchTrueFalseTotal
if exists $self->{"fallback_cache"}{$locale}{$dictname_key} 0 0 0
defined $self->{'fallback_cache'}{$locale}{$dictname_key} ? : 0 0 0
201  
202 0 ▶ my @fallback_locales = @{ $self->{fallbacks}->{$locale} // [] };
Condition0%0/2
$self->{"fallbacks"}{$locale} // []
l!l
00
MC/DC0%0/1
$self->{"fallbacks"}{$locale} // []
$self->{"fallbacks"}{$locale}
Truth table0%0/2
A
A= $self->{"fallbacks"}{$locale}
Aresult
11
00
203 0 for ( @fallback_locales ) {
204 0 ▶ return 1 if defined $self->{dictionaries}->{$_}->{$dictname_key};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"dictionaries"}{$_}{$dictname_key} 0 0 0
205 }
206  
207 }
208  
209  
210 sub load_dictionaries {
211 1 ▶ my $self = shift;
Subroutine load_dictionaries: called CC=2 SCAR=7.1
Pod documented
212  
213 1 for my $dir ( @{$self->dirs} ) {
214 1 my $fdir = File::Spec->rel2abs( $dir );
215 find( {
216 follow => 1,
217 no_chdir => 1,
218 wanted => sub {
219 14 ▶ my $file = File::Spec->rel2abs( $File::Find::name );
Subroutine __ANON__: called CC=7 SCAR=20.5
220 14 ▶ return unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 6 8 14
221 8 my ( $volume, $directories, $base ) = File::Spec->splitpath( $file );
222  
223 8 my @tmp = split m/\./, $base;
224  
225 8 my $cur_suffix = pop @tmp;
226 8 ▶ return unless $cur_suffix eq $self->suffix;
Branch: 1 branch
BranchTrueFalseTotal
unless $cur_suffix eq $self->suffix 0 8 8
227 8 my $lang = pop @tmp;
228  
229 8 ▶ pop @tmp if $tmp[-1] eq 'tt'; # словари вида formatting.tt.ru_RU.yaml - имеют имя formatting
Branch: 1 branch
BranchTrueFalseTotal
if $tmp[-1] eq "tt" 0 8 8
230 8 ▶ if ( $tmp[-1] eq 'js') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tmp[-1] eq "js") 0 8 8
231 # словари .js перекрывают одноимённые словари без суффикса
232 # если это нежелательное поведение - словарь с суффиксом .tt перекроет одноимённый .js, и будет доступен только на сервере
233 0 pop @tmp; # словари вида formatting.js.ru_RU.yaml - имеют имя formatting
234 # и не загружаются, если есть аналогичный tt.
235 0 ▶ return if -f File::Spec->catpath( $volume, $directories, join('.', @tmp). ".tt.$lang.$cur_suffix" );
Branch: 1 branch
BranchTrueFalseTotal
if -f "File::Spec"->catpath($volume, $directories, join(".", @tmp) . ".tt.$lang.$cur_suffix") 0 0 0
236 }
237 8 my $dictname = join('.', @tmp);
238 8 my $subdir = File::Spec->catpath( $volume, $directories, '' );
239 8 ▶ if ( $subdir =~ m/\A\Q$fdir\E[\\\/](.+)\z/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($subdir =~ m[\A\Q$fdir\E[\\/](.+)\z]) 6 2 8
240 6 $dictname = "$1$dictname";
241 }
242  
243 8 $self->load_dictionary($dictname, $lang, $file);
244 },
245 1 }, $dir );
246 }
247 1 $self->prepare_to_compile;
248 }
249  
250  
251 sub load_dictionary {
252 8 ▶ my ( $self, $dictname, $lang, $file ) = @_;
Subroutine load_dictionary: called CC=3 SCAR=11.2
Pod documented
253  
254 8 ▶ $self->dictionaries->{$lang} //= {};
Condition100%2/2
$self->dictionaries->{$lang} //= {}
l!l
62
MC/DC100%1/1
$self->dictionaries->{$lang} //= {}
$self->dictionaries->{$lang}
Truth table100%2/2
A
A= $self->dictionaries->{$lang}
Aresult
11
00
255  
256 8 my $yaml = load_yaml( $file );
257  
258 8 _flat_hash_keys( $yaml, "$dictname.", $self->dictionaries->{$lang} );
259  
260 8 ▶ return unless $self->watch;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->watch 8 0 8
261  
262 0 $self->watchers->{$file} = (stat($file))[MTIME_INDEX];
263 }
264  
265  
266 sub phrase_need_compilation {
267 27 ▶ my ( undef, $phrase, $key ) = @_;
Subroutine phrase_need_compilation: called CC=3 SCAR=11.0
Pod documented
268 27 ▶ die "L10N: $key is undef" unless defined $phrase;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $phrase 0 27 27
269 27 ▶ return 1
Condition100%3/3
ref $phrase eq '' && $phrase =~ / (?: \(\( | \#\{ | \\\\ )/x
!ll&&!rl&&r
6615
MC/DC100%2/2
ref $phrase eq '' && $phrase =~ / (?: \(\( | \#\{ | \\\\ )/x
ref $phrase eq '' $phrase =~ / (?: \(\( | \#\{ | \\\\ )/x
Truth table100%3/3
A && B
A= ref $phrase eq ''B= $phrase =~ / (?: \(\( | \#\{ | \\\\ )/x
ABresult
0X0
100
111
270 && ref($phrase) eq ''
271 && $phrase =~ m/ (?: \(\( | \#\{ | \\\\ )/x
272 ;
273 }
274  
275  
276  
277 sub prepare_to_compile {
278 1 ▶ my ( $self ) = @_;
Subroutine prepare_to_compile: called CC=4 SCAR=13.9
Pod documented
279 1 ▶ while ( my ($lang, $dic) = each(%{ $self->{dictionaries} }) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$$self{"dictionaries"};}) 2 1 3
280 2 ▶ while ( my ($key, $value) = each(%$dic) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$dic) 27 2 29
281 27 ▶ if ( $self->phrase_need_compilation( $value, $key ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->phrase_need_compilation($value, $key)) 15 12 27
282 15 $dic->{$key} = \$value; # отложенная компиляция
283 #my $ast = $parser->parse($value, $lang);
284 #$dic->{$key} = $compiler->compile( $ast );
285 }
286 }
287 }
288 1 return 1;
289 }
290  
291  
292 sub detect_locale {
293 4 ▶ my ( $self, $locale ) = @_;
Subroutine detect_locale: called CC=8 SCAR=23.6
Pod documented
294 4 ▶ return $locale if $self->dictionaries->{$locale};
Branch: 1 branch
BranchTrueFalseTotal
if $self->dictionaries->{$locale} 3 1 4
295 1 my @alt_locales = grep { $_ =~ m/\A\Q$locale\E[\-_]/i } keys %{ $self->dictionaries };
296 1 ▶ confess "only one alternative locale allowed: ", join ',', @alt_locales
Branch: 1 branch
BranchTrueFalseTotal
if @alt_locales > 1 0 1 1
297 if @alt_locales > 1;
298  
299 1 my $alt_locale = $alt_locales[0];
300 1 ▶ if ( $alt_locale && $self->dictionaries->{$alt_locale} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($alt_locale and $self->dictionaries->{$alt_locale}) 1 0 1
Condition33%1/3
$alt_locale and $self->dictionaries->{$alt_locale}
!ll&&!rl&&r
001
MC/DC0%0/2
$alt_locale and $self->dictionaries->{$alt_locale}
$alt_locale $self->dictionaries->{$alt_locale}
Truth table33%1/3
A and B
A= $alt_localeB= $self->dictionaries->{$alt_locale}
ABresult
0X0
100
111
301 # сделаем locale dictionary ссылкой на alt locale dictinary.
302 # это ускорит работу всех t с указанием языка типа "ru" вместо локали "ru_RU".
303 1 $self->dictionaries->{$locale} = $self->dictionaries->{$alt_locale};
304  
305 $self->fallback_cache->{$locale} = $self->fallback_cache->{$alt_locale}
306 1 ▶ if exists $self->fallback_cache->{$alt_locale};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->fallback_cache->{$alt_locale} 0 1 1
307  
308 $self->fallbacks->{$locale} = $self->fallbacks->{$alt_locale}
309 1 ▶ if exists $self->fallbacks->{$alt_locale};
Branch: 1 branch
BranchTrueFalseTotal
if exists $self->fallbacks->{$alt_locale} 1 0 1
310  
311 1 return $locale;
312 }
313 0 ▶ return $self->{default_locale} if $self->dictionaries->{ $self->{default_locale} };
Branch: 1 branch
BranchTrueFalseTotal
if $self->dictionaries->{$self->{"default_locale"}} 0 0 0
314 0 confess "bad locale: $locale and bad default_locale: $self->{default_locale}.";
315 }
316  
317  
318 sub set_fallback {
319 1 ▶ my ( $self, $locale, @fallback_locales ) = @_;
Subroutine set_fallback: called CC=4 SCAR=15.2
Pod documented
320 1 ▶ return unless scalar( @fallback_locales );
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @fallback_locales 0 1 1
321  
322 1 $locale = $self->detect_locale( $locale );
323  
324 1 ▶ @fallback_locales = @{ $fallback_locales[0] } if 1
Branch: 1 branch
BranchTrueFalseTotal
if scalar @fallback_locales == 1 and ref $fallback_locales[0] eq "ARRAY" 0 1 1
Condition33%1/3
scalar @fallback_locales == 1 and ref $fallback_locales[0] eq "ARRAY"
!ll&&!rl&&r
010
MC/DC0%0/2
scalar @fallback_locales == 1 and ref $fallback_locales[0] eq "ARRAY"
scalar @fallback_locales == 1 ref $fallback_locales[0] eq "ARRAY"
Truth table33%1/3
A and B
A= scalar @fallback_locales == 1B= ref $fallback_locales[0] eq "ARRAY"
ABresult
0X0
100
111
325 && scalar( @fallback_locales ) == 1
326 && ref( $fallback_locales[0] ) eq 'ARRAY'
327 ;
328  
329 1 $self->fallbacks->{ $locale } = \@fallback_locales;
330 1 delete $self->{fallback_cache}->{ $locale };
331  
332 1 return 1;
333 }
334  
335  
336 sub _flat_hash_keys {
337 35 ▶ my ( $hash, $prefix, $store ) = @_;
Subroutine _flat_hash_keys: called CC=3 SCAR=11.0
338 35 ▶ while ( my ($key, $value) = each(%$hash) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$hash) 58 35 93
339 58 ▶ if (ref($value) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq 'HASH') { } 10 48 58
340 10 _flat_hash_keys( $value, "$prefix$key.", $store );
341 } else {
342 48 $store->{"$prefix$key"} = $value;
343 }
344 }
345 35 return 1;
346 }
347  
348  
349 sub _process_list_items {
350 6 ▶ my ( $r, $locale ) = @_;
Subroutine _process_list_items: called CC=5 SCAR=16.1
351  
352 6 my @compiled_items;
353 6 for my $item ( @{ $r } ) {
354 14 ▶ if ( ref $item eq 'HASH' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $item eq 'HASH') { } 8 6 14
elsif (ref $item ne 'HASH' and defined $item) { } 4 2 6
355 8 push @compiled_items, _process_nested_hash_item( $item, $locale );
356 }
357 ▶ elsif ( ref $item ne 'HASH' && defined $item ) {
Condition66%2/3
ref $item ne "HASH" and defined $item
!ll&&!rl&&r
024
MC/DC50%1/2
ref $item ne "HASH" and defined $item
ref $item ne "HASH" defined $item
Truth table66%2/3
A and B
A= ref $item ne "HASH"B= defined $item
ABresult
0X0
100
111
358 4 push @compiled_items, $compiler->compile( $parser->parse( $item, $locale ) );
359 }
360 else {
361 2 push @compiled_items, $item;
362 }
363 }
364  
365 return sub {
366 6 ▶ my $results = [];
Subroutine __ANON__: called CC=6 SCAR=17.9
367  
368 6 for my $item ( @compiled_items ) {
369 14 ▶ if ( ref( $item ) eq 'CODE' ) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $item eq 'CODE') { } 4 10 14
elsif (ref $item eq 'HASH') { } 8 2 10
370 4 push @{ $results }, $item->(@_);
371 }
372 # Нужно скомпилить значения в хэшрефе
373 elsif ( ref( $item ) eq 'HASH' ) {
374 8 ▶ while ( my ( $key, $value ) = each ( %$item ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$item) 12 8 20
375 12 ▶ if ( ref ($value) eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq "CODE") 4 8 12
376 4 $item->{$key} = $value->(@_);
377 }
378 }
379 8 push @{ $results }, $item;
380 }
381 else {
382 2 push @{ $results }, $item;
383 }
384 }
385  
386 6 return $results;
387 6 };
388 }
389  
390 sub _process_nested_hash_item {
391 8 ▶ my ( $hashref, $locale ) = @_;
Subroutine _process_nested_hash_item: called CC=2 SCAR=6.9
392  
393 8 ▶ while ( my ( $key, $value ) = each ( %$hashref ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$hashref) 12 8 20
394 12 my $compiled_value = $compiler->compile( $parser->parse( $value, $locale ) );
395 12 $hashref->{$key} = $compiled_value;
396 }
397  
398 8 return $hashref;
399 }
400  
401  
402 2 1;
403  
404 __END__
405  
406 =pod
407  
408 =encoding utf-8
409  
410 =head1 NAME
411  
412 Locale::Babelfish - Perl I18n using https://github.com/nodeca/babelfish format.
413  
414 =head1 VERSION
415  
416 version 2.10
417  
418 =head1 DESCRIPTION
419  
420 Библиотека локализации.
421  
422 =head1 NAME
423  
424 Locale::Babelfish
425  
426 =head1 SYNOPSYS
427  
428 package Foo;
429  
430 use Locale::Babelfish ();
431  
432 my $bf = Locale::Babelfish->new( { dirs => [ '/path/to/dictionaries' ] } );
433 print $bf->t('dictionary.firstkey.nextkey', { foo => 'bar' } );
434  
435 More sophisticated example:
436  
437 package Foo::Bar;
438  
439 use Locale::Babelfish ();
440  
441 my $bf = Locale::Babelfish->new( {
442 # configuration
443 dirs => [ '/path/to/dictionaries' ],
444 default_locale => [ 'ru_RU' ], # By default en_US
445 } );
446  
447 # using default locale
448 print $bf->t( 'dictionary.akey' );
449 print $bf->t( 'dictionary.firstkey.nextkey', { foo => 'bar' } );
450  
451 # using specified locale
452 print $bf->t( 'dictionary.firstkey.nextkey', { foo => 'bar' }, 'by_BY' );
453  
454 # using scalar as count or value variable
455 print $bf->t( 'dictionary.firstkey.nextkey', 90 );
456 # same as
457 print $bf->t( 'dictionary.firstkey.nextkey', { count => 90, value => 90 } );
458  
459 # set locale
460 $bf->locale( 'en_US' );
461 print $bf->t( 'dictionary.firstkey.nextkey', { foo => 'bar' } );
462  
463 # Get current locale
464 print $bf->locale;
465  
466 =head1 DICTIONARIES
467  
468 =head2 Phrases Syntax
469  
470 #{varname} Echoes value of variable
471 ((Singular|Plural1|Plural2)):variable Plural form
472 ((Singular|Plural1|Plural2)) Short plural form for "count" variable
473  
474 Example:
475  
476 I have #{nails_count} ((nail|nails)):nails_count
477  
478 or short form
479  
480 I have #{count} ((nail|nails))
481  
482 or with zero and onу plural forms:
483  
484 I have ((=0 no nails|=1 a nail|#{nails_count} nail|#{nails_count} nails)):nails_count
485  
486 =head2 Dictionary file example
487  
488 Module support only YAML format. Create dictionary file like: B<dictionary.en_US.yaml> where
489 C<dictionary> is name of dictionary and C<en_US> - its locale.
490  
491 profile:
492 apps:
493 forums:
494 new_topic: New topic
495 last_post:
496 title : Last message
497 demo:
498 apples: I have #{count} ((apple|apples))
499 list:
500 - some content #{data}
501 - some other content #{data}
502  
503 =head1 DETAILS
504  
505 Словари грузятся при создании экземпляра, сразу в плоской форме
506 $self->{dictionaries}->{ru_RU}->{dictname_key}...
507  
508 Причем все скалярные значения, при необходимости (есть спецсимволы Babelfish),
509 преобразуются в ссылки на скаляры (флаг - "нужно скомпилировать").
510  
511 Метод t_or_undef получает значение по указанному ключу.
512  
513 Если это ссылка на скаляр, то парсит и компилирует строку.
514  
515 Если это ссылка на массив, то работаем со всеми элементами массива как со скалярами,
516 собираем полученные результаты компиляции в новый массив и возвращаем ссылку на этот массив.
517  
518 Результат компиляции либо ссылка на подпрограмму, либо просто строка.
519  
520 Если это ссылка на подпрограмму, мы просто вызываем ее с плоскими параметрами.
521  
522 Если просто строка, то возвращаем её as is.
523  
524 Поддерживается опция watch.
525  
526 =head1 METHODS
527  
528 =over
529  
530 =item locale
531  
532 Если указана локаль, устанавливет её. Если нет - возвращает.
533  
534 =item on_watcher_change
535  
536 Перечитывает все словари.
537  
538 =item look_for_watchers
539  
540 Обновляет словари оп мере необходимости, через L</on_watcher_change>.
541  
542 =item t_or_undef
543  
544 $self->t_or_undef( 'main.key.subkey' , { paaram1 => 1 , param2 => 'test' } , 'ru' );
545  
546 Локализация по ключу.
547  
548 первой частью в ключе $key должен идти словарь, например, main.key
549 параметр языка не обязательный.
550  
551 $params - хэш параметров
552  
553 =item t
554  
555 $self->t( 'main.key.subkey' , { paaram1 => 1 , param2 => 'test' } , 'ru' );
556  
557 Локализация по ключу.
558  
559 первой частью в ключе $key должен идти словарь, например, main.key
560 параметр языка не обязательный.
561  
562 $params - хэш параметров
563  
564 =item has_any_value
565  
566 $self->has_any_value( 'main.key.subkey' );
567  
568 Проверяет есть ли ключ в словаре
569  
570 первой частью в ключе должен идти словарь, например, main.
571  
572 =item load_dictionaries
573  
574 Загружает все yaml словари с диска
575  
576 =item load_dictionary
577  
578 Загружает один yaml словарь с диска
579  
580 =item phrase_need_compilation
581  
582 $self->phrase_need_compilation( $phrase, $key )
583 $class->phrase_need_compilation( $phrase, $key )
584  
585 Определяет, требуется ли компиляция фразы.
586  
587 Используется также при компиляции плюралов (вложенные выражения).
588  
589 =item prepare_to_compile
590  
591 $self->prepare_to_compile()
592  
593 Либо маркирует как refscalar строки в словарях, требующие компиляции,
594 либо просто компилирует их.
595  
596 =item detect_locale
597  
598 $self->detect_locale( $locale );
599  
600 Определяем какой язык будет использован.
601 приоритет $locale, далее default_locale.
602  
603 =item set_fallback
604  
605 $self->set_fallback( 'by_BY', 'ru_RU', 'en_US');
606 $self->set_fallback( 'by_BY', [ 'ru_RU', 'en_US' ] );
607  
608 Для указанной локали устанавливает список локалей, на которые будет производится откат
609 в случае отсутствия фразы в указанной.
610  
611 Например, в вышеуказанных примерах при отсутствии фразы в
612 белорусской локали будет затем искаться фраза в русской локали,
613 затем в англоамериканской.
614  
615 =item _flat_hash_keys
616  
617 _flat_hash_keys( $hash, '', $result );
618  
619 Внутренняя, рекурсивная.
620 Преобразует хэш любой вложенности в строку, где ключи хешей разделены точками.
621  
622 =item _process_list_items
623  
624 _process_list_items( $dictionary_values);
625  
626 Обрабатывает ключи словарей содержащие списки, и оборачивает в функцию для компиляции списка.
627 Поддерживаются вложенные в список плоские хэшрефы
628  
629 =back
630  
631 =head1 AUTHORS
632  
633 =over 4
634  
635 =item *
636  
637 Akzhan Abdulin <akzhan@cpan.org>
638  
639 =item *
640  
641 Igor Mironov <grif@cpan.org>
642  
643 =item *
644  
645 Victor Efimov <efimov@reg.ru>
646  
647 =item *
648  
649 REG.RU LLC
650  
651 =item *
652  
653 Kirill Sysoev <k.sysoev@me.com>
654  
655 =item *
656  
657 Alexandr Tkach <tkach@reg.ru>
658  
659 =back
660  
661 =head1 COPYRIGHT AND LICENSE
662  
663 This software is Copyright (c) 2014 by REG.RU LLC.
664  
665 This is free software, licensed under:
666  
667 The MIT (X11) License
668  
669 =cut
« Babelfish/Phrase/Parser.pm ↑ Summary Babelfish/Phrase/PluralForms.pm »