diff Lib/IMPL/Web/Handler/LocaleHandler.pm @ 360:39842eedd923

language detection from request
author sergey
date Tue, 26 Nov 2013 03:22:44 +0400
parents
children eff7f75a4408
line wrap: on
line diff
--- /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