diff options
Diffstat (limited to 'lib/JWebmail/Plugin/I18N2.pm')
-rw-r--r-- | lib/JWebmail/Plugin/I18N2.pm | 67 |
1 files changed, 62 insertions, 5 deletions
diff --git a/lib/JWebmail/Plugin/I18N2.pm b/lib/JWebmail/Plugin/I18N2.pm index 9c10c8d..8c57ec5 100644 --- a/lib/JWebmail/Plugin/I18N2.pm +++ b/lib/JWebmail/Plugin/I18N2.pm @@ -2,6 +2,59 @@ package JWebmail::Plugin::I18N2; use Mojo::Base 'Mojolicious::Plugin'; +use List::Util 'any'; + + +package JWebmail::Plugin::I18N2::Maketext { + + use JWebmail::I18N; + use File::Basename 'fileparse'; + + sub new { + my $class = shift; + my $conf = @_ == 1 ? shift : {@_}; + + my $lexica = $conf->{directory} || [fileparse(__FILE__)]->[1] . '../I18N'; + + my @languages = keys %{$conf->{languages} // {}}; + + unless (@languages) { + use autodie; + + opendir(my $dh, $lexica); + my @res = grep { /\.pm$/ && -f "$lexica/$_" } readdir $dh; + closedir($dh); + @languages = map { scalar fileparse $_, '.pm' } @res; + } + + my $self = {}; + for (@languages) { + $self->{$_} = JWebmail::I18N->get_handle($_) || die "unable to load language $_"; + } + + if (my $dl = $conf->{default_language}) { + $self->{$dl} = JWebmail::I18N->get_handle($dl) || die "unable to load language $dl"; + } + + return bless $self, $class; + } + + sub languages { + my $self = shift; + if (@_) { + return exists $self->{$_[0]}; + } + return wantarray ? sort keys $self->%* : scalar keys $self->%*; + } + + sub translate { + my $self = shift; + my $lang = shift; + my $phrase = shift; + return $self->{$lang}->maketext($phrase, @_); + } + +} package JWebmail::Plugin::I18N2::Translator { @@ -12,7 +65,6 @@ package JWebmail::Plugin::I18N2::Translator { sub new { my $cls = shift; my $conf = @_ == 1 ? shift : {@_}; - my $self = {}; my @languages = keys %{$conf->{languages} // {}}; @@ -21,6 +73,7 @@ package JWebmail::Plugin::I18N2::Translator { } # load languages + my $self = {}; for my $l (@languages) { if (my $dict = __loadi18n($conf->{directory}, $l)) { $self->{$l} = $dict; @@ -110,11 +163,11 @@ sub register { my $i18n_log = $app->log->context('[' . __PACKAGE__ . ']'); - my $translator = $conf->{translator} || sub { JWebmail::Plugin::I18N2::Translator->new(@_) }; + my $translator = $conf->{translator} || sub { JWebmail::Plugin::I18N2::Maketext->new(@_) }; my $defaultLang = $conf->{default_language} || 'en'; - my $fileLocation = $conf->{directory} && Mojo::File->new($conf->{directory})->is_abs - ? $conf->{directory} - : $app->home->child($conf->{directory} || 'lang'); + my $fileLocation = $conf->{directory} + ? Mojo::File->new($conf->{directory}) + : $app->home->child('lang'); my $t = $translator->( default_language => $defaultLang, @@ -126,6 +179,10 @@ sub register { local $" = ','; $i18n_log->info("loaded languages (@{[$t->languages]})"); + unless (any { $defaultLang eq $_ } $t->languages) { + die "default language '$defaultLang' not loaded"; + } + if (keys $conf->{languages}->%* > $t->languages) { $i18n_log->warn("missing languages"); } |