diff options
author | Jannis M. Hoffmann <jannis@fehcom.de> | 2022-11-16 23:11:42 +0100 |
---|---|---|
committer | Jannis M. Hoffmann <jannis@fehcom.de> | 2022-11-16 23:11:42 +0100 |
commit | a52a7d7c27440a7c2716af033a6113abcaa2bd46 (patch) | |
tree | 0b40912e689dfed35306558b3b41e6a98f169c39 /lib/JWebmail/Plugin/I18N2/INI.pm | |
parent | b36eada764601355be4616fb92822ffabdcb1dc8 (diff) |
split I18N2 plugin into multiple files and added translate role
Diffstat (limited to 'lib/JWebmail/Plugin/I18N2/INI.pm')
-rw-r--r-- | lib/JWebmail/Plugin/I18N2/INI.pm | 84 |
1 files changed, 84 insertions, 0 deletions
diff --git a/lib/JWebmail/Plugin/I18N2/INI.pm b/lib/JWebmail/Plugin/I18N2/INI.pm new file mode 100644 index 0000000..29364bb --- /dev/null +++ b/lib/JWebmail/Plugin/I18N2/INI.pm @@ -0,0 +1,84 @@ +package JWebmail::Plugin::I18N2::INI; + +use v5.22; +use warnings; +use utf8; + +use Mojo::File; + +use Config::Tiny; + +use Role::Tiny::With; +with 'JWebmail::Plugin::I18N2::Role'; + + +sub new { + my $cls = shift; + my $conf = @_ == 1 ? shift : {@_}; + + my $self = bless {}, $cls; + + $self->_log($conf->{log} || sub { @_ = $_[0]->() if ref $_[0] eq 'CODE'; local $" = ' '; warn "@_" }); + + my @languages = keys %{$conf->{languages} // {}}; + + unless (@languages) { + @languages = map { s|^.*/(..)\.lang$|$1|r } glob("'$conf->{directory}/*.lang'"); + } + + # load languages + for my $l (@languages) { + if (my $dict = __loadi18n($conf->{directory}, $l)) { + $self->{$l} = $dict; + } + } + + return $self; +} + +sub loaded_languages { grep { $_ !~ /^_/ } keys $_[0]->%* } + +sub translate { + my $self = shift; + my $lang = shift; + my $word = shift; + + my $res = $self->{$lang}{$word}; + unless ($res) { + local $" = ' '; + $self->_log->("missing translation for $lang:'$word' @{[ caller(1) ]}[0..2]"); + } + if (@_) { + $res = sprintf($res, @_); + } + return $res; +} + +sub _log { + my $self = shift; + if (@_) { + $self->{_log} = $_[0]; + return $self; + } + else { + return $self->{_log}; + } +} + +sub __loadi18n { + my $langsubdir = shift; + my $lang = shift; + + my $langFile = "$langsubdir/$lang.lang"; + my $TXT; + + if ( -f $langFile ) { + $TXT = Config::Tiny->read($langFile, 'utf8')->{'_'}; + if ($@) { + die "error reading file $langFile: $@"; + } + } + return $TXT; +} + +1 |