Mercurial > pub > Impl
changeset 360:39842eedd923
language detection from request
author | sergey |
---|---|
date | Tue, 26 Nov 2013 03:22:44 +0400 |
parents | 833e663796c4 |
children | eff7f75a4408 |
files | Lib/IMPL/Resources.pm Lib/IMPL/Web/Handler/LocaleHandler.pm |
diffstat | 2 files changed, 80 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/Lib/IMPL/Resources.pm Mon Nov 25 02:19:31 2013 +0400 +++ b/Lib/IMPL/Resources.pm Tue Nov 26 03:22:44 2013 +0400 @@ -10,13 +10,16 @@ sub SetLocale { my ($self,$locale) = @_; + $locale =~ tr/\-/_/; + $CurrentLocale = $locale; } sub InvokeInLocale { my ($this,$locale,$code) = @_; - local $CurrentLocale = $locale; + local $CurrentLocale; + $this->SetLocale($locale); eval { &$code() if $code;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Lib/IMPL/Web/Handler/LocaleHandler.pm Tue Nov 26 03:22:44 2013 +0400 @@ -0,0 +1,76 @@ +package IMPL::Web::Handler::LocaleHandler; +use strict; + +use IMPL::Const qw(:prop); +use IMPL::declare { + require => { + Resources => 'IMPL::Resources' + }, + base => [ + 'IMPL::Object' => undef, + 'IMPL::Object::Autofill' => '@_', + 'IMPL::Object::Serializable' => undef + ], + props => [ + locales => PROP_RO | PROP_LIST, + default => PROP_RO + ] +}; + +sub Invoke { + my ($this,$action,$nextHandler) = @_; + + my @matches; + + my $best = [$this->default,0]; + + if(my $header = $action->header('Accept-Language')) { + foreach my $part (split(/\s*,\s*/, $header)) { + my ($lang,$quality) = ($part =~ /([a-z]+(?:\-[a-z]+)*)(?:\s*;\s*q=(0\.[\d]+|1))?/i ); + + $quality ||=1; + + foreach my $tag ($this->locales) { + if ( $tag =~ m/^$lang/i ) { + push @matches, [$tag,$quality]; + } + } + } + + foreach my $match (@matches) { + if ($match->[1] > $best->[1]) { + $best = $match; + } + } + + + } + + if (my $locale = $best->[0]) { + Resources->SetLocale($locale); + } + + return $nextHandler->($action); +} + +1; + +__END__ + +=pod + +=head1 NAME + +C<IMPL::Web::Handler::LocaleHandler> - handles locale for the request + +=head1 SYNOPSIS + +=begin code xml + + <handlers type="ARRAY"> + <item type="IMPL::Web::Handler::LocationHandler"/> + </handlers> + +=end code xml + +=cut \ No newline at end of file